var Coupon = {
    value: '',
    label: null,
    success: null,
    submitButton: null,
    property: 0,

    init: function() {
        Coupon.submitButton = $('#submit-wz_publish');
        Coupon.submitButton.unbind();
        
        Coupon.label   = $('#coupon_label');
        Coupon.success = $('#coupon_label_success');

        $('input[type=\"submit\"][name=\"submit-wz_coupon\"]').unbind('click').click(function(){
            if (!Coupon.isDefined()) {
                Coupon.reject();
                return false;
            }

            Coupon.check();
            return false;
        });
        
        $('input[type=\"submit\"][name=\"cancel-wz_coupon\"]').click(function(){ window.location.reload(); });        
    },

    reject: function() {
        Coupon.lockForRedirect();
        Coupon.label.text(Lang._('No coupon given. Redirecting to PayPal system ...'))
        Coupon.onReject();
    },

    check: function() {
        Coupon.lockForRedirect();
        Coupon.label.text(Lang._('Checking...'));

        $.getJSON(
            '/property/ajax-check-coupon',
            {
                'code' : Coupon.value,
                'property_id' : Coupon.property,
                'invoice': $('input[name="invoice"]').val(),
                'item': $('input[name="item_number"]').val()
            },
            function(response){
                if(response.valid && response.valid === true) {
                    Coupon.success.text(response.message).show();
                    Coupon.label.hide();
                    Coupon.submitButton.hide();
                    Coupon.indicator.hide();

                    Coupon.used();
                } else {
                    Coupon.unlock();
                    Coupon.label.text(response.error).show();
                }
            }
        );
    },

    isDefined: function() {
        Coupon.value = $('#coupon').val();
        return (0 != Coupon.value.length);
    },

    lockForRedirect: function() {
        $('input[type=\"text\"][name=\"coupon\"]').attr('disabled', 'disabled');
        $('input[type=\"submit\"][name=\"submit-wz_coupon\"]').attr('disabled', 'disabled');
        Coupon.indicator.show();
    },

    unlock: function() {
        $('input[type=\"text\"][name=\"coupon\"]').removeAttr('disabled');
        $('input[type=\"submit\"][name=\"submit-wz_coupon\"]').removeAttr('disabled');
        Coupon.label.text('').hide();
        Coupon.indicator.hide();
    },

    indicator: {
        show: function() {
            $('#splash_window_loader').show();
        },

        hide: function() {
            $('#splash_window_loader').hide();
        }
    },

    used: function() {
        $('form').attr('action', '');
        $('#submit-wz_publish').unbind().click();
    },

    onReject: function() {
        setTimeout('Coupon.submitButton.click()', 2000);
    }
};

