/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
var CheckoutSteps = Class.create();
CheckoutSteps.prototype = 
{
	"method": "",
	"payment": "",
	"loadWaiting": false,
	"steps": ['login', 'billing', 'shipping', 'shipping_method', 'payment', 'review'],
	"history": [],
	"forms": {},
	
    "initialize": function(params)
    {
        this.gotoItem = params.gotoItem || function(){};
    },
    
    "init": function(elm, params)
    {
		
		if (!elm)
		{
			return false;
		}
		
		this.container = elm;  
		
        var urls = params.urls;
        this.progressUrl = urls.progress;
        this.reviewUrl = urls.review;
        this.saveMethodUrl = urls.saveMethod;        
        this.failureUrl = urls.failure;
		
		var _this = this;

        // Init des formulaires  
	 	var _initForms = function(params)
	 	{
	 		for(var i=0, len=params.length; i<len; i++)
	 		{
	 			
	 			var oParams = params[i];
	 			if (typeof oParams != "object")
	 			{
	 				continue;
	 			}			
							
				for (var name in oParams)
	 			{
					this.forms[name] = new CheckoutForm[name](this, oParams[name]);
	 			}
	 		}
	 	}
		
		_initForms.call(this, params.formOptions);

		// Gestion du Login
		var buttons = driver.find(elm, ".btn-login");
		for(var i=0, len=buttons.length; i<len; i++)
		{
			driver.addEvent(buttons[i], "click", function(e)
			{
				e.preventDefault();
				_this.setMethod();
			})
		};
        
        // Affichage de la 1ère étape
        this.gotoSection(params.startStep || this.steps[0]);
    },

    "ajaxFailure": function()
    {
        location.href = this.failureUrl;
    },
    
    /*
    // FIXME : cette méthode est un peu cradingue
   "reloadReviewBlock": function()
    {
        var updater = new Ajax.Updater('checkout-review-load', this.reviewUrl, {method: 'get', onFailure: this.ajaxFailure.bind(this)});
    },
    */

    "_disableEnableAll": function(element, isDisabled) 
    {
        element.disabled = isDisabled;
    },

    "getStepElement": function(id)
    {
    	return $("opc-" + id);
    },

    "setLoadWaiting": function(step, keepDisabled) 
    {
        // Activer
    	if (step)
    	{
            if (this.loadWaiting) 
            {
                this.setLoadWaiting(false);
            }
        	driver.addClass(this.container, "loading");
            this._disableEnableAll(this.getStepElement(step), true);
        }
    	
        // Désactiver
    	else if (this.loadWaiting)
    	{
        	driver.removeClass(this.container, "loading");
            this._disableEnableAll(this.getStepElement(this.loadWaiting), false);
            this._disableEnableAll(this.getStepElement(this.history[this.history.length-1]), (keepDisabled ? true : false));
        }
        this.loadWaiting = step;
    },

    "gotoSection": function(section, isBack)
    {
    	var 
    		maxHistory = 6,
    		isBack = isBack || false,
    		elm = this.getStepElement(section)
    	;

    	//_trace("gotoSection")
    	//_trace(elm)
    	//_trace(this.history)
    	
        if (typeof elm == "undefined" || !elm)
        {
        	return false
        }
    	if (this.history.length >= maxHistory)
    	{
    		this.history.shift();
    	}
    	if (!isBack)
    	{
    		this.history.push(section);
    	} 
        this.gotoItem(elm, true);
        
        // Désactiver le loading
    	//driver.removeClass(this.container, "loading");
    },

    /**
     * FIXME : 
     * Automatiser si possible ces méthodes
     * */
    "setMethod": function()
    {
        if ($('login:guest') && $('login:guest').checked) 
        {
            this.method = 'guest';
            var request = new Ajax.Request(
                this.saveMethodUrl,
                {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,
                {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;
        }
    },

    "back": function()
    {
        if (this.loadWaiting) return;
        if (this.history.length > 1)
        {
        	this.history.pop();
        	this.gotoSection(this.history[this.history.length-1], true);
        }
    },

    "setStepResponse": function(response)
    {
    	//_trace("setStepResponse : ", response)
    	
        if (response.update_section) 
        {
        	//_trace("reponse: "+response.update_section.name);
        	// FIXME : ne fctionne pas avec "shipping_method" car il faut chercher l'id avec "shipping-method"
        	//response.update_section.name.replace("_", "-")
        	var elm = $('checkout-'+response.update_section.name+'-load');
        	if (elm)
        	{
        		$('checkout-'+response.update_section.name+'-load').replace(response.update_section.html);
        	}
        }

    	//_trace(response.duplicateBillingInfo);
        
        // FIXME : shipping n'existe plus
        if(response.duplicateBillingInfo || null)
        {
            this.setSameAsBilling(true);
        }

    	//_trace(response.goto_section)
    	
        // Aller à l'étape suivante
        if (response.goto_section) 
        {
            this.gotoSection(response.goto_section);
            return true;
        }
        if (response.redirect) 
        {
            location.href = response.redirect;
            return true;
        }
        return false;
    },

    "linkAddressElm": false,    
    "syncWithBilling": function (flag) 
    {
		var
			formBilling = this.forms["Billing"],
			formShipping = this.forms["Shipping"]
		;
		
		if (!formBilling || !formShipping)
		{
			return false;
		}
		var
			billingAddress = formBilling.form["billing-address-select"],
			shippingAddress = formShipping.form["shipping-address-select"]
		;
		
		// Sélection de l'addresse du Carnet d'adresse
		if (billingAddress)
		{
			formBilling.newAddress(!billingAddress.value);
			shippingAddress.value = billingAddress.value;
		}
		
		// Relie les addresses
    	if (this.linkAddressElm)
    	{
    		this.linkAddressElm.checked = true;
    	}

    	// formShipping : update    	
        if (!billingAddress || !billingAddress.value) 
        {
        	var 
        		elements = formShipping.form.elements,
    			_fieldShippingCountry = formShipping.regionField,
    			_fieldBillingCountry = formBilling.regionField
    		;
        	for(var i=0, len=elements.length; i<len; i++)
        	{
        		var 
        			elm = elements[i],
        			elm0 = formBilling.form[(elm.id || "").replace(/^shipping:/, 'billing:')]
        		;
        		// FIXME : si le champ elm == this.regionField alors charger 
        		// le select région quand on met à jour le pays
        		if (elm == _fieldShippingCountry.countryEl)
        		{
        			_fieldShippingCountry.countryEl.value = _fieldBillingCountry.countryEl.value;
        			_fieldShippingCountry.update(_fieldBillingCountry.countryEl.value);
        		}
        		
        		if (elm0 && typeof elm.value != "undefined")
        		{
        			elm.value = elm0.value;
        		}
        	}
        } 
        /*
        else if (billingAddress && shippingAddress)
        {
        	shippingAddress.value = billingAddress.value;
        }
        */
    },
    
    "setSameAsBilling": function(flag)
    {	
    	if (!this.linkAddressElm)
    	{
    		this.linkAddressElm = this.forms["Shipping"].form["shipping:same_as_billing"];
    	}
    	if (!this.linkAddressElm)
    	{
    		return false;
    	}    	
		this.linkAddressElm.checked = flag
    	if (flag)
    	{
    		this.syncWithBilling();
    	}
    }
}

// billing
var CheckoutForm = Class.create();
CheckoutForm.prototype = 
{
	"name": null,
	"className":
	{
		"disable": "disabled",
		"address-bloc" : "address-form"
	},
	
	"regionField": null,
	"addressElm": null,
	"dataError": "",
	
	"setErrorMessage": function(data)
	{
		var
		 _data = data || false
		;

		if(_data != false) this.dataError += _data+'<br/>';
	},
	
	"putErrorMessage": function()
	{
		var 
		_elm = driver.getElement(this.form, ".error");
		
		// Suppression du message d'erreur
		if (_elm)
		{
		   this.form.removeChild(_elm);
		   _elm = this.createElmError();
		   
		} else { _elm = this.createElmError(); }
		
		driver.putHTML(_elm, this.dataError);
		this.dataError = "";
		
		return;
	},
	
	"createElmError": function()
	{
		_elm = document.createElement("p");
		driver.addClass(_elm, "error");
		this.form.insertBefore(_elm, this.form.firstChild);
		
		return _elm;
	},
    
    "newAddress": function(isDisabled)
    {
		var 
			elm = this.addressElm,
			className = this.className["disable"]
		;

		//_trace("newAddress : " + this.name)
		//_trace(isDisabled)
		
        if (isDisabled) 
        {
            this.resetSelectedAddress(this);
            driver.removeClass(elm, className);
            return;
        }        
        driver.addClass(elm, className);
        
        if (this.name == "shipping")
        {
            this.checkout.setSameAsBilling(false);
        }
        return;
    },

   "resetSelectedAddress": function()
   {	
    	var
    		formBilling = this.checkout.forms["Billing"],
    		field = formBilling.form["billing-address-select"]
    	;
        if (field) 
        {
        	field.value = '';
        }
    },

    "setUseForShipping": function(flag) 
    {
    	if (this.linkAddressElm)
    	{
    		this.linkAddressElm.checked = flag;
    	}
    },

    "save": function()
    {
        var 
	    	checkout = this.checkout,
	    	form = this.form
	    ;
        if (!this.validator)
        {
            this.validator = new Validation(form)
        }

        if (checkout.loadWaiting)
        {
        	return;
        }

        if (this.validator.validate()) 
        {
            checkout.setLoadWaiting(this.name);

            //alert("send Ajax")
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    method: 'post',
                    onComplete: this.onComplete,
                    onSuccess: this.onSave,
                    onFailure: checkout.ajaxFailure.bind(checkout),
                    parameters: Form.serialize(form)
                }
            );
        }
    },
    
    'fillForm': function(transport)
    {
        var values = {};
        if (transport && transport.responseText)
        {
            try
            {
            	values = eval('(' + transport.responseText + ')');
            }
            catch (e)
            {
            	values = {};
            }
        }
        else
        {
            this.resetSelectedAddress();
        }
        
        var elements = this.form.elements;
        for (var name in elements)
        {
            if (!elements[name].id)
            {
            	continue;
            }
            
            var 
            	elm = elements[name],
            	fieldName = elm.id.replace(/^billing:/, '')
            ;
            elm.value = values[fieldName] ? values[fieldName] : '';
            
            
            if (fieldName == 'country_id' && billingForm)
            {
                billingForm.elementChildLoad(elements[name]);
            }
        }
    },

    "resetLoadWaiting": function()
    {
    	if (this.checkout)
    	{
        	this.checkout.setLoadWaiting(false);
    	}
    },

    /**
        This method recieves the AJAX response on success.
        There are 3 options: error, redirect or html with shipping options.
    */
    "nextStep": function(transport)
    {
    	// Vider le message d'erreur
        if (transport && transport.responseText)
        {
            try
            {
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) 
            {
                response = {};
            }
        }
		
        if (response.error)
        {
            if (typeof response.message == 'object') 
			{
			  for(var p in response.message) 
			  {
				  if (typeof response.message[p] == 'object') 
				  {
					  this.setErrorMessage(response.message[p]);
				  } else if(typeof response.message[p] == 'string') {
					  this.setErrorMessage(response.message[p]);
			      }
			  }
			  this.putErrorMessage();
			  
			} else if (typeof response.message == 'string') 
            {
        		this.setErrorMessage(response.message);
        		this.putErrorMessage();
        	} else {
            	this.regionField.update();
        		this.setErrorMessage(response.message.join("\n"));
                //alert(response.message.join("\n"));
        		this.putErrorMessage();
            }
            return false;
        }
    	/*
    	_trace(this.checkout)
    	_trace(this.checkout.setStepResponse)
    	*/
        this.checkout.setStepResponse(response);
        
    },
    
    "init": function(name, oCheckout, params)
    {   
	
		var params = params || {};
		if (typeof params.form == "undefined" || !params.form || typeof name == "undefined" || !name)
		{
			return false;
		}
    	
    	var _this = this;    	
        this.form = params.form;
    	this.name = name; 
    	this.checkout = oCheckout;
		
    	//
    	// Init champ Région
    	// FIXME : mettre cette partie dans Checkout ?!
    	//
    	var
    		elm = document.getElementById(name + ':region_id'),
    		regions = params.countryRegions,
    		defaultValue = params.regionId
    	;
    	
    	if (typeof regions == "object" && elm)
    	{	
			// Comportements
    		this.regionField = new RegionUpdater(
    				document.getElementById(name + ':country_id'),
    				document.getElementById(name + ':region'), 
    				elm, 
    				regions, 
    				undefined, 
    				document.getElementById(name + ':postcode')
    			);
				
    		this.regionField.regionSelectEl.value = defaultValue;
    	}
    	
    	//
    	// Navigation dans le formulaire
    	// FIXME : mettre cette partie dans Checkout ?!
    	//
    	
    	// Aller à l'étape précédente
    	var links = driver.find(this.form, ".back-link");
    	for (var i=0, len=links.length; i<len; i++)
    	{
    		driver.addEvent(links[i], "click", function(e)
    		{
	    		e.preventDefault();
	    		oCheckout.back();
    		});
    	}

    	// Aller à l'étape suivante
    	//_trace("CheckoutForm : init ", this.form)
    	//_trace(_this.save)
        driver.addEvent(this.form, "submit", function(e)
        {
    		e.preventDefault();
        	_this.save();
		});
        
        // Afficher/masquer le champ d'adresse
        var className = this.className["address-bloc"];
        this.addressElm = driver.find(this.form, '.' + className)[0] || null;
        
        // Urls
        this.addressUrl = params.addressUrl;
        this.saveUrl = params.saveUrl;
        this.methodsUrl = params.methodsUrl;
        
        this.onAddressLoad = this.fillForm.bindAsEventListener(this);
        this.onSave = this.nextStep.bindAsEventListener(this);
        this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
    }
}

CheckoutForm["Billing"] = Class.create(CheckoutForm, 
{
	// FIXME : voir pour mettre cette methode dans la fction parente
    initialize: function(oCheckout, params)
    {
	   this.init("billing", oCheckout, params);
    }
});

// shipping
CheckoutForm["Shipping"] = Class.create(CheckoutForm, 
{
    initialize: function(oCheckout, params)
    {
	    this.init("shipping", oCheckout, params);
    },
    
    setRegionValue: function()
    {
        $('shipping:region').value = $('billing:region').value;
    }
});

// shipping method
CheckoutForm["ShippingMethod"] = Class.create(CheckoutForm, 
{
    "initialize": function(oCheckout, params) /*form, saveUrl*/
    {
    	this.init("shipping_method", oCheckout, params);
        this.validator = new Validation(this.form);
    },

    "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 necessary 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(transport)
    {	
    	if (transport && transport.responseText)
        {
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
        }
        if (response.error) 
        {
        	if (typeof response.message == 'object') 
			{
			  for(var p in response.message) 
			  {
				  if (typeof response.message[p] == 'object') 
				  {
					  this.setErrorMessage(response.message[p]);
				  } else if(typeof response.message[p] == 'string') {
					  this.setErrorMessage(response.message[p]);
			      }
			  }
			  this.putErrorMessage();
			  
			} else {
				this.setErrorMessage(response.message);
				this.putErrorMessage();
			}
            return false;
        }
        if (response.update_section) 
        {
        	$('checkout-'+response.update_section.name+'-load').replace(response.update_section.html);
        }
        
        this.checkout.forms["Payment"].initWhatIsCvvListeners();
        
        if (response.goto_section) 
        {
            this.checkout.gotoSection(response.goto_section);
            return;
        }
        
        if (response.payment_methods_html) 
        {
            $('checkout-payment-method-load').replace(response.payment_methods_html);
        }

        checkout.setShippingMethod();
    }
});


// payment
CheckoutForm["Payment"] = Class.create(CheckoutForm, 
{
	/*
    "beforeInitFunc": $H({}),
    "afterInitFunc": $H({}),
    "beforeValidateFunc": $H({}),
    "afterValidateFunc": $H({}),
    "addBeforeInitFunction" : function(code, func) 
    {
        this.beforeInitFunc.set(code, func);
    },
    "beforeInit" : function() 
    {
        (this.beforeInitFunc).each(function(init){
           (init.value)();;
        });
    },
    "addAfterInitFunction" : function(code, func) 
    {
        this.afterInitFunc.set(code, func);
    },
    "afterInit" : function() 
    {
        (this.afterInitFunc).each(function(init){
            (init.value)();
        });
    },
    "addBeforeValidateFunction" : function(code, func) 
    {
        this.beforeValidateFunc.set(code, func);
    },
    "addAfterValidateFunction" : function(code, func) 
    {
        this.afterValidateFunc.set(code, func);
    },
    */
    
    "initialize": function(oCheckout, params) /*form, saveUrl*/
    {
    	this.init("payment", oCheckout, params);
    	
    	/* Init */
    	/*
        this.beforeInit();
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        */

        //payment[method]
        var 
        	elements = Form.getElements(this.form),
        	method = null,
        	_this = this
        ;
        
        // Comportement sur champs radio
        driver.addEvent(this.form, "click", function(e)
		{
        	var 
        		elm = e.target,
        		name = elm.name || ""
        	;
        	if (name == "payment[method]")
        	{
            	_this.switchMethod(elm.value);
        	}
		});
        
        for (var i=0; i<elements.length; i++) 
        {
        	var elm = elements[i];
        	
            if (elm.name=='payment[method]') 
            {
                if (elm.checked) 
                {
                    method = elm.value;
                }
            } 
            else 
            {
            	elm.disabled = true;
            }
            elm.setAttribute('autocomplete','off');
        }
        
        if (method) 
        {
        	_this.switchMethod(method);
        }
        
        /*
        this.afterInit();
        */
    },

    "switchMethod": function(method)
    {    	
        if (this.currentMethod && $('payment_form_'+this.currentMethod)) 
        {
            this.changeVisible(this.currentMethod, true);
        }

        if ($('payment_form_'+method))
        {
            this.changeVisible(method, false);
            $('payment_form_'+method).fire('payment-method:switched', {method_code : method});
        } 
        else 
        {
            //Event fix for payment methods without form like "Check / Money order"
            document.body.fire('payment-method:switched', {method_code : method});
        }
        this.currentMethod = method;
    },

    "changeVisible": function(method, mode) 
    {
        var block = 'payment_form_' + method;
        [block + '_before', block, block + '_after'].each(function(el) 
        {
            element = $(el);
            if (element) 
            {
                element.style.display = (mode) ? 'none' : '';
                element.select('input', 'select', 'textarea').each(function(field) {
                    field.disabled = mode;
                });
            }
        });
    },

    "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;
    },

    "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;
    },

    "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;
    },

    "nextStep": function(transport)
    {
    	if (transport && transport.responseText)
        {
            try
            {
                response = eval('(' + transport.responseText + ')');
            }
            catch (e)
            {
                response = {};
            }
        }
        
        /*
        * if there is an error in payment, need to show error message
        */
        if (response.error) 
        {
            if (response.fields) 
            {
                var fields = response.fields.split(',');
                for (var i=0;i<fields.length;i++) 
                {
                    var field = null;
                    if (field = $(fields[i])) 
                    {
                        Validation.ajaxError(field, response.error);
                    }
                }
                return;
            }

        	this.setErrorMessage(response.error);
        	this.putErrorMessage();
            return;
        }
        this.checkout.setStepResponse(response);
        //this.checkout.setPayment();
    },
 
    initWhatIsCvvListeners: function()
    {
    	//_trace("paiement : initWhatIsCvvListeners")
    	//_trace($$('.cvv-what-is-this'))
        $$('.cvv-what-is-this').each(function(element)
       {
            Event.observe(element, 'click', toggleToolTip);
        });
    }
});

CheckoutForm["Review"] = Class.create(CheckoutForm, 
{
    "isSuccess": false,
    "initialize": function(oCheckout, params) /*saveUrl, successUrl, agreementsForm*/
    {
		this.init("review", oCheckout, params);
        this.successUrl = params.successUrl;
        this.agreementsForm = params.form;
    	_trace("Review : initialize : ", this);
    },

    "save": function()
    {
        var 
	    	checkout = this.checkout,
	    	form =  checkout.forms["Payment"].form;
	    ;

        if (checkout.loadWaiting) return;
        checkout.setLoadWaiting(this.name);

        /**/        
        var params = Form.serialize(form);
        if (this.agreementsForm) 
        {
            params += '&'+Form.serialize(this.agreementsForm);
        }
        /**/

        var request = new Ajax.Request(
            this.saveUrl,
            {
                method: 'post',
                onComplete: this.onComplete,
                onSuccess: this.onSave,
                onFailure: checkout.ajaxFailure.bind(checkout),
                parameters: params
            }
        );
    },

    "nextStep": function(transport)
    {
    	//_trace("Review : nextStep : ", transport.responseText);
        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");
                }
                if (msg)
                {
                	// Mise à jour des données
                	this.setErrorMessage(msg);
                	this.putErrorMessage();
                }
            }
            if (response.update_section) 
            {
                $('checkout-'+response.update_section.name+'-load').replace(response.update_section.html);
            }

            if (response.goto_section) 
            {
                this.checkout.gotoSection(response.goto_section);
            }
        }
    }
});
