Jump to content

Voucher gets removed from cart after saving address on one page guest checkout! PS 1.6.1.1


babyewok

Recommended Posts

I have a one page guest only checkout setup.  When I add a voucher, it is added correctly but then when I add an address, and save, the voucher is removed from the checkout!

 

I have a voucher going live on Friday so need this sorted ASAP!  I can PM the link to the test server to anyone who woudl like to take a look - unless the problem is obvious?

 

Please help!

Link to comment
Share on other sites

I am concerned it may be due to a shipping module that I have installed.  As teh shipping price is supposed to be updated upon address save so it makes sense if an error there is causing the discount to be removed.  This is the cart.php override:

<?php
/**
* 2007-2015 PrestaShop
*
* 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.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 [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
*  @author    MARGO
*  @copyright MARGO
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of Margo
*/

class Cart extends CartCore
{
    protected $freeproductlist;
    protected $fixed;
    protected $fixedunit;
    protected $fsrules;
    
    /**
     * Return package shipping cost
     *
     * @param integer $id_carrier Carrier ID (default : current carrier)
     * @param booleal $use_tax
     * @param Country $default_country
     * @param Array $product_list
     * @param array $product_list List of product concerned by the shipping.
     * If null, all the product of the cart are used to calculate the shipping cost
     *
     * @return float Shipping total
     */
    public function getPackageShippingCost(
        $id_carrier = null,
        $use_tax = true,
        Country $default_country = null,
        $product_list = null,
        $id_zone = null
    ) {
        if ($this->isVirtualCart()) {
            return 0;
        }
        
        if (!$default_country) {
            $default_country = Context::getContext()->country;
        }
        
        //MARGO
        $complete_product_list = $this->getProducts(true);
        //END MARGO
        
        if (is_null($product_list)) {
            $products = $complete_product_list;
        } else {
            $products = $product_list;
        }
        
        //MARGO
        //get products from free shipping products
        $this->fsrules = Tools::jsonDecode(Context::getContext()->cookie->__get('fs_rules'.(int)$this->id));
        //check if the carrier has free shipping rules -> delete products with free shipping
        $fixedShipping = 0;
        if (!empty($id_carrier)) {
            foreach ($this->fsrules as $key => $fsrule) {
                //if rule carrier is the same as the passed carrier
                if ((int)$fsrule->id_carrier == (int)$id_carrier) {
                    //check if shipping has to be 0 always
                    if ($fsrule->allcartfree && $fsrule->freeproductlist != '' && $fsrule->freeproductlist != '0,') {
                        $products = null;
                    } elseif (count($products) > 0) {
                        foreach ($products as $key => $prod) {
                            if (!strpos($fsrule->freeproductlist, ','.$prod['id_product'].',') === false) {
                                unset($products[$key]);
                            }
                        }
                        foreach ($fsrule->fixed as $key => $fixed) {
                            $fixedShipping += $fixed->amount;
                        }
                        foreach ($fsrule->fixedunit as $key => $fixed) {
                            $fixedShipping += ($fixed->amount * $fixed->quantity);
                        }
                    }
                    
                }
            }
        }
        $product_list = $products;
        //END MARGO

        if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
            $address_id = (int)$this->id_address_invoice;
        } elseif (count($product_list)) {
            $prod = current($product_list);
            $address_id = (int)$prod['id_address_delivery'];
        } else {
            $address_id = null;
        }
        if (!Address::addressExists($address_id)) {
            $address_id = null;
        }
        
        $cache_id = 'getPackageShippingCost_'.(int)$this->id.'_'.(int)$address_id.'_'.
        (int)$id_carrier.'_'.(int)$use_tax.'_'.(int)$default_country->id;
        if ($products) {
            foreach ($products as $product) {
                $cache_id .= '_'.(int)$product['id_product'].'_'.(int)$product['id_product_attribute'];
            }
        }
        if (Cache::isStored($cache_id)) {
            return Cache::retrieve($cache_id);
        }
        // Order total in default currency without fees
        $order_total = $this->getOrderTotal(true, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING, $product_list);

        // Start with shipping cost at 0
        $shipping_cost = 0;
        
        //MARGO
        //add fixed shipping cost
        $shipping_cost += $fixedShipping;
        //END MARGO
        
        // If no product added, return 0
        if (!count($products)) {
            Cache::store($cache_id, $shipping_cost);
            return $shipping_cost;
        }

        if (!isset($id_zone)) {
            // Get id zone
            if (!$this->isMultiAddressDelivery()
                && isset($this->id_address_delivery) // Be carefull, id_address_delivery is not usefull one 1.5
                && $this->id_address_delivery
                && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)
            ) {
                $id_zone = Address::getZoneById((int)$this->id_address_delivery);
            } else {
                if (!Validate::isLoadedObject($default_country)) {
                    $default_country = new Country(
                        Configuration::get('PS_COUNTRY_DEFAULT'),
                        Configuration::get('PS_LANG_DEFAULT')
                    );
                }
                $id_zone = (int)$default_country->id_zone;
            }
        }

        if ($id_carrier && !$this->isCarrierInRange((int)$id_carrier, (int)$id_zone)) {
            $id_carrier = '';
        }
        
        if (empty($id_carrier) &&
            $this->isCarrierInRange((int)Configuration::get('PS_CARRIER_DEFAULT'), (int)$id_zone)) {
            $id_carrier = (int)Configuration::get('PS_CARRIER_DEFAULT');
        }
        
        $total_package_without_shipping_tax_inc = $this->getOrderTotal(
            true,
            Cart::BOTH_WITHOUT_SHIPPING,
            $product_list
        );
        if (empty($id_carrier)) {
            if ((int)$this->id_customer) {
                $customer = new Customer((int)$this->id_customer);
                $result = Carrier::getCarriers(
                    (int)Configuration::get('PS_LANG_DEFAULT'),
                    true,
                    false,
                    (int)$id_zone,
                    $customer->getGroups()
                );
                unset($customer);
            } else {
                $result = Carrier::getCarriers((int)Configuration::get('PS_LANG_DEFAULT'), true, false, (int)$id_zone);
            }
            
            foreach ($result as $k => $row) {
                if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                    continue;
                }
                
                if (!isset(self::$_carriers[$row['id_carrier']])) {
                    self::$_carriers[$row['id_carrier']] = new Carrier((int)$row['id_carrier']);
                }
                
                $carrier = self::$_carriers[$row['id_carrier']];

                // Get only carriers that are compliant with shipping method
                if (
                    ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT &&
                    $carrier->getMaxDeliveryPriceByWeight((int)$id_zone) === false)
                    || ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE &&
                    $carrier->getMaxDeliveryPriceByPrice((int)$id_zone) === false)
                ) {
                    unset($result[$k]);
                    continue;
                }

                // If out-of-range behavior carrier is set on "Desactivate carrier"
                if ($row['range_behavior']) {
                    $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight(
                        $row['id_carrier'],
                        $this->getTotalWeight(),
                        (int)$id_zone
                    );

                    $total_order = $total_package_without_shipping_tax_inc;
                    $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice(
                        $row['id_carrier'],
                        $total_order,
                        (int)$id_zone,
                        (int)$this->id_currency
                    );

                    // Get only carriers that have a range compatible with cart
                    if (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT &&
                        !$check_delivery_price_by_weight)
                        || ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE &&
                        !$check_delivery_price_by_price)
                    ) {
                        unset($result[$k]);
                        continue;
                    }
                }
                
                if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                    $shipping = $carrier->getDeliveryPriceByWeight(
                        $this->getTotalWeight($product_list),
                        (int)$id_zone
                    );
                } else {
                    $shipping = $carrier->getDeliveryPriceByPrice(
                        $order_total,
                        (int)$id_zone,
                        (int)$this->id_currency
                    );
                }
                
                //if (!isset($min_shipping_price))
                $min_shipping_price = $shipping;

                if ($shipping <= $min_shipping_price) {
                    $id_carrier = (int)$row['id_carrier'];
                    $min_shipping_price = $shipping;
                }
            }
        }

        if (empty($id_carrier)) {
            $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
        }
        
        if (!isset(self::$_carriers[$id_carrier])) {
            self::$_carriers[$id_carrier] = new Carrier((int)$id_carrier, Configuration::get('PS_LANG_DEFAULT'));
        }
        
        $carrier = self::$_carriers[$id_carrier];

        // No valid Carrier or $id_carrier <= 0 ?
        if (!Validate::isLoadedObject($carrier)) {
            Cache::store($cache_id, 0);
            return 0;
        }

        if (!$carrier->active) {
            Cache::store($cache_id, $shipping_cost);
            return $shipping_cost;
        }

        // Free fees if free carrier
        if ($carrier->is_free == 1) {
            Cache::store($cache_id, 0);
            return 0;
        }

        // Select carrier tax
        if ($use_tax && !Tax::excludeTaxeOption()) {
            $address = Address::initialize((int)$address_id);
            $carrier_tax = $carrier->getTaxesRate($address);
        }

        $configuration = Configuration::getMultiple(array(
            'PS_SHIPPING_FREE_PRICE',
            'PS_SHIPPING_HANDLING',
            'PS_SHIPPING_METHOD',
            'PS_SHIPPING_FREE_WEIGHT'
        ));

        // Free fees
        $free_fees_price = 0;
        if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
            $free_fees_price = Tools::convertPrice(
                (float)$configuration['PS_SHIPPING_FREE_PRICE'],
                Currency::getCurrencyInstance((int)$this->id_currency)
            );
        }
        $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, null, null, false);
        if ($orderTotalwithDiscounts >= (float)($free_fees_price) && (float)($free_fees_price) > 0) {
            Cache::store($cache_id, $shipping_cost);
            return $shipping_cost;
        }

        if (isset($configuration['PS_SHIPPING_FREE_WEIGHT'])
            && $this->getTotalWeight() >= (float)$configuration['PS_SHIPPING_FREE_WEIGHT']
            && (float)$configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
            Cache::store($cache_id, $shipping_cost);
            return $shipping_cost;
        }

        // Get shipping cost using correct method
        if ($carrier->range_behavior) {
            if (!isset($id_zone)) {
                // Get id zone
                if (isset($this->id_address_delivery)
                    && $this->id_address_delivery
                    && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
                    $id_zone = Address::getZoneById((int)$this->id_address_delivery);
                } else {
                    $id_zone = (int)$default_country->id_zone;
                }
            }

            if (
                ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT &&
                !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), (int)$id_zone))
                || ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE &&
                !Carrier::checkDeliveryPriceByPrice(
                    $carrier->id,
                    $total_package_without_shipping_tax_inc,
                    $id_zone,
                    (int)$this->id_currency
                )
            )) {
                $shipping_cost += 0;
            } else {
                if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                    $shipping_cost += $carrier->getDeliveryPriceByWeight(
                        $this->getTotalWeight($product_list),
                        $id_zone
                    );
                } else {
                    // by price
                    $shipping_cost += $carrier->getDeliveryPriceByPrice(
                        $order_total,
                        $id_zone,
                        (int)$this->id_currency
                    );
                }
            }
        } else {
            if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
            } else {
                $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int)$this->id_currency);
            }
        }
        // Adding handling charges
        if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) {
            $shipping_cost += (float)$configuration['PS_SHIPPING_HANDLING'];
        }
        
        // Additional Shipping Cost per product
        foreach ($products as $product) {
            if (!$product['is_virtual']) {
                $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
            }
        }

        $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int)$this->id_currency));

        //get external shipping cost from module
        if ($carrier->shipping_external) {
            $module_name = $carrier->external_module_name;
            $module = Module::getInstanceByName($module_name);

            if (Validate::isLoadedObject($module)) {
                if (array_key_exists('id_carrier', $module)) {
                    $module->id_carrier = $carrier->id;
                }
                if ($carrier->need_range) {
                    if (method_exists($module, 'getPackageShippingCost')) {
                        $shipping_cost = $module->getPackageShippingCost($this, $shipping_cost, $products);
                    } else {
                        $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
                    }
                } else {
                    $shipping_cost = $module->getOrderShippingCostExternal($this);
                }
                
                // Check if carrier is available
                if ($shipping_cost === false) {
                    Cache::store($cache_id, false);
                    return false;
                }
            } else {
                Cache::store($cache_id, false);
                return false;
            }
        }

        // Apply tax
        if ($use_tax && isset($carrier_tax)) {
            $shipping_cost *= 1 + ($carrier_tax / 100);
        }
        
        $shipping_cost = (float)Tools::ps_round((float)$shipping_cost, 2);
        Cache::store($cache_id, $shipping_cost);

        return $shipping_cost;
    }
}



Can anyone see any obvious reason for the voucher to be removed on address save?

Edited by babyewok (see edit history)
Link to comment
Share on other sites

OK, so looking at my order-ops.js, I think actually this is where the issue lies.  This is my file:

/*
* 2007-2015 PrestaShop
*
* 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.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 [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <[email protected]>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
$(document).ready(function(){
    // GUEST CHECKOUT / NEW ACCOUNT MANAGEMENT
    if ((typeof isLogged == 'undefined' || !isLogged) || (typeof isGuest !== 'undefined' && isGuest))
    {
        if (guestCheckoutEnabled && !isLogged && !isGuest)
        {
         /*     $('#opc_account_choice').show();
            $('#opc_account_form, #opc_invoice_address').hide();

            $(document).on('click', '#opc_createAccount',function(e){
                e.preventDefault();
                $('.is_customer_param').show();
                $('#opc_account_form').slideDown('slow');
                $('#is_new_customer').val('1');
                $('#opc_account_choice, #opc_invoice_address').hide();
                if (typeof bindUniform !=='undefined')
                    bindUniform();
            });
            $(document).on('click', '#opc_guestCheckout', function(e){
                e.preventDefault();
                $('.is_customer_param').hide();
                $('#opc_account_form').slideDown('slow');
                $('#is_new_customer').val('0');
                $('#opc_account_choice, #opc_invoice_address').hide();
                $('#new_account_title').html(txtInstantCheckout);
                $('#submitAccount').attr({id : 'submitGuestAccount', name : 'submitGuestAccount'});
                if (typeof bindUniform !=='undefined')
                    bindUniform();
            });
             $('#opc_guestCheckout').click();
        }
        else if (isGuest)
        {*/ isGuest = 1;
            $('.is_customer_param').hide();
            $('#opc_account_form').show();
            $('#is_new_customer').val('0');
            $('#opc_account_choice, #opc_invoice_address').hide();


        }
        else
        { isGuest = 1;
        $('.is_customer_param').hide();
            $('#opc_account_form').show();
            $('#is_new_customer').val('0');
            $('#opc_account_choice, #opc_invoice_address').hide();

        }

        // LOGIN FORM
        $(document).on('click', '#openLoginFormBlock', function(e){
            e.preventDefault();
            $('#openNewAccountBlock').show();
            $(this).hide();
            $('#login_form_content').slideDown('slow');
            $('#new_account_form').slideUp('slow');
        });
        // LOGIN FORM SENDING
        $(document).on('click', '#SubmitLogin', function(e){
            e.preventDefault();
            var that = $(this);
            $.ajax({
                type: 'POST',
                headers: { "cache-control": "no-cache" },
                url: authenticationUrl + '?rand=' + new Date().getTime(),
                async: false,
                cache: false,
                dataType : "json",
                data: 'SubmitLogin=true&ajax=true&email='+encodeURIComponent($('#login_email').val())+'&passwd='+encodeURIComponent($('#login_passwd').val())+'&token=' + static_token ,
                success: function(jsonData)
                {
                    if (jsonData.hasError)
                    {
                        var errors = '<b>'+txtThereis+' '+jsonData.errors.length+' '+txtErrors+':</b><ol>';
                        for(var error in jsonData.errors)
                            //IE6 bug fix
                            if(error !== 'indexOf')
                                errors += '<li>'+jsonData.errors[error]+'</li>';
                        errors += '</ol>';
                        $('#opc_login_errors').html(errors).slideDown('slow');
                    }
                    else
                    {
                        // update token
                        static_token = jsonData.token;
                        updateNewAccountToAddressBlock(that.attr('data-adv-api'));
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus !== 'abort')
                    {
                        error = "TECHNICAL ERROR: unable to send login informations \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
                        if (!!$.prototype.fancybox)
                            $.fancybox.open([
                                {
                                    type: 'inline',
                                    autoScale: true,
                                    minHeight: 30,
                                    content: '<p class="fancybox-error">' + error + '</p>'
                                }
                            ], {
                                padding: 0
                            });
                        else
                            alert(error);
                    }
                }
            });
        });

        // VALIDATION / CREATION AJAX
        $(document).on('click', '#submitAccount, #submitGuestAccount', function(e){
            e.preventDefault();
            $('#opc_new_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeIn('slow');
            var callingFile = '';
            var advApiParam = '';
            var params = '';

            if ($(this).attr('data-adv-api')) {
                advApiParam = '&isAdvApi=1';
            }

            if (parseInt($('#opc_id_customer').val()) == 0)
            {
                callingFile = authenticationUrl;
                params = 'submitAccount=true&';
            }
            else
            {
                callingFile = orderOpcUrl;
                params = 'method=editCustomer&';
            }

            $('#opc_account_form input:visible, #opc_account_form input[type=hidden], textarea').each(function() {
                if ($(this).is('input[type=checkbox]'))
                {
                    if ($(this).is(':checked'))
                        params += encodeURIComponent($(this).attr('name'))+'=1&';
                }
                else if ($(this).is('input[type=radio]'))
                {
                    if ($(this).is(':checked'))
                        params += encodeURIComponent($(this).attr('name'))+'='+encodeURIComponent($(this).val())+'&';
                }
                else
                    params += encodeURIComponent($(this).attr('name'))+'='+encodeURIComponent($(this).val())+'&';
            });

            $('#opc_account_form select:visible').each(function() {
                params += encodeURIComponent($(this).attr('name'))+'='+encodeURIComponent($(this).val())+'&';
            });
            //params += 'customer_lastname='+encodeURIComponent($('#customer_lastname').val())+'&';
            //params += 'customer_firstname='+encodeURIComponent($('#customer_firstname').val())+'&';
            //params += 'alias='+encodeURIComponent($('#alias').val())+'&';
            //params += 'other='+encodeURIComponent($('#other').val())+'&';
            //params += 'is_new_customer='+encodeURIComponent($('#is_new_customer').val())+'&';
            if ( isGuest != undefined)            
            params += 'isGuest='+isGuest+'&';
            // Clean the last &
            params = params.substr(0, params.length-1);

            $.ajax({
                type: 'POST',
                headers: { "cache-control": "no-cache" },
                url: callingFile + '?rand=' + new Date().getTime() + advApiParam,
                async: false,
                cache: false,
                dataType : "json",
                data: 'ajax=true&'+params+'&token=' + static_token ,
                success: function(jsonData)
                {
                    if (jsonData.hasError)
                    {
                        var tmp = '';
                        var i = 0;
                        for(var error in jsonData.errors)
                            //IE6 bug fix
                            if(error !== 'indexOf')
                            {
                                i = i+1;
                                tmp += '<li>'+jsonData.errors[error]+'</li>';
                            }
                        tmp += '</ol>';
                        var errors = '<b>'+txtThereis+' '+i+' '+txtErrors+':</b><ol>'+tmp;
                        $('#opc_account_errors').slideUp('fast', function(){
                            $(this).html(errors).slideDown('slow', function(){
                                $.scrollTo('#opc_account_errors', 800);
                            });
                        });
                    }
                    else
                    {
                        $('#opc_account_errors').slideUp('slow', function(){
                            $(this).html('');
                        });
                    }

                    isGuest = parseInt($('#is_new_customer').val()) == 1 ? 0 : 1;
                    // update addresses id
                    if(jsonData.id_address_delivery !== undefined && jsonData.id_address_delivery > 0)
                        $('#opc_id_address_delivery').val(jsonData.id_address_delivery);
                    if(jsonData.id_address_invoice !== undefined && jsonData.id_address_invoice > 0)
                        $('#opc_id_address_invoice').val(jsonData.id_address_invoice);

                    if (jsonData.id_customer !== undefined && jsonData.id_customer !== 0 && jsonData.isSaved)
                    {
                        // update token
                        static_token = jsonData.token;

                        // It's not a new customer
                        if ($('#opc_id_customer').val() !== '0')
                            if (!saveAddress('delivery'))
                                return false;

                        // update id_customer
                        $('#opc_id_customer').val(jsonData.id_customer);

                        if ($('#invoice_address:checked').length !== 0)
                        {
                            if (!saveAddress('invoice'))
                                return false;
                        }

                        // update id_customer
                        $('#opc_id_customer').val(jsonData.id_customer);

                        // force to refresh carrier list
                        if (isGuest)
                        {
                            isLogged = 1;
                            $('#opc_account_saved').fadeIn('slow');
                            $('#submitAccount').hide();
                            updateAddressSelection(advApiParam);
                        }
                        else
                            updateNewAccountToAddressBlock(advApiParam);
                    }
                    $('#opc_new_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeIn('slow');
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus !== 'abort')
                    {
                        error = "TECHNICAL ERROR: unable to save account \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
                        if (!!$.prototype.fancybox)
                            $.fancybox.open([
                                {
                                    type: 'inline',
                                    autoScale: true,
                                    minHeight: 30,
                                    content: '<p class="fancybox-error">' + error + '</p>'
                                }
                            ], {
                                padding: 0
                            });
                        else
                            alert(error);
                    }
                    $('#opc_new_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeIn('slow')
                }
            });
        });
    }

    bindInputs();

    $('#opc_account_form input,select,textarea').change(function() {
        if ($(this).is(':visible'))
        {
            $('#opc_account_saved').fadeOut('slow');
            $('#submitAccount').show();
        }
    });

    // If the multishipping mode is off assure us the checkbox "I want to specify a delivery address for each products I order." is unchecked.
    $('#multishipping_mode_checkbox').attr('checked', false);
    // If the multishipping mode is on, check the box "I want to specify a delivery address for each products I order.".
    if (typeof(multishipping_mode) !== 'undefined' && multishipping_mode)
    {
        $('#multishipping_mode_checkbox').click();
        $('.addressesAreEquals').hide().find('input').attr('checked', false);
    }
    if (typeof(open_multishipping_fancybox) !== 'undefined' && open_multishipping_fancybox)
        $('#link_multishipping_form').click();
});

function updateCarrierList(json)
{
    var html = json.carrier_block;
    $('#carrier_area').replaceWith(html);
    bindInputs();
    /* update hooks for carrier module */
    $('#HOOK_BEFORECARRIER').html(json.HOOK_BEFORECARRIER);
}

function updatePaymentMethods(json)
{
    $('#HOOK_TOP_PAYMENT').html(json.HOOK_TOP_PAYMENT);
    $('#opc_payment_methods-content #HOOK_PAYMENT').html(json.HOOK_PAYMENT);
}

function updatePaymentMethodsDisplay()
{
    var checked = '';
    if ($('#cgv:checked').length !== 0)
        checked = 1;
    else
        checked = 0;
    $('#opc_payment_methods-overlay').fadeIn('slow', function(){
        $.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            url: orderOpcUrl + '?rand=' + new Date().getTime(),
            async: true,
            cache: false,
            dataType : "json",
            data: 'ajax=true&method=updateTOSStatusAndGetPayments&checked=' + checked + '&token=' + static_token,
            success: function(json)
            {
                updatePaymentMethods(json);
                if (typeof bindUniform !=='undefined')
                    bindUniform();
            }
        });
        $(this).fadeOut('slow');
    });
}

function updateAddressSelection(is_adv_api)
{
    var idAddress_delivery = ($('#opc_id_address_delivery').length == 1 ? $('#opc_id_address_delivery').val() : $('#id_address_delivery').val());
    var idAddress_invoice = ($('#opc_id_address_invoice').length == 1 ? $('#opc_id_address_invoice').val() : ($('#addressesAreEquals:checked').length == 1 ? idAddress_delivery : ($('#id_address_invoice').length == 1 ? $('#id_address_invoice').val() : idAddress_delivery)));

    $('#opc_account-overlay').fadeIn('slow');
    $('#opc_delivery_methods-overlay').fadeIn('slow');
    $('#opc_payment_methods-overlay').fadeIn('slow');

    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: orderOpcUrl + '?rand=' + new Date().getTime(),
        async: true,
        cache: false,
        dataType : "json",
        data: 'allow_refresh=1&ajax=true&method=updateAddressesSelected&id_address_delivery=' + idAddress_delivery +
              '&id_address_invoice=' + idAddress_invoice + '&token=' + static_token +
              (is_adv_api ? '&isAdvApi=1' : ''),
        success: function(jsonData)
        {
            if (jsonData.hasError)
            {
                var errors = '';
                for(var error in jsonData.errors)
                    //IE6 bug fix
                    if(error !== 'indexOf')
                        errors += $('<div />').html(jsonData.errors[error]).text() + "\n";
                if (!!$.prototype.fancybox)
                    $.fancybox.open([
                        {
                            type: 'inline',
                            autoScale: true,
                            minHeight: 30,
                            content: '<p class="fancybox-error">' + errors + '</p>'
                        }
                    ], {
                        padding: 0
                    });
                else
                    alert(errors);
            }
            else
            {
                if (jsonData.refresh)
                {
                    location.reload();
                    return;
                }
                // Update all product keys with the new address id
                $('#cart_summary .address_' + deliveryAddress).each(function() {
                    $(this)
                        .removeClass('address_' + deliveryAddress)
                        .addClass('address_' + idAddress_delivery);
                    $(this).attr('id', $(this).attr('id').replace(/_\d+$/, '_' + idAddress_delivery));
                    if ($(this).find('.cart_unit ul').length > 0 && $(this).find('.cart_unit ul').attr('id').length > 0)
                        $(this).find('.cart_unit ul').attr('id', $(this).find('.cart_unit ul').attr('id').replace(/_\d+$/, '_' + idAddress_delivery));

                    if ($(this).find('.cart_total span').length > 0 && $(this).find('.cart_total span').attr('id').length > 0)
                        $(this).find('.cart_total span').attr('id', $(this).find('.cart_total span').attr('id').replace(/_\d+$/, '_' + idAddress_delivery));

                    if ($(this).find('.cart_quantity_input').length > 0 && $(this).find('.cart_quantity_input').attr('name').length > 0)
                    {
                        var name = $(this).find('.cart_quantity_input').attr('name')+'_hidden';

                        $(this).find('.cart_quantity_input').attr('name', $(this).find('.cart_quantity_input').attr('name').replace(/_\d+$/, '_' + idAddress_delivery));
                        if ($(this).find('[name="' + name + '"]').length > 0)
                            $(this).find('[name="' + name + '"]').attr('name', name.replace(/_\d+_hidden$/, '_' + idAddress_delivery + '_hidden'));
                    }

                    if ($(this).find('.cart_quantity_delete').length > 0 && $(this).find('.cart_quantity_delete').attr('id').length > 0)
                    {
                        $(this).find('.cart_quantity_delete')
                            .attr('id', $(this).find('.cart_quantity_delete').attr('id').replace(/_\d+$/, '_' + idAddress_delivery))
                            .attr('href', $(this).find('.cart_quantity_delete').attr('href').replace(/id_address_delivery=\d+&/, 'id_address_delivery=' + idAddress_delivery+'&'));
                    }

                    if ($(this).find('.cart_quantity_down').length > 0 && $(this).find('.cart_quantity_down').attr('id').length > 0)
                    {
                        $(this).find('.cart_quantity_down')
                            .attr('id', $(this).find('.cart_quantity_down').attr('id').replace(/_\d+$/, '_' + idAddress_delivery))
                            .attr('href', $(this).find('.cart_quantity_down').attr('href').replace(/id_address_delivery=\d+&/, 'id_address_delivery=' + idAddress_delivery+'&'));
                    }

                    if ($(this).find('.cart_quantity_up').length > 0 && $(this).find('.cart_quantity_up').attr('id').length > 0)
                    {
                        $(this).find('.cart_quantity_up')
                            .attr('id', $(this).find('.cart_quantity_up').attr('id').replace(/_\d+$/, '_' + idAddress_delivery))
                            .attr('href', $(this).find('.cart_quantity_up').attr('href').replace(/id_address_delivery=\d+&/, 'id_address_delivery=' + idAddress_delivery+'&'));
                    }
                });

                // Update global var deliveryAddress
                deliveryAddress = idAddress_delivery;
                if (window.ajaxCart !== undefined)
                {
                    $('.cart_block_list dd, .cart_block_list dt').each(function(){
                        if (typeof($(this).attr('id')) != 'undefined')
                            $(this).attr('id', $(this).attr('id').replace(/_\d+$/, '_' + idAddress_delivery));
                    });
                }
                updateCarrierList(jsonData.carrier_data);
                updatePaymentMethods(jsonData);
                updateCartSummary(jsonData.summary);
                updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART);
                updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA);
                if ($('#gift-price').length == 1)
                    $('#gift-price').html(jsonData.gift_price);
                $('#opc_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (textStatus !== 'abort')
            {
                error = "TECHNICAL ERROR: unable to save adresses \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
                if (!!$.prototype.fancybox)
                    $.fancybox.open([
                        {
                            type: 'inline',
                            autoScale: true,
                            minHeight: 30,
                            content: '<p class="fancybox-error">' + error + '</p>'
                        }
                    ], {
                        padding: 0
                    });
                else
                    alert(error);
            }
            $('#opc_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
        }
    });
}

function getCarrierListAndUpdate()
{
    $('#opc_delivery_methods-overlay').fadeIn('slow');
    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: orderOpcUrl + '?rand=' + new Date().getTime(),
        async: true,
        cache: false,
        dataType : "json",
        data: 'ajax=true&method=getCarrierList&token=' + static_token,
        success: function(jsonData)
        {
            if (jsonData.hasError)
            {
                var errors = '';
                for(var error in jsonData.errors)
                    //IE6 bug fix
                    if(error !== 'indexOf')
                        errors += $('<div />').html(jsonData.errors[error]).text() + "\n";
                if (!!$.prototype.fancybox)
                {
                    $.fancybox.open([
                        {
                            type: 'inline',
                            autoScale: true,
                            minHeight: 30,
                            content: '<p class="fancybox-error">' + errors + '</p>'
                        }
                    ], {
                        padding: 0
                    });
                }
                else
                {
                    if (!!$.prototype.fancybox)
                        $.fancybox.open([
                            {
                                type: 'inline',
                                autoScale: true,
                                minHeight: 30,
                                content: '<p class="fancybox-error">' + errors + '</p>'
                            }
                        ], {
                            padding: 0
                        });
                    else
                        alert(errors);
                }
            }
            else
                updateCarrierList(jsonData);
            $('#opc_delivery_methods-overlay').fadeOut('slow');
        }
    });
}

function updateCarrierSelectionAndGift()
{
    var recyclablePackage = 0;
    var gift = 0;
    var giftMessage = '';

    var delivery_option_radio = $('.delivery_option_radio');
    var delivery_option_params = '&';
    $.each(delivery_option_radio, function(i) {
        if ($(this).prop('checked'))
            delivery_option_params += $(delivery_option_radio[i]).attr('name') + '=' + $(delivery_option_radio[i]).val() + '&';
    });
    if (delivery_option_params == '&')
        delivery_option_params = '&delivery_option=&';

    if ($('input#recyclable:checked').length)
        recyclablePackage = 1;
    if ($('input#gift:checked').length)
    {
        gift = 1;
        giftMessage = encodeURIComponent($('#gift_message').val());
    }

    $('#opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: orderOpcUrl + '?rand=' + new Date().getTime(),
        async: true,
        cache: false,
        dataType : "json",
        data: 'ajax=true&method=updateCarrierAndGetPayments' + delivery_option_params + 'recyclable=' + recyclablePackage + '&gift=' + gift + '&gift_message=' + giftMessage + '&token=' + static_token ,
        success: function(jsonData)
        {
            if (jsonData.hasError)
            {
                var errors = '';
                for(var error in jsonData.errors)
                    //IE6 bug fix
                    if(error !== 'indexOf')
                        errors += $('<div />').html(jsonData.errors[error]).text() + "\n";
                if (!!$.prototype.fancybox)
                    $.fancybox.open([
                        {
                            type: 'inline',
                            autoScale: true,
                            minHeight: 30,
                            content: '<p class="fancybox-error">' + errors + '</p>'
                        }
                    ], {
                        padding: 0
                    });
                else
                    alert(errors);
            }
            else
            {
                updateCartSummary(jsonData.summary);
                updatePaymentMethods(jsonData);
                updateHookShoppingCart(jsonData.summary.HOOK_SHOPPING_CART);
                updateHookShoppingCartExtra(jsonData.summary.HOOK_SHOPPING_CART_EXTRA);
                updateCarrierList(jsonData.carrier_data);
                $('#opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
                refreshDeliveryOptions();
                if (typeof bindUniform !=='undefined')
                    bindUniform();
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (textStatus !== 'abort')
                alert("TECHNICAL ERROR: unable to save carrier \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
            $('#opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
        }
    });
}

function confirmFreeOrder()
{
    if ($('#opc_new_account-overlay').length !== 0)
        $('#opc_new_account-overlay').fadeIn('slow');
    else
        $('#opc_account-overlay').fadeIn('slow');
    $('#opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
    $('#confirmOrder').prop('disabled', 'disabled');
    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: orderOpcUrl + '?rand=' + new Date().getTime(),
        async: true,
        cache: false,
        dataType : "html",
        data: 'ajax=true&method=makeFreeOrder&token=' + static_token ,
        success: function(html)
        {
            $('#confirmOrder').prop('disabled', false);
            var array_split = html.split(':');
            if (array_split[0] == 'freeorder')
            {
                if (isGuest)
                    document.location.href = guestTrackingUrl+'?id_order='+encodeURIComponent(array_split[1])+'&email='+encodeURIComponent(array_split[2]);
                else
                    document.location.href = historyUrl;
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (textStatus !== 'abort')
            {
                error = "TECHNICAL ERROR: unable to confirm the order \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
                if (!!$.prototype.fancybox)
                    $.fancybox.open([
                        {
                            type: 'inline',
                            autoScale: true,
                            minHeight: 30,
                            content: '<p class="fancybox-error">' + error + '</p>'
                        }
                    ], {
                        padding: 0
                    });
                else
                    alert(error);
            }
        }
    });
}

function saveAddress(type)
{
    if (type !== 'delivery' && type !== 'invoice')
        return false;

    var params = 'firstname=' + encodeURIComponent($('#firstname' + (type == 'invoice' ? '_invoice' : '')).val()) + '&lastname=' + encodeURIComponent($('#lastname' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#company' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'company=' + encodeURIComponent($('#company' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#vat_number' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'vat_number='+encodeURIComponent($('#vat_number' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#dni' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'dni=' + encodeURIComponent($('#dni' + (type == 'invoice' ? '_invoice' : '')).val())+'&';
    if ($('#address1' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'address1=' + encodeURIComponent($('#address1' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#address2' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'address2=' + encodeURIComponent($('#address2' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#postcode' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'postcode=' + encodeURIComponent($('#postcode' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#city' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'city=' + encodeURIComponent($('#city' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#id_country' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'id_country=' + parseInt($('#id_country' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#id_state' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'id_state=' + encodeURIComponent($('#id_state' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#other' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'other=' + encodeURIComponent($('#other' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#phone' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'phone=' + encodeURIComponent($('#phone' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#phone_mobile' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'phone_mobile=' + encodeURIComponent($('#phone_mobile' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if ($('#alias' + (type == 'invoice' ? '_invoice' : '')).length)
        params += 'alias=' + encodeURIComponent($('#alias' + (type == 'invoice' ? '_invoice' : '')).val()) + '&';
    if (type == 'delivery' && $('#opc_id_address_delivery').val() != undefined && parseInt($('#opc_id_address_delivery').val()) > 0)
        params += 'opc_id_address_delivery=' + parseInt($('#opc_id_address_delivery').val()) + '&';
    if (type == 'invoice' && $('#opc_id_address_invoice').val() != undefined && parseInt($('#opc_id_address_invoice').val()) > 0)
        params += 'opc_id_address_invoice=' + parseInt($('#opc_id_address_invoice').val()) + '&';
    // Clean the last &
    params = params.substr(0, params.length-1);

    var result = false;

    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: addressUrl + '?rand=' + new Date().getTime(),
        async: false,
        cache: false,
        dataType : "json",
        data: 'ajax=true&submitAddress=true&type='+type+'&'+params+'&token=' + static_token,
        success: function(jsonData)
        {
            if (jsonData.hasError)
            {
                var tmp = '';
                var i = 0;
                for(var error in jsonData.errors)
                    //IE6 bug fix
                    if(error !== 'indexOf')
                    {
                        i = i+1;
                        tmp += '<li>'+jsonData.errors[error]+'</li>';
                    }
                tmp += '</ol>';
                var errors = '<b>'+txtThereis+' '+i+' '+txtErrors+':</b><ol>'+tmp;
                $('#opc_account_errors').slideUp('fast', function(){
                    $(this).html(errors).slideDown('slow', function(){
                        $.scrollTo('#opc_account_errors', 800);
                    });
                });
                $('#opc_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
                result = false;
            }
            else
            {
                // update addresses id
                $('input#opc_id_address_delivery').val(jsonData.id_address_delivery);
                $('input#opc_id_address_invoice').val(jsonData.id_address_invoice);
                $('#vouchers').show('slow');
                result = true;
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (textStatus !== 'abort')
            {
                error = "TECHNICAL ERROR: unable to save adresses \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
                if (!!$.prototype.fancybox)
                    $.fancybox.open([
                        {
                            type: 'inline',
                            autoScale: true,
                            minHeight: 30,
                            content: '<p class="fancybox-error">' + error + '</p>'
                        }
                    ], {
                        padding: 0
                    });
                else
                    alert(error);
            }
            $('#opc_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
        }
        });

    return result;
}

function updateNewAccountToAddressBlock(is_adv_api)
{
    $('#opc_account-overlay, #opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');

    $.ajax({
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        url: orderOpcUrl + '?rand=' + new Date().getTime(),
        async: true,
        cache: false,
        dataType : "json",
        data: 'ajax=true&method=getAddressBlockAndCarriersAndPayments&token=' + static_token +
              (is_adv_api ? '&isAdvApi=1' : '') ,
        success: function(json)
        {
            if (json.hasError)
            {
                var errors = '';
                for(var error in json.errors)
                    //IE6 bug fix
                    if(error !== 'indexOf')
                        errors += $('<div />').html(json.errors[error]).text() + "\n";
                alert(errors);
            }
            else
            {
                isLogged = 1;
                if (json.no_address == 1)
                    document.location.href = addressUrl;

                $('#opc_new_account').fadeOut('fast', function() {
                    if (typeof json.formatedAddressFieldsValuesList !== 'undefined' && json.formatedAddressFieldsValuesList )
                        formatedAddressFieldsValuesList = json.formatedAddressFieldsValuesList;
                    if (typeof json.order_opc_adress !== 'undefined' && json.order_opc_adress)
                        $('#opc_new_account').html(json.order_opc_adress);
                    // update block user info

                    // 1.5 template
                    if (json.block_user_info !== '' && $('#header_user').length == 1)
                    {
                        var elt = $(json.block_user_info).find('#header_user_info').html();
                        $('#header_user_info').fadeOut('normal', function() {
                            $(this).html(elt).fadeIn();
                        });
                    }

                    // 1.6 temmplate
                    if (json.block_user_info_nav !== '' && $('.header_user_info').length == 1)
                    {
                        $('.header_user_info').fadeOut('normal', function() {
                            $(this).html(json.block_user_info_nav).fadeIn();
                        });
                    }

                    $(this).fadeIn('fast', function() {
                        if ($('#gift-price').length == 1)
                            $('#gift-price').html(json.gift_price);

                        //After login, the products are automatically associated to an address
                        $.each(json.summary.products, function() {
                            updateAddressId(this.id_product, this.id_product_attribute, '0', this.id_address_delivery);
                        });
                        updateAddressesDisplay(true);
                        if (typeof is_adv_api === 'undefined' || !is_adv_api) {
                            updateCarrierList(json.carrier_data);
                            updateCarrierSelectionAndGift();
                            updatePaymentMethods(json);
                        }
                        $('#opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
                    });
                });
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (textStatus !== 'abort')
                alert("TECHNICAL ERROR: unable to send login informations \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
            $('#opc_delivery_methods-overlay, #opc_payment_methods-overlay').fadeOut('slow');
        }
    });
}

function bindInputs()
{
    // Order message update
    $('#message').blur(function() {
        $('#opc_delivery_methods-overlay').fadeIn('slow');
        $.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            url: orderOpcUrl + '?rand=' + new Date().getTime(),
            async: false,
            cache: false,
            dataType : "json",
            data: 'ajax=true&method=updateMessage&message=' + encodeURIComponent($('#message').val()) + '&token=' + static_token ,
            success: function(jsonData)
            {
                if (jsonData.hasError)
                {
                    var errors = '';
                    for(var error in jsonData.errors)
                        //IE6 bug fix
                        if(error !== 'indexOf')
                            errors += $('<div />').html(jsonData.errors[error]).text() + "\n";
                    alert(errors);
                }
            else
                $('#opc_delivery_methods-overlay').fadeOut('slow');
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus !== 'abort')
                    alert("TECHNICAL ERROR: unable to save message \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
                $('#opc_delivery_methods-overlay').fadeOut('slow');
            }
        });
        if (typeof bindUniform !=='undefined')
            bindUniform();
    });

    // Recyclable checkbox
    $('#recyclable').on('click', function(e){
        updateCarrierSelectionAndGift();
    });

    // Gift checkbox update
    $('#gift').off('click').on('click', function(e){
        if ($('#gift').is(':checked'))
            $('#gift_div').show();
        else
            $('#gift_div').hide();
        updateCarrierSelectionAndGift();
    });

    if ($('#gift').is(':checked'))
        $('#gift_div').show();
    else
        $('#gift_div').hide();

    // Gift message update
    $('#gift_message').on('change', function() {
        updateCarrierSelectionAndGift();
    });

    // Term Of Service (TOS)
    $('#cgv').on('click', function(e){
        updatePaymentMethodsDisplay();
    });
}

function multishippingMode(it)
{
    if ($(it).prop('checked'))
    {
        $('#address_delivery, .address_delivery').hide();
        $('#address_delivery, .address_delivery').parent().hide();
        $('#address_invoice').removeClass('alternate_item').addClass('item');
        $('#multishipping_mode_box').addClass('on');
        $('.addressesAreEquals').hide();
        $('#address_invoice_form').show();

        $(document).on('click', '#link_multishipping_form', function(e){e.preventDefault();});
        $('.address_add a').attr('href', addressMultishippingUrl);

        $(document).on('click', '#link_multishipping_form', function(e){
            if(!!$.prototype.fancybox)
                $.fancybox({
                    'openEffect': 'elastic',
                    'closeEffect': 'elastic',
                    'type': 'ajax',
                    'href':     this.href,
                    'beforeClose': function(){
                        // Reload the cart
                        $.ajax({
                            type: 'POST',
                            headers: { "cache-control": "no-cache" },
                            url: orderOpcUrl + '?rand=' + new Date().getTime(),
                            data: 'ajax=true&method=cartReload',
                            dataType : 'html',
                            cache: false,
                            success: function(data) {
                                $('#cart_summary').replaceWith($(data).find('#cart_summary'));
                                $('.cart_quantity_input').typeWatch({ highlight: true, wait: 600, captureLength: 0, callback: function(val) { updateQty(val, true, this.el); } });
                            }
                        });
                        updateCarrierSelectionAndGift();
                    },
                    'beforeLoad': function(){
                        // Removing all ids on the cart to avoid conflic with the new one on the fancybox
                        // This action could "break" the cart design, if css rules use ids of the cart
                        $.each($('#cart_summary *'), function(it, el) {
                            $(el).attr('id', '');
                        });
                    },
                    'afterLoad': function(){
                        $('.fancybox-inner .cart_quantity_input').typeWatch({ highlight: true, wait: 600, captureLength: 0, callback: function(val) { updateQty(val, false, this.el);} });
                        cleanSelectAddressDelivery();
                        $('.fancybox-outer').append($('<div class="multishipping_close_container"><a id="multishipping-close" class="btn btn-default button button-small" href="#"><span>'+CloseTxt+'</span></a></div>'));
                        $(document).on('click', '#multishipping-close', function(e){
                            var newTotalQty = 0;
                            $('.fancybox-inner .cart_quantity_input').each(function(){
                                newTotalQty += parseInt($(this).val());
                            });
                            if (newTotalQty !== totalQty) {
                                if(!confirm(QtyChanged)) {
                                    return false;
                                }
                            }
                            $.fancybox.close();
                            return false;
                        });
                        totalQty = 0;
                        $('.fancybox-inner .cart_quantity_input').each(function(){
                            totalQty += parseInt($(this).val());
                        });
                    }
                });
        });
    }
    else
    {
        $('#address_delivery, .address_delivery').show();
        $('#address_invoice').removeClass('item').addClass('alternate_item');
        $('#multishipping_mode_box').removeClass('on');
        $('.addressesAreEquals').show();
        if ($('.addressesAreEquals').find('input:checked').length)
            $('#address_invoice_form').hide();
        else
            $('#address_invoice_form').show();
        $('.address_add a').attr('href', addressUrl);

        // Disable multi address shipping
        $.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            url: orderOpcUrl + '?rand=' + new Date().getTime(),
            async: true,
            cache: false,
            data: 'ajax=true&method=noMultiAddressDelivery'
        });

        // Reload the cart
        $.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            url: orderOpcUrl + '?rand=' + new Date().getTime(),
            async: true,
            cache: false,
            data: 'ajax=true&method=cartReload',
            dataType : 'html',
            success: function(data) {
                $('#cart_summary').replaceWith($(data).find('#cart_summary'));
                }
        });
    }
    if (typeof bindUniform !=='undefined')
        bindUniform();
}


Edited by babyewok (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...