
var J2t_One_Checkout = Class.create();
J2t_One_Checkout.prototype = {
    initialize: function(urls){
        this.saveMethodUrl = urls.saveMethod;
        this.failureUrl = urls.failure;
        this.method = '';

        this.shippingUrl = urls.shippingUrl;
        this.saveBilling = urls.saveBilling;
        this.shippingMethod = urls.shippingMethod;
        this.paymentMethod = urls.paymentMethod;
        this.reviewUrl = urls.reviewUrl;
        this.stepProcess=0;
        this.firstLoad = true;
        this.stepShippingComplete = false;
        this.stepPaymentComplete = false;
    },
    ajaxFailure: function(){
        location.href = this.failureUrl;
    },
    setMethod: function(){
        if ($('login:guest') && $('login:guest').checked) {
            this.method = 'guest';
            //alert(this.saveMethodUrl);
            var request = new Ajax.Request(
                this.saveMethodUrl,
                {
                    asynchronous: true,
                    method: 'post',
                    onFailure: this.ajaxFailure.bind(this),
                    parameters: {method:'guest'}
                }
            );
            Element.hide('register-customer-password');
            //this.gotoSection('billing');
        }
        else if($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) {
            this.method = 'register';
            var request = new Ajax.Request(
                this.saveMethodUrl,
                {
                    asynchronous: true,
                    method: 'post',
                    onFailure: this.ajaxFailure.bind(this),
                    parameters: {method:'register'}
                }
            );
            Element.show('register-customer-password');
            //this.gotoSection('billing');
        }
        else{
            /*alert(Translator.translate('Please choose to register or to checkout as a guest'));
            return false;*/
        }
    },
    setLoadWaiting: function(step, keepDisabled) {
        if (step) {
            Element.show(step+'-please-wait');
        } else {
            
        }
        
    },
    reloadReview: function() {
        var reviewUrl = this.reviewUrl;
        if ($('j2t-review-please-wait')){
            $('j2t-review-please-wait').show();

                new Ajax.Request(
                    reviewUrl,
                    {
                        asynchronous: true,
                        method: 'get',
                        onComplete: function(transport) {
                            $('checkout-review-table-wrapper').replace(transport.responseText);
                            $('j2t-review-please-wait').hide();
                        }
                    }
                );

        }
    },

    reloadPayment: function() {
        var paymentUrl = this.paymentMethod;
        this.stepProcess = 0;

        if ($('j2t-payment-please-wait') /*  && $('billing:use_for_shipping_yes').checked */){
            $('j2t-payment-please-wait').show();

            new Ajax.Request(
                paymentUrl,
                {
                    asynchronous: true,
                    method: 'get',
                    onComplete: function(transport) {
                        j2t_one_checkout.stepPaymentComplete = false;
                        $('checkout-payment-method-load').replace(transport.responseText);
                        var j2t_onechekout_payment_checked = false;
                        var j2t_onechekout_payment_form = $('co-payment-form');
                        var j2t_onechekout_payment_radios = j2t_onechekout_payment_form.getInputs('radio');
                        j2t_onechekout_payment_radios.each(function (el, index){
                            if(el.checked){
                                j2t_onechekout_payment_checked = true;
                            }
                        });

                        if (!j2t_onechekout_payment_checked && j2t_onechekout_payment_radios.length > 0){
                            j2t_onechekout_payment_radios[0].checked = true;
                        }

                        j2t_one_checkout.stepProcess++;

                        payment.checkSave();
                        $('j2t-payment-please-wait').hide();

                    }
                }
            );
        }
    },
    reloadShipping: function(){
        var shippingUrl = this.shippingUrl;
        if ($('j2t-shipping-please-wait') /*&& $('billing:use_for_shipping_yes').checked*/){
            $('j2t-shipping-please-wait').show();
            new Ajax.Request(
                shippingUrl,
                {
                    asynchronous: true,
                    method: 'get',
                    onComplete: function(transport) {
                        j2t_one_checkout.stepShippingComplete = false;
                        $('checkout-shipping-method-load').innerHTML = transport.responseText;

                        var j2t_onechekout_shipment_form = $('co-shipping-method-form');
                        var j2t_onechekout_shipment_radios = j2t_onechekout_shipment_form.getInputs('radio');
                        j2t_onechekout_shipment_radios.each(function (el, index){
                            el.stopObserving();
                            el.observe('click', function (event){
                                j2t_one_checkout.stepShippingComplete = false;
                                shippingMethod.saveRefresh();
                                //j2t_one_checkout.reloadProcess();
                            });
                        });

                        if (!j2t_onechekout_checked && j2t_onechekout_shipment_radios.length > 0){
                            j2t_onechekout_shipment_radios[0].checked = true;
                        }

                        j2t_one_checkout.stepProcess++;

                        shippingMethod.save();
                        $('j2t-shipping-please-wait').hide();
                    }
                }
            );
        }
    },

    reloadProcess: function(){
        //I. HIDE PLACE ORDER
        //II. RELOAD SHIPPING_METHOD - PAYMENT - ORDER REVIEW
        this.reloadShipping();

        //III. SAVE SHIPPING_METHOD, PAYMENT (dans les call ajax ci-dessus)
        //IV. RELOAD OVERVIEW (dans les call ajax ci-dessus)
    }
}

var J2t_Billing = Class.create();
J2t_Billing.prototype = {
    initialize: function(form, addressUrl, saveUrl, shippingUrl, paymentUrl, reviewUrl){
        this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        this.addressUrl = addressUrl;
        this.saveUrl = saveUrl;
        //this.onAddressLoad = this.fillForm.bindAsEventListener(this);
        //this.onSave = this.nextStep;
        this.shippingUrl = shippingUrl;
        this.paymentUrl = paymentUrl;
        this.reviewUrl = reviewUrl;
        this.onSave = this.preNextStep.bindAsEventListener(this);
        //this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
    },
    newAddress: function(isNew){
        if (isNew) {
            this.resetSelectedAddress();
            Element.show('billing-new-address-form');
        } else {
            Element.hide('billing-new-address-form');
            this.save();
        }
    },
    resetSelectedAddress: function(){
        var selectElement = $('billing-address-select')
        if (selectElement) {
            selectElement.value='';
        }
    },
    preNextStep: function(transport){
        
        if (transport && transport.responseText){
            //alert(transport.responseText);
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
        }

        if (response.error){
            if ((typeof response.message) == 'string') {
                alert(response.message);
            } else {
                if (window.billingRegionUpdater) {
                    billingRegionUpdater.update();
                }

                alert(response.message.join("\n"));
            }

            return false;
        } else {
            this.nextStep.bind(this);
            //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl);
        }

    },
    nextStep: function(parent){
        //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl);
        //JON
        //alert('test');
        if(!j2t_one_checkout.firstLoad && shipping == undefined){
            j2t_one_checkout.reloadProcess();
            //shipping.checkSave();
        } else {
            shipping.checkSave();
        }
    },
    checkSave: function(){
        var validator = new Validation(this.form, {stopOnFirst: true, focusOnError:false});
        if (!validator.validate()) {
            //validator.reset();
            //alert('ko');
        } else {
            //alert('ok');
            this.save();
        }
    },
    save: function(){
        //if (checkout.loadWaiting!=false) return;

        var validator = new Validation(this.form);
        if (validator.validate()) {
            //checkout.setLoadWaiting('billing');
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    asynchronous: true,
                    method: 'post',
                    /*onComplete: this.onComplete,
                     onSuccess: this.nextStep(this.shippingUrl),*/
                    /*onComplete: this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl),*/
                    onSuccess: this.nextStep.bind(this),
                    /*onFailure: checkout.ajaxFailure.bind(checkout),*/
                    parameters: Form.serialize(this.form)
                }
            );
        }
    }
}

var J2t_Shipping = Class.create();
J2t_Shipping.prototype = {
    initialize: function(form, addressUrl, saveUrl, methodsUrl, paymentUrl, reviewUrl){
        this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        this.addressUrl = addressUrl;
        this.saveUrl = saveUrl;
        this.methodsUrl = methodsUrl;
        this.paymentUrl = paymentUrl;
        this.reviewUrl = reviewUrl;
    },
     newAddress: function(isNew){
        if (isNew) {
            this.resetSelectedAddress();
            Element.show('shipping-new-address-form');
        } else {
            Element.hide('shipping-new-address-form');
            this.save();
        }
        shipping.setSameAsBilling(false);

    },

    resetSelectedAddress: function(){
        var selectElement = $('shipping-address-select')
        if (selectElement) {
            selectElement.value='';
        }
    },

    setSameAsBilling: function(flag) {
        $('shipping:same_as_billing').checked = flag;

        if (flag) {
            this.syncWithBilling();
        }
    },
    syncWithBilling: function () {
        $('billing-address-select') && this.newAddress(!$('billing-address-select').value);
        $('shipping:same_as_billing').checked = true;
        if (!$('billing-address-select') || !$('billing-address-select').value) {
            arrElements = Form.getElements(this.form);
            for (var elemIndex in arrElements) {
                if (arrElements[elemIndex].id) {
                    var sourceField = $(arrElements[elemIndex].id.replace(/^shipping:/, 'billing:'));
                    if (sourceField){
                        arrElements[elemIndex].value = sourceField.value;
                    }
                }
            }
            shippingRegionUpdater.update();
            $('shipping:region_id').value = $('billing:region_id').value;
            $('shipping:region').value = $('billing:region').value;
        } else {
            $('shipping-address-select').value = $('billing-address-select').value;
        }
    },
    nextStep: function(parent){
        //alert(this.methodsUrl);
        //JON
        //alert('test');
        if(!j2t_one_checkout.firstLoad){
            j2t_one_checkout.reloadProcess();
            //shipping.checkSave();
        } else {
            //reload & save shipping method + reload review
            shippingMethod.save();
            //j2t_one_checkout.reloadReview();
        }
    },
    checkSave: function(){
        var validator = new Validation(this.form, {stopOnFirst: true, focusOnError:false});
        if (!validator.validate()) {
            validator.reset();
        } else if ($('billing:use_for_shipping_no').checked) {
            this.save();
        } else {
            j2t_one_checkout.reloadProcess();
        }
    },
    save: function(){
        //if (checkout.loadWaiting!=false) return;
        var validator = new Validation(this.form);
        if (validator.validate()) {
            //checkout.setLoadWaiting('shipping');
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    asynchronous: true,
                    method:'post',
                    /*onComplete: this.onComplete,
                    onSuccess: this.onSave,*/
                    /*onFailure: checkout.ajaxFailure.bind(checkout),*/
                    onSuccess: this.nextStep.bind(this),
                    parameters: Form.serialize(this.form)
                }
            );
        }
    }
}

var J2t_ShippingMethod = Class.create();
J2t_ShippingMethod.prototype = {
    initialize: function(form, saveUrl, shippingUrl, paymentUrl, reviewUrl){
        this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        this.saveUrl = saveUrl;
        this.validator = new Validation(this.form);
        this.shippingUrl = shippingUrl;
        this.paymentUrl = paymentUrl;
        this.reviewUrl = reviewUrl;
        /*this.onSave = this.nextStep.bindAsEventListener(this);
        this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);*/
    },

    validate: function() {
        var methods = document.getElementsByName('shipping_method');
        if (methods.length==0) {
            alert(Translator.translate('Your order cannot be completed at this time as there is no shipping methods available for it. Please make neccessary changes in your shipping address.'));
            return false;
        }

        if(!this.validator.validate()) {
            return false;
        }

        for (var i=0; i<methods.length; i++) {
            if (methods[i].checked) {
                return true;
            }
        }
        alert(Translator.translate('Please specify shipping method.'));
        return false;
    },
    nextStep: function(parent){
        //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl),
        //JON
        //alert('test');
        j2t_one_checkout.stepShippingComplete = true;
    },
    nextStepRefresh: function(parent){
        j2t_one_checkout.reloadReview();
        j2t_one_checkout.stepShippingComplete = true;
    },
    saveRefresh: function(){
        if (this.validate()) {
            //checkout.setLoadWaiting('shipping-method');
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    asynchronous: true,
                    method:'post',
                    onSuccess: this.nextStepRefresh.bind(this), //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl),
                    /*onComplete: this.onComplete,
                    onSuccess: this.onSave,
                    onFailure: checkout.ajaxFailure.bind(checkout),*/
                    parameters: Form.serialize(this.form)
                }
            );
        }

    },
    save: function(){
        //alert(this.saveUrl);
        //if (checkout.loadWaiting!=false) return;
        if (this.validate()) {
            //checkout.setLoadWaiting('shipping-method');
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    asynchronous: true,
                    method:'post',
                    onSuccess: this.nextStep.bind(this), //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl),
                    /*onComplete: this.onComplete,
                    onSuccess: this.onSave,
                    onFailure: checkout.ajaxFailure.bind(checkout),*/
                    parameters: Form.serialize(this.form)
                }
            );
        }
    }
}

var J2t_Payment = Class.create();
J2t_Payment.prototype = {
    beforeInitFunc:$H({}),
    afterInitFunc:$H({}),
    beforeValidateFunc:$H({}),
    afterValidateFunc:$H({}),
    initialize: function(form, saveUrl, shippingUrl, paymentUrl, reviewUrl){
        this.form = form;
        this.saveUrl = saveUrl;
        /*this.onSave = this.nextStep.bindAsEventListener(this);
        this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);*/
        this.shippingUrl = shippingUrl;
        this.paymentUrl = paymentUrl;
        this.reviewUrl = reviewUrl;
    },

    beforeInit : function() {
        (this.beforeInitFunc).each(function(init){
           (init.value)();;
        });
    },

    init : function () {
        this.beforeInit();
        var elements = Form.getElements(this.form);
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        var method = null;
        for (var i=0; i<elements.length; i++) {
            if (elements[i].name=='payment[method]') {
                if (elements[i].checked) {
                    method = elements[i].value;
                }
            } else {
                elements[i].disabled = true;
            }
            elements[i].setAttribute('autocomplete','off');
        }
        if (method) this.switchMethod(method);
        this.afterInit();
    },
    addAfterInitFunction : function(code, func) {
        this.afterInitFunc.set(code, func);
    },

    afterInit : function() {
        (this.afterInitFunc).each(function(init){
            (init.value)();
        });
    },

    checkSave: function(){
        var validator = new Validation(this.form, {stopOnFirst: true, focusOnError:false});
        if (!validator.validate()) {
            validator.reset();
        } else {
            this.save();
        }
    },

    switchMethod: function(method){
        if (this.currentMethod && $('payment_form_'+this.currentMethod)) {
            var form = $('payment_form_'+this.currentMethod);
            form.style.display = 'none';
            var elements = form.select('input', 'select', 'textarea');
            for (var i=0; i<elements.length; i++) elements[i].disabled = true;
        }
        if ($('payment_form_'+method)){
            var form = $('payment_form_'+method);
            form.style.display = '';
            var elements = form.select('input', 'select', 'textarea');
            for (var i=0; i<elements.length; i++) elements[i].disabled = false;
        } else {
            //Event fix for payment methods without form like "Check / Money order"
            document.body.fire('payment-method:switched', {method_code : method});
        }
        this.currentMethod = method;
        //check if checkbox is checked
        //this.save();

        
        var j2t_onechekout_payment_form = $('co-payment-form');
        var j2t_onechekout_payment_inputs = j2t_onechekout_payment_form.getInputs('text', 'password');
        j2t_onechekout_payment_inputs.each(function (el, index){
            //el.onBlur = 'payment.checkSave();';
            el.stopObserving();
            el.observe('blur', function (event){
                payment.checkSave();
            });
        });


        this.checkSave();
    },

    addBeforeValidateFunction : function(code, func) {
        this.beforeValidateFunc.set(code, func);
    },

    beforeValidate : function() {
        var validateResult = true;
        var hasValidation = false;
        (this.beforeValidateFunc).each(function(validate){
            hasValidation = true;
            if ((validate.value)() == false) {
                validateResult = false;
            }
        }.bind(this));
        if (!hasValidation) {
            validateResult = false;
        }
        return validateResult;
    },
    nextStep: function(parent){
        //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl)
        j2t_one_checkout.reloadReview();
        j2t_one_checkout.stepPaymentComplete = true;
    },

    save: function(){
        //if (checkout.loadWaiting!=false) return;
        var validator = new Validation(this.form);
        if (this.validate() && validator.validate()) {
            //checkout.setLoadWaiting('payment');
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    asynchronous: true,
                    method:'post',
                    /*onComplete: this.onComplete,
                    onSuccess: this.onSave,
                    onFailure: checkout.ajaxFailure.bind(checkout),*/
                    onSuccess: this.nextStep.bind(this), //this.nextStep(this.shippingUrl, this.paymentUrl, this.reviewUrl),
                    parameters: Form.serialize(this.form)
                }
            );
        }
    },
    afterValidate : function() {
        var validateResult = true;
        var hasValidation = false;
        (this.afterValidateFunc).each(function(validate){
            hasValidation = true;
            if ((validate.value)() == false) {
                validateResult = false;
            }
        }.bind(this));
        if (!hasValidation) {
            validateResult = false;
        }
        return validateResult;
    },
    validate: function() {
        var result = this.beforeValidate();
        if (result) {
            return true;
        }
        var methods = document.getElementsByName('payment[method]');
        if (methods.length==0) {
            alert(Translator.translate('Your order cannot be completed at this time as there is no payment methods available for it.'));
            return false;
        }
        for (var i=0; i<methods.length; i++) {
            if (methods[i].checked) {
                return true;
            }
        }
        result = this.afterValidate();
        if (result) {
            return true;
        }
        alert(Translator.translate('Please specify payment method.'));
        return false;
    }
}

var J2t_Review = Class.create();
J2t_Review.prototype = {
    initialize: function(saveUrl, successUrl, agreementsForm){
        this.saveUrl = saveUrl;
        this.successUrl = successUrl;
        this.agreementsForm = agreementsForm;
        this.onSave = this.nextStep.bindAsEventListener(this);
        //this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
    },
    save: function(){
        //if (j2t_one_checkout.loadWaiting!=false) return;
        j2t_one_checkout.setLoadWaiting('review');
        var params = Form.serialize(payment.form);
        if (this.agreementsForm) {
            params += '&'+Form.serialize(this.agreementsForm);
        }
        params.save = true;
        var request = new Ajax.Request(
            this.saveUrl,
            {
                asynchronous: true,
                method:'post',
                parameters:params/*,
                onComplete: this.onComplete*/,
                onSuccess: this.onSave/*,
                onFailure: checkout.ajaxFailure.bind(checkout)*/
            }
        );
    },
    nextStep: function(transport){
        if (transport && transport.responseText) {
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
            if (response.redirect) {
                location.href = response.redirect;
                return;
            }
            if (response.success) {
                this.isSuccess = true;
                window.location=this.successUrl;
            }
            else{
                var msg = response.error_messages;
                if (typeof(msg)=='object') {
                    msg = msg.join("\n");
                }
                alert(msg);
            }

            if (response.update_section) {
                $('checkout-'+response.update_section.name+'-load').update(response.update_section.html);
                response.update_section.html.evalScripts();
            }

            if (response.goto_section) {
                checkout.gotoSection(response.goto_section);
                checkout.reloadProgressBlock();
            }
        }
    }
}
