jQuery(window).load(function(){

    /* Shipping description page */
    jQuery('.multilingual_field_select').change(function(){
        jQuery(this).closest('.multilingual_fieldset').find('.multilingual_field').hide();
        jQuery(this).closest('.multilingual_fieldset').find('.multilingual_field_'+jQuery(this).val()).show();
    });

    /* Carrier page */
    jQuery('input[name="refresh"], input[name="refresh_w_override"]').click(function(){
        var input = jQuery("<input>").attr("type", "hidden").attr("name", jQuery(this).attr('name')).val(jQuery(this).attr('name'));
        jQuery('#mainform').append(jQuery(input)).find('input[name="save"]').click();
    });

    jQuery('.woocommerce_page_envoimoinscher-settings a.reload-action').click(function(e){
        e.preventDefault();
        if (jQuery(this).hasClass("initial")) {
            var input = jQuery("<input>").attr("type", "hidden").attr("name", "refresh").val("refresh");
            jQuery('#mainform').append(jQuery(input)).find('input[name="save"]').click();
        } else {
            jQuery(this).colorbox({current:' ', title:' ', inline:true, href:"#carrier-reload-popup", width:"440px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
        }
    });

    jQuery('.woocommerce_page_envoimoinscher-settings a.flush').click(function(e){
        e.preventDefault();
        var input = jQuery("<input>").attr("type", "hidden").attr("name", "flush").val("flush");
        jQuery('#mainform').append(jQuery(input)).find('input[name="save"]').click();
    });

    /* Help page */
    jQuery('#emc_help .category_head').click(function() {
        jQuery(this).find('img').attr('src', img_folder + 'arrow_down.png');
        jQuery(this).next('.questions').slideToggle(function() {
            if(jQuery(this).prev('.category_head').hasClass('closed')){

                jQuery(this).prev('.category_head').removeClass('closed');
                jQuery(this).prev('.category_head').addClass('open');
            }
            else if(jQuery(this).prev('.category_head').hasClass('open')){
                jQuery(this).prev('.category_head').find('img').attr('src', img_folder + 'arrow_right.png');
                jQuery(this).prev('.category_head').removeClass('open');
                jQuery(this).prev('.category_head').addClass('closed');
                jQuery(this).closest('.category').find('.question').removeClass('open');
                jQuery(this).closest('.category').find('.question').addClass('closed');
                jQuery(this).closest('.category').find('.answer').hide();
            }
        });
    });

    jQuery('#emc_help .question').click(function() {
        jQuery(this).next('.answer').slideToggle();

        if(jQuery(this).hasClass('closed')){
            jQuery(this).removeClass('closed');
            jQuery(this).addClass('open');
        }
        else if(jQuery(this).hasClass('open')){
            jQuery(this).removeClass('open');
            jQuery(this).addClass('closed');
        }
    });
});

jQuery(document).ready(function(){

    /* manage pricing rules (carrier settings) */
    jQuery("#emc_pricing .insert").click(function(e) {
        e.preventDefault();
        var carrier_code = jQuery("#emc_pricing").attr("data-carrier");
        var row = jQuery("#emc_pricing tbody tr").length;
        jQuery.ajax({
            url:ajaxurl,
            data: {
                action: 'add_rate_line',
                security: ajax_nonce,
                row: row,
                carrier_code: carrier_code
            },
            dataType:'html',
            timeout:15000,
            success:function(res) {
                jQuery("#emc_pricing tbody").append(res);

                jQuery("#emc_pricing tr.row-"+row+" .multiple-select").multipleSelect({
                    width: 300,
                    selectAllText: translations.selectAll,
                    allSelected: translations.allSelected,
                });

                jQuery("#emc_pricing tr.row-"+row+" .single-select").multipleSelect({
                    single: true,
                    width: "100%"
                });
            }
        });
    });

    jQuery("#emc_pricing .remove").click(function(e) {
        e.preventDefault();
        jQuery("#emc_pricing tr.current").remove();
    });

    jQuery(document).delegate("#emc_pricing .pricing", "change", function() {
        var pricing = jQuery(this).val();
        switch (pricing) {
            case "live":
                jQuery(this).closest('td').next('.flat-rate').find('input').prop("disabled", true);
                jQuery(this).closest('td').prev('.handling-fees').find('input').prop("disabled", false);
                break;

            case "rate":
                jQuery(this).closest('td').next('.flat-rate').find('input').prop("disabled", false);
                jQuery(this).closest('td').prev('.handling-fees').find('input').prop("disabled", false);
                break;

            case "free":
                jQuery(this).closest('td').prev('.handling-fees').find('input').prop("disabled", true);
                jQuery(this).closest('td').next('.flat-rate').find('input').prop("disabled", true);
                break;

            case "deactivate":
                jQuery(this).closest('td').prev('.handling-fees').find('input').prop("disabled", true);
                jQuery(this).closest('td').next('.flat-rate').find('input').prop("disabled", true);
                break;

            default:
                break;
        }
    });

    if (jQuery("#emc_pricing .multiple-select").length > 0) {
        jQuery("#emc_pricing .multiple-select").multipleSelect({
            width: 300,
            selectAllText: translations.selectAll,
            allSelected: translations.allSelected,
        });
    }

    if (jQuery("#emc_pricing .single-select").length > 0) {
        jQuery("#emc_pricing .single-select").multipleSelect({
            single: true,
            width: "100%"
        });
    }

    // convert pricing data to json before submit because of php array limits
    if (jQuery("#emc_pricing").length > 0) {
        jQuery("#mainform").submit(function (e) {
            e.preventDefault();
            var values = [];
            jQuery.each(jQuery('.pricing-item'), function(index, value) {
                var rel = jQuery(this).attr("rel");
                var pricingItem = {
                    'price_from': jQuery(".price-from-"+rel).val(),
                    'price_to': jQuery(".price-to-"+rel).val(),
                    'weight_from': jQuery(".weight-from-"+rel).val(),
                    'weight_to': jQuery(".weight-to-"+rel).val(),
                    'shipping_class': jQuery(".shipping-class-"+rel).val(),
                    'zones': jQuery(".zones-"+rel).val(),
                    'handling_fees': jQuery(".handling-fees-"+rel).val(),
                    'pricing': jQuery(".pricing-"+rel).val(),
                    'flat_rate': jQuery(".flat-rate-"+rel).val()
                };
                values.push(pricingItem);
            });
            // disable inputs to prevent them from being posted in PHP
            jQuery.each(jQuery('.pricing-item input, .pricing-item select'), function(index, value) {
                jQuery(this).prop("disabled", true);
            });
            jQuery("#mainform").append(
                jQuery('<input>', {
                    type: 'hidden',
                    name: 'pricing',
                    val: JSON.stringify(values)
                })
            );

            document.getElementById("mainform").submit();
        });
    }

    /* manage addresses (account settings) */
    if (jQuery('#address-popup-content').length > 0) {
        var fields = [
            {"name": "label", "required": true, type: "text", excludeType: ""},
            {"name": "gender", "required": true, type: "single-select", excludeType: ""},
            {"name": "first_name", "required": true, type: "text", excludeType: ""},
            {"name": "last_name", "required": true, type: "text", excludeType: ""},
            {"name": "company", "required": true, type: "text", excludeType: ""},
            {"name": "address", "required": true, type: "text", excludeType: ""},
            {"name": "zipcode", "required": true, type: "text", excludeType: ""},
            {"name": "city", "required": true, type: "text", excludeType: ""},
            {"name": "phone", "required": true, type: "text", excludeType: ""},
            {"name": "email", "required": true, type: "text", excludeType: ""},
            {"name": "add_info", "required": false, type: "text", excludeType: ""},
            {"name": "dispo_hde", "required": true, type: "single-select", excludeType: ""},
            {"name": "dispo_hle", "required": true, type: "single-select", excludeType: ""},
            {"name": "pickup_day_1", "required": true, type: "single-select", excludeType: ""},
            {"name": "pickup_split", "required": true, type: "single-select", excludeType: ""},
            {"name": "pickup_day_2", "required": true, type: "single-select", excludeType: ""},
            {"name": "shipping_classes", "required": true, type: "multiple-select", excludeType: "default"},
        ];

        var shippingClassesSlugs = [];
        jQuery.each(shippingClasses, function(index, shippingClass) {
            shippingClassesSlugs.push(shippingClass.slug);
        });

        var addressIndex;
        var addressType;
        initMultipleSelect();

        jQuery('button[name="add-address"]').click(function() {
            var valid = true;
            var data = {};
            jQuery.each(fields, function(index, field) {
                // skip shipping class for default address
                if (field.excludeType !== addressType) {
                    // store data
                    if (field.type == "text") {
                        data[field.name] = jQuery('[name="'+field.name+'"]').val();
                    } else if (field.type == "single-select") {
                        data[field.name] = jQuery('[name="'+field.name+'"]').multipleSelect("getSelects")[0];
                    } else if (field.type == "multiple-select") {
                        data[field.name] = jQuery('[name="'+field.name+'"]').multipleSelect("getSelects").join(',');
                    }

                    // validate fields
                    if (field.required === true && ((field.type == "multiple-select" && jQuery('[name="'+field.name+'"]').multipleSelect("getSelects").length === 0) || jQuery('[name="'+field.name+'"]').val() === "")) {
                        if (field.type == "text") {
                            jQuery('[name="'+field.name+'"]').addClass("error");
                        } else {
                            jQuery('[name="'+field.name+'"]').next('.ms-parent').find('button.ms-choice').addClass("error");
                        }
                        jQuery('.required-fields-warning').show();
                        valid = false;
                    }
                }

                // submit form if valid
                if (index == (fields.length-1) && valid === true) {
                    jQuery('.required-fields-warning').hide();
                    jQuery.ajax({
                        url:ajaxurl,
                        data: { action: 'add_address', security: ajax_nonce, address: data, index: addressIndex, type: addressType },
                        dataType:"json",
                        method:"POST",
                        timeout:15000,
                        success:function(res) {
                            if (typeof(res.error) != "undefined") {
                                jQuery.colorbox.close();
                                if (addressIndex === "") {
                                    alert(translations.add_address_fail);
                                } else {
                                    alert(translations.edit_address_fail);
                                }
                            } else {
                                addressLine(res.id, data, addressType, shippingClasses);
                                jQuery.colorbox.close();
                            }
                        }
                    });
                }
            });
        });

        jQuery(document).delegate("#address-popup-content .error", "focus", function() {
            jQuery(this).removeClass("error");
        });

        jQuery(document).delegate("#address-popup-content input", "blur", function() {
            var el = jQuery(this);
            jQuery.each(fields, function(index, field) {
                if (field.required === true && field.name == el.attr("name") && el.val() === "") {
                    jQuery('[name="'+field.name+'"]').addClass("error");
                }
            });

        });

        // new default address
        jQuery('#default-address').delegate("#new-default-address", "click", function() {
            addressIndex = "";
            addressType = "default";
            initPopup("default", "add");
            jQuery(this).colorbox({current:' ', title:' ', inline:true, href:"#address-popup", width:"950px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
        });

        // edit default address
        jQuery('#default-address').delegate(".edit-default-address", "click", function() {
            addressIndex = jQuery(this).closest('.address-block').attr("rel");
            addressType = "default";
            initPopup("default", "edit");

            // set values in modal
            setExistingValues(addressIndex, fields);

            jQuery(this).colorbox({current:' ', title:' ', inline:true, href:"#address-popup", width:"950px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
        });

        // new additional address
        jQuery('#additional-addresses').delegate("#new-additional-address", "click", function() {
            addressIndex = "";
            addressType = "additional";
            initPopup("additional", "add");

            // reset default values
            resetValues(fields, shippingClassesSlugs);

            jQuery(this).colorbox({current:' ', title:' ', inline:true, href:"#address-popup", width:"950px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
        });

        // edit additional address
        jQuery('#additional-addresses').delegate(".edit-additional-address", "click", function() {
            addressIndex = jQuery(this).closest('.address-block').attr("rel");
            addressType = "additional";
            initPopup("additional", "edit");

            // set values in modal
            setExistingValues(addressIndex, fields);

            jQuery(this).colorbox({current:' ', title:' ', inline:true, href:"#address-popup", width:"950px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
        });

        // remove additional address
        jQuery('#additional-addresses').delegate(".remove-additional-address", "click", function() {
            addressIndex = jQuery(this).closest('.address-block').attr("rel");
            addressType = "additional";

            jQuery(this).colorbox({current:' ', title:' ', inline:true, href:"#remove-address-popup", width:"400px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
        });
        jQuery('body').delegate("button[name='remove-address']", "click", function() {
            jQuery.ajax({
                url:ajaxurl,
                data: { action: 'remove_address', security: ajax_nonce, index: addressIndex },
                dataType:"json",
                method:"POST",
                timeout:15000,
                success:function(res) {
                    if (typeof(res.error) != "undefined") {
                        jQuery.colorbox.close();
                        alert(translations.remove_address_fail);
                    } else {
                        removeAddressLine(res.id);
                        jQuery.colorbox.close();
                    }
                }
            });
        });

        // activate cancel buttons
        jQuery('#remove-address-popup button[name="cancel"]').click(function() {
            jQuery.colorbox.close();
        });
        jQuery('#address-popup button[name="cancel"]').click(function() {
            jQuery.colorbox.close();
        });

        // display payment method warning
        jQuery("input[name='EMC_ENV'][value='prod']").colorbox({
            current:' ',
            title:' ',
            inline:true,
            href:"#payment-method-popup",
            width:"450px",
            height:"auto",
            scrolling:false,
            innerWidth:"100%",
            innerHeight:"100%",
            onComplete:function(){
                // select radio
                jQuery(this).prop("checked",true);
            }
        });
        jQuery('body').on("click", "#payment-method-popup button", function() {
            jQuery.colorbox.close();
        });
    }

    /* Simulator page */
    jQuery('button[name="add-product-to-simulator"]').click(function(e) {
        e.preventDefault();
        var productId = jQuery('select[name="product_simulator"]').val();
        var qty = parseInt(jQuery('input[name="qty"]').val());

        // if product not already added in cart, create new product line, else update qty
        if (jQuery('.product-'+productId).length === 0) {
            jQuery.ajax({
                url:ajaxurl,
                data: { action: 'add_product_line', security: ajax_nonce, product_id: productId, qty: qty },
                dataType:'html',
                method: 'POST',
                timeout:15000,
                success:function(res) {
                    jQuery('.cart_totals').before(res);
                    updateCartInfo();
                }
            });
        } else {
            var currentQty = parseInt(jQuery('.product-'+productId+' .qty').html());
            jQuery('.product-'+productId+' .qty').html(currentQty+qty);
            jQuery('.product-'+productId+' .hidden-qty').val(currentQty+qty);
            updateCartInfo();
        }
    });
    jQuery(document).delegate('a.remove-product-from-simulator', 'click', function(e) {
        e.preventDefault();
        jQuery.when(jQuery(this).closest('.product').remove()).then(updateCartInfo());
    });
    if (jQuery("#simulator_cart_content").length !== 0) {
        updateCartInfo();
    }

    /* weight options */
    if (jQuery('.weight_options').length !== 0) {
        jQuery('button[name="add_weight_option_row"]').click(function(e) {
            e.preventDefault();

            // find last number
            var max=0;
            jQuery('.weight_options input[name^="id"]').each(function(index, el) {
                if (parseInt(jQuery(el).val()) > max) {
                    max = parseInt(jQuery(el).val());
                }
                if (index == jQuery('.weight_options input[name^="id"]').length-1) {
                    var id = max+1;
                    var html = '<tr><td>'+id+'</td><td class="dimension"><input type="text" name="weight'+id+'" id="weight'+id+'" value="" /> <span>kg</span></td>';
                    html += '<td class="dimension"><input type="text" name="length'+id+'" id="length'+id+'" value="" /> <span>cm</span></td>';
                    html += '<td class="dimension"><input type="text" name="width'+id+'" id="width'+id+'" value="" /> <span>cm</span></td>';
                    html += '<td class="dimension"><input type="text" name="height'+id+'" id="height'+id+'" value="" class="" /> <span>cm</span>';
                    html += '<input type="hidden" name="id'+id+'" id="id'+id+'" value="'+id+'" /></td></tr>';
                    jQuery('.weight_options tbody').append(html);
                }
            });

            // enable delete row if more than 1 row
            var active_rows = jQuery('.weight_options tbody tr').length - jQuery('.weight_options tbody tr input[type="hidden"][value="ignore"]').length;
            if (active_rows > 1) {
                jQuery('button[name="delete_weight_option_row"]').removeAttr("disabled");
            }
        });

        jQuery('button[name="delete_weight_option_row"]').click(function(e) {
            e.preventDefault();
            // find last number
            var id = jQuery('.weight_options tr.last_selected').find('input[name^="id"]').val();
            var html = '<input type="hidden" name="ignore'+id+'" value="ignore" />';
            jQuery('.weight_options tr.last_selected').find('input[type="hidden"]').after(html);
            jQuery('.weight_options tr.last_selected').hide();

            // transfer carrier logos and parcel splitting limit
            var replaceId;
            // find next active row in lower rows
            jQuery(jQuery('.weight_options tbody tr').get().reverse()).each(function(i) {
                var rowId = jQuery(this).find('input[name^="id"]').val();
                if(parseInt(rowId) >= parseInt(id)) {
                    return true;
                }
                if (typeof(replaceId) != "undefined") {
                    return true;
                }
                if(jQuery(this).find('input[type="hidden"][value="ignore"]').length === 0) {
                    replaceId = rowId;
                }
            });
            // if not found, get upper row
            if (typeof(replaceId) == "undefined") {
                jQuery('.weight_options tbody tr').each(function(i) {
                    var rowId = jQuery(this).find('input[name^="id"]').val();
                    if(parseInt(rowId) <= parseInt(id)) {
                        return true;
                    }
                    if (typeof(replaceId) != "undefined") {
                        return true;
                    }
                    if(jQuery(this).find('input[type="hidden"][value="ignore"]').length === 0) {
                        replaceId = rowId;
                    }
                });
            }
            // now transfer carrier logos and parcel splitting limit
            jQuery('.weight_options tr.last_selected td.carriers div').appendTo(jQuery('.weight_options tr[rel='+replaceId+'] td.carriers'));
            if (jQuery('.weight_options tr.last_selected input[name="EMC_PARCEL_MAX_DIM"]').is(":checked")) {
                jQuery('.weight_options input[name="EMC_PARCEL_MAX_DIM"][value="'+replaceId+'"]').prop( "checked", true );
            }

            // disable delete row if last row
            var active_rows = jQuery('.weight_options tbody tr').length - jQuery('.weight_options tbody tr input[type="hidden"][value="ignore"]').length;
            if (active_rows < 2) {
                jQuery('button[name="delete_weight_option_row"]').attr("disabled", "disabled");
            }
        });
    }

    /* manage float input type */
    jQuery(document).on('input', '.emc_input_decimal', function() {
        var pattern = /^\d*\.?\d*$/;
        if(!pattern.test(jQuery(this).val())) {
            var offset = jQuery(this).position();
            if (jQuery(this).parent().find('.emc_error_tip').length === 0) {
				jQuery(this).after( '<div class="emc_error_tip emc_add_error_tip">' + translations.decimalOnly + '</div>' );
				jQuery(this).parent().find( '.emc_error_tip' )
					.css( 'left', offset.left + jQuery(this).width() - ( jQuery(this).width() / 2 ) - ( jQuery( '.emc_error_tip' ).width() / 2 ) )
					.css( 'top', offset.top + jQuery(this).height() )
					.fadeIn( '100' );
			}
        } else if(jQuery(this).parent().find('.emc_error_tip').length > 0) {
            jQuery(this).parent().find( '.emc_error_tip.emc_add_error_tip').fadeOut( '100', function() { jQuery( this ).remove(); } );
        }
    });

    /* manage integer input type */
    jQuery(document).on('input', '.emc_input_integer', function() {
        var value = jQuery(this).val();
        if(!(Math.floor(value) == value && jQuery.isNumeric(value))) {
            var offset = jQuery(this).position();
            if (jQuery(this).parent().find('.emc_error_tip').length === 0) {
				jQuery(this).after( '<div class="emc_error_tip emc_add_error_tip">' + translations.integerOnly + '</div>' );
				jQuery(this).parent().find( '.emc_error_tip' )
					.css( 'left', offset.left + jQuery(this).width() - ( jQuery(this).width() / 2 ) - ( jQuery( '.emc_error_tip' ).width() / 2 ) )
					.css( 'top', offset.top + jQuery(this).height() )
					.fadeIn( '100' );
			}
        } else if(jQuery(this).parent().find('.emc_error_tip').length > 0) {
            jQuery(this).parent().find( '.emc_error_tip.emc_add_error_tip').fadeOut( '100', function() { jQuery( this ).remove(); } );
        }
    });
});

/* helper functions */
function initPopup(addressType, action) {
    if(addressType == "default") {
        jQuery('#address-popup-content .shipping-classes-block').hide();
    } else {
        jQuery('#address-popup-content .shipping-classes-block').show();
    }

    if (action == "edit") {
        jQuery('#address-popup-content button .add').hide();
        jQuery('#address-popup-content button .edit').show();
    } else {
        jQuery('#address-popup-content button .add').show();
        jQuery('#address-popup-content button .edit').hide();
    }
}

function initMultipleSelect() {
    jQuery("#address-popup-content .gender").multipleSelect({
        single: true,
        width:70,
    });

    jQuery("#address-popup-content .pickup-day").multipleSelect({
        single: true,
        width:70,
    });

    jQuery("#address-popup-content .fromto-1").multipleSelect({
        single: true,
        width:90,
        onClick: function(view) {
            jQuery("#address-popup-content select.fromto-2").multipleSelect("setSelects", [view.value]);
        }
    });

    jQuery("#address-popup-content .fromto-2").multipleSelect({
        single: true,
        width:90,
        onClick: function(view) {
            jQuery("#address-popup-content select.fromto-1").multipleSelect("setSelects", [view.value]);
        }
    });

    jQuery("#address-popup-content .pickup-dispo").multipleSelect({
        single: true,
        width:90,
    });

    jQuery("#address-popup-content select.shipping-classes").multipleSelect({
        width:250,
        maxHeight:500,
        selectAllText: translations.selectAll,
        allSelected: translations.allSelected,
    });
}

function setExistingValues(addressIndex, fields) {
    jQuery.each(jQuery('#address-'+addressIndex+' input[type="hidden"]'), function(index, input) {
        // find relative field
        var field;
        jQuery.each(fields, function(index, value) {
            if (jQuery(input).attr("name") == "hidden-"+value.name) {
                field = value;
            }
        });
        if (field.type == "text") {
            jQuery('#address-popup-content [name="'+field.name+'"]').val(jQuery(input).val());
        } else if (field.type == "single-select" || field.type == "multiple-select") {
            jQuery('#address-popup-content [name="'+field.name+'"]').multipleSelect("setSelects", jQuery(input).val().split(","));

            if (field.name == "pickup_split") {
                jQuery('#address-popup-content select.fromto-2').multipleSelect("setSelects", jQuery(input).val().split(","));
            }
        }
    });
}

function resetValues(fields, shippingClassesSlugs) {
    jQuery.each(fields, function(index, field) {
        if (field.type == "text") {
            jQuery('#address-popup-content [name="'+field.name+'"]').val("");
        } else if (field.type == "single-select" || field.type == "multiple-select") {
            switch(field.name) {
                case 'gender':
                    jQuery('#address-popup-content [name="gender"]').multipleSelect("setSelects", ['M']);
                    break;

                case 'dispo_hde':
                    jQuery('#address-popup-content [name="dispo_hde"]').multipleSelect("setSelects", ['12:00']);
                    break;

                case 'dispo_hle':
                    jQuery('#address-popup-content [name="dispo_hle"]').multipleSelect("setSelects", ['17:00']);
                    break;

                case 'pickup_day_1':
                    jQuery('#address-popup-content [name="pickup_day_1"]').multipleSelect("setSelects", ['2']);
                    break;

                case 'pickup_split':
                    jQuery('#address-popup-content [name="pickup_split"]').multipleSelect("setSelects", ['17']);
                    jQuery('#address-popup-content select.fromto-2').multipleSelect("setSelects", ['17']);
                    break;

                case 'pickup_day_2':
                    jQuery('#address-popup-content [name="pickup_day_2"]').multipleSelect("setSelects", ['3']);
                    break;

                case 'shipping_classes':
                    jQuery('#address-popup-content [name="shipping_classes"]').multipleSelect("setSelects", shippingClassesSlugs);
                    break;
            }
        }
    });
}

function addressLine(addressIndex, addressObject, addressType, shippingClasses) {
    jQuery.ajax({
        url:ajaxurl,
        data: { action: 'format_address', security: ajax_nonce, index: addressIndex },
        dataType:"html",
        method:"POST",
        timeout:15000,
        success:function(res) {
            if (addressType == "default") {
                // hide new address button, show edit
                jQuery('#default-address').html(res);

                /* if no additional address yet, add button (only if there are shipping classes) */
                if (jQuery('#additional-addresses .address-block').length === 0) {
                    if (shippingClasses.length > 0) {
                        jQuery('#additional-addresses').html('<a id="new-additional-address" class="button-primary thickbox">'+translations.new_button+'</a>');
                    } else {
                        jQuery('#additional-addresses').html(translations.no_shipping_class);
                    }
                }
            } else {
                if (jQuery('#address-'+addressIndex).length > 0) {
                    jQuery('#address-'+addressIndex).replaceWith(res);
                } else {
                    jQuery('#new-additional-address').before(res);
                }
            }
        }
    });

}

function removeAddressLine(addressIndex) {
    jQuery('#address-'+addressIndex).remove();
}

function updateCartInfo() {
    if (jQuery("#simulator_cart_content .product").length !== 0) {
        products = [];
        productItems = jQuery('input[name^="product-"]');

        productItems.each(function(index, el) {
            var productId = jQuery(el).val();
            products.push({product_id: productId, qty: jQuery('input[name="qty-'+productId+'"]').val()});

            // launch ajax call on last iteration
            if (index == (productItems.length-1) && products.length !== 0) {
                jQuery.ajax({
                    url:ajaxurl,
                    data: { action: 'get_simulator_cart_info', security: ajax_nonce, products: products },
                    dataType:"json",
                    method:"POST",
                    timeout:15000,
                    success:function(res) {
                        jQuery('#simulator_cart_weight').html(res.cart_weight);
                        jQuery('#simulator_cart_price').html(res.cart_price);
                        jQuery('#simulator_cart_shipping_classes').html(res.cart_shipping_classes.join(', '));
                    }
                });
            }
        });
    } else {
        // initialize cart info
        jQuery('#simulator_cart_weight').html('-');
        jQuery('#simulator_cart_price').html('-');
        jQuery('#simulator_cart_shipping_classes').html('');
    }
}

function colorbox(href){
    jQuery.colorbox({iframe:true, width:"1180px", height:"635px", scrolling:false, innerWidth:"100%", innerHeight:"100%", href:href});
}
