jQuery( function ( $ ) {
	/**
	 * Order Shipping Panel
	 */
	var wc_meta_boxes_order = {

		init: function() {
			$( 'a.edit_dimensions' ).click( this.edit_dimensions );
			$( 'a.edit_shipment_info' ).click( this.edit_shipment_info );
			$( '._insurance' ).click( this.edit_insurance );
			this.edit_insurance(); // calculate insurance price on page display

            // manage changes in proforma quantity
			$( 'input.proforma_qty' ).change(function() {
                var qty = $(this).val();
                var parentItem = $(this).closest('.item');
                if (qty === 0) {
                    parentItem.find('.proforma_editable_fields').hide();
                } else {
                    parentItem.find('.proforma_editable_fields').show();
                }

                // calculate and refresh desc value
                var descValue = 0;
                var parentSuborder = $(this).closest('.suborder');
                parentSuborder.find('.international_shipping').each(function() {
                    $(this).find('input.item-price').each(function(){
                        var itemPrice = $(this).val();
                        var itemQty = $(this).siblings('input.proforma_qty').val();
                        descValue += itemPrice*itemQty;
                    });
                });
                var desc_value_element = parentSuborder.find('.desc_value_replace');

                $.post(ajaxurl, { action: 'format_price', security: ajax_nonce, value: descValue, tax:"notax" }, function (html) {
                    desc_value_element.html( html ).addClass("font-red");
                });
                parentSuborder.find('input._desc_value').val(descValue).addClass("border-red");

                // calculate and refresh 1st parcel weight if it's inferior to the sum of proforma items
                var proformaWeight = 0;
                parentSuborder.find('.international_shipping').each(function() {
                    $(this).find('input.item-weight').each(function(){
                        var itemWeight = $(this).val();
                        var itemQty = $(this).siblings('input.proforma_qty').val();
                        proformaWeight += itemWeight*itemQty;
                    });
                });
                // check current sum
                var currentWeightValue = 0;
                var firstParcelWeight;
                parentSuborder.find('input._dims_weight').each(function(index, el) {
                    currentWeightValue += parseFloat(jQuery(el).val());
                    if (index === 0) {
                        firstParcelWeight = parseFloat(jQuery(el).val());
                    }
                });
                if (currentWeightValue != proformaWeight) {
                    parentSuborder.find('input._dims_1_weight').val(proformaWeight-currentWeightValue+firstParcelWeight).addClass("border-red");
                    parentSuborder.find('span._dims_1_weight').html(proformaWeight-currentWeightValue+firstParcelWeight).parent('span').addClass("font-red");
                }
                parentSuborder.find('.warning_rate').show();
            });
            $('input._desc_value').focus(function() {
                $(this).removeClass("border-red");
                var parentSuborder = $(this).closest('.suborder');
                parentSuborder.find('.desc_value_replace').removeClass("font-red");
            });
            $('input._dims_weight').focus(function() {
                $(this).removeClass("border-red");
                var parentSuborder = $(this).closest('.suborder');
                parentSuborder.find('span.weight').parent('span').removeClass("font-red");
            });
            $('.parcel_dropoff_point input').focus(function() {
                $(this).removeClass("red");
            });
            $('select._address_select').focus(function() {
                $(this).removeClass("border-red");
            });
            $('input._dims_weight, input._dims_height, input._dims_width, input._dims_length, input._pickup_date, input._desc_value, ._emc_carrier, ._address_select, ._insurance, .proforma_qty').change(function() {
                var parentSuborder = $(this).closest('.suborder');
                parentSuborder.find('.warning_rate').show();
                parentSuborder.find('.send-shipment').attr("disabled", "disabled");
            });
            $('.send-shipment').click(function() {
                jQuery('.send-shipment').attr("disabled", "disabled");
                jQuery(this).hide();
                jQuery(this).prev('.sending').show();
            });
            $('._emc_carrier, ._address_select').change(function() {
                var parentSuborder = $(this).closest('.suborder');
                var carrier = parentSuborder.find('select._emc_carrier').val();
                var address = parentSuborder.find('select._address_select').val();
                var suborder_key = parentSuborder.attr("data-suborder");
                if (carrier !== "" && address !== "") {
                    // change dropoff map link
                    $.ajax({
                        url:ajaxurl,
                        data: { action: 'get_relay_map_link', security: ajax_nonce, type:'dropoff', carrier_code: carrier, address_id: address, suborder_key: suborder_key },
                        dataType:'json',
                        timeout:15000,
                        method: 'POST',
                        success:function(res) {
                            if (res !== false) {
                                parentSuborder.find('.parcel_dropoff_point a').attr("href", res);
                            }
                        }
                    });

                    // change pickup map link
                    $.ajax({
                        url:ajaxurl,
                        data: { action: 'get_relay_map_link', security: ajax_nonce, type:'pickup', carrier_code: carrier, order_id: jQuery("#post_ID").val(), suborder_key: suborder_key },
                        dataType:'json',
                        timeout:15000,
                        method: 'POST',
                        success:function(res) {
                            if (res !== false) {
                                parentSuborder.find('.parcel_pickup_point a').attr("href", res);
                            }
                        }
                    });

                    // get dropoff point
                    $.ajax({
                        url:ajaxurl,
                        data: { action: 'get_parcel_point', security: ajax_nonce, type:'dropoff', carrier_code: carrier, address_id: address, order_id: jQuery("#post_ID").val(), suborder_key: suborder_key },
                        dataType:'json',
                        timeout:15000,
                        method: 'POST',
                        success:function(res) {
                            // if carrier has no dropoff point, hide fields
                            if (res === false) {
                                parentSuborder.find('.parcel_dropoff_point').hide();
                            } else {
                                parentSuborder.find('.parcel_dropoff_point').show();
                                parentSuborder.find('.parcel_dropoff_point .field_replace').html(res).addClass("red");
                                parentSuborder.find('.parcel_dropoff_point .input_replace').val(res).addClass("red");
                            }
                        }
                    });

                    // get pickup point
                    $.ajax({
                        url:ajaxurl,
                        data: { action: 'get_parcel_point', security: ajax_nonce, type:'pickup', carrier_code: carrier, order_id: jQuery("#post_ID").val(), suborder_key: suborder_key },
                        dataType:'json',
                        timeout:15000,
                        method: 'POST',
                        success:function(res) {
                            // if carrier has no pickup point, hide fields
                            if (res === false) {
                                parentSuborder.find('.parcel_pickup_point').hide();
                            } else {
                                parentSuborder.find('.parcel_pickup_point').show();
                                parentSuborder.find('.parcel_pickup_point .field_replace').html(res).addClass("red");
                                parentSuborder.find('.parcel_pickup_point .input_replace').val(res).addClass("red");
                            }
                        }
                    });
                }
            });

            $( 'a.edit_item_international' ).click(this.edit_proforma);
		},

		edit_dimensions: function( e ) {
			e.preventDefault();
			$( this ).hide();
			$( this ).closest( '.order_shipping_column' ).find( 'div.dimensions' ).hide();
			$( this ).closest( '.order_shipping_column' ).find( 'div.edit_dimensions' ).show();
		},

		edit_shipment_info: function( e ) {
			e.preventDefault();
			$( this ).hide();
			$( this ).closest( '.order_shipping_column' ).find( 'div.shipment_info' ).hide();
			$( this ).closest( '.order_shipping_column' ).find( 'div.edit_shipment_info' ).show();
		},

		edit_proforma: function( e ) {
			e.preventDefault();
            var parentItem = $(this).closest('.item');
			parentItem.find( 'div.proforma' ).hide();
			parentItem.find('.edit_proforma').show();
		},

		edit_insurance: function() {
            $('._insurance').each(function(index, el) {
                var current_rate, display_rate_element, insurance_rate, sum;
                if( $(el).attr( "checked" ) == "checked" ) {
                    $(el).closest( '.order_shipping_column' ).find( '.edit_insurance' ).show();

                    current_rate = parseFloat($(el).closest( '.suborder' ).find( '.current_rate' ).html());
                    insurance_rate = parseFloat($(el).closest( '.order_shipping_column' ).find( '.insurance_rate_unformatted' ).html());
                    sum = (current_rate + insurance_rate).toFixed(2);
                    display_rate_element = $(el).closest( '.suborder' ).find( ".display_rate" );

                    $.post(ajaxurl, { action: 'format_price', security: ajax_nonce, value: sum, tax:"notax" }, function (html) {
                        display_rate_element.html( html );
                    });
                }
                else{
                    $(el).closest( '.order_shipping_column' ).find( '.edit_insurance' ).hide();

                    current_rate = parseFloat($(el).closest( '.suborder' ).find( '.current_rate' ).html());
                    display_rate_element = $(el).closest( '.suborder' ).find( ".display_rate" );

                    $.post(ajaxurl, { action: 'format_price', security: ajax_nonce, value: current_rate, tax:"notax" }, function (html) {
                        display_rate_element.html( html );
                    });
                }
            });
		},

	};

	wc_meta_boxes_order.init();

});

function delay_do_label_request() {
	setTimeout(do_label_request,10000);
}

function do_label_request() {

    jQuery('.suborder').each(function() {
        if ( !jQuery(this).find(".emc_documents").hasClass("labels_available") ) {
            // Call server for documents
            var suborder = jQuery(this);
            var suborder_key = suborder.attr("data-suborder");
            jQuery.post(ajaxurl, { action: 'check_labels', security: ajax_nonce, order_id: jQuery("#post_ID").val(), suborder_key: suborder_key }, function(data) {
                if(data) {
                    if ( typeof data.label_url != 'undefined' ) {
                        suborder.find(".label_url a").attr("href", data.label_url );
                        suborder.find(".label_url").show();
                    }
                    if ( typeof data.remise != 'undefined' ) {
                        suborder.find(".remise a").attr("href", data.remise );
                        suborder.find(".remise").show();
                    }
                    if ( typeof data.manifest != 'undefined' ) {
                        suborder.find(".manifest a").attr("href", data.manifest );
                        suborder.find(".manifest").show();
                    }
                    if ( typeof data.connote != 'undefined' ) {
                        suborder.find(".connote a").attr("href", data.connote );
                        suborder.find(".connote").show();
                    }
                    if ( typeof data.proforma != 'undefined' ) {
                        suborder.find(".proforma a").attr("href", data.proforma );
                        suborder.find(".proforma").show();
                    }
                    if ( typeof data.b13a != 'undefined' ) {
                        suborder.find(".b13a a").attr("href", data.b13a );
                        suborder.find(".b13a").show();
                    }

                    // no need to check again
                    suborder.find(".emc_documents").addClass("labels_available");
                }
            }, "json");
        }
    });
    delay_do_label_request();
}

jQuery(document).ready(function(){
	do_label_request();

    if (jQuery(".iframe").length !== 0) {
        /* parcel point selection popup */
        jQuery(".iframe").colorbox({rel:false, iframe:true, width:"1180px", height:"635px", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
    }

    /* add shipment popup */
    jQuery("#add-shipment").colorbox({inline:true, href:"#add-shipment-popup", width:"600px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
    jQuery('#add-shipment-popup button[name="cancel"]').click(function() {
        jQuery.colorbox.close();
    });
    jQuery('#add-shipment-popup button[name="add-shipment"]').click(function() {
        var shipment_data = {};
        shipment_data.address_id = jQuery('#add-shipment-popup select[name="_address_select"]').val();
        shipment_data.products = [];
        jQuery('.popup_proforma_qty').each(function(index, el) {
            var product = {};
            product.id = jQuery(this).attr("name").replace('proforma_qty_', '');
            product.qty = jQuery(this).val();
            shipment_data.products.push(product);
        });
        jQuery.ajax({
			url:ajaxurl,
			data: { action: 'add_shipment', security: ajax_nonce, order_id: jQuery("#post_ID").val(), address_id: shipment_data.address_id, products: shipment_data.products },
			dataType:'json',
			timeout:15000,
            method: 'POST',
			success:function(res) {
                if (typeof(res.error) == "undefined") {
                    location.reload();
                } else {
                    jQuery('.add-shipment-error').html(res.error);
                }
            }
		});
    });
    
    /* reset shipping options popup */
    jQuery("#reset-shipping").colorbox({inline:true, href:"#reset-shipping-popup", width:"600px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
    jQuery('#reset-shipping-popup button[name="cancel"]').click(function() {
        jQuery.colorbox.close();
    });
    jQuery('#reset-shipping-popup button[name="reset-shipping"]').click(function() {
        jQuery.ajax({
			url:ajaxurl,
			data: { action: 'reset_shipping', security: ajax_nonce, order_id: jQuery("#post_ID").val() },
			dataType:'json',
			timeout:15000,
            method: 'POST',
			success:function(res) {
                location.reload();
            }
		});
    });

    /* delete shipment popup */
    jQuery(".delete-shipment").colorbox({inline:true, href:"#delete-shipment-popup", width:"500px", height:"auto", scrolling:false, innerWidth:"100%", innerHeight:"100%"});
    jQuery(".delete-shipment").click(function() {
        var suborder = jQuery(this).closest('.suborder').attr("data-suborder");
        jQuery('#delete-shipment-popup button[name="delete-shipment"]').attr("rel", suborder);
    });
    jQuery('#delete-shipment-popup button[name="cancel"]').click(function() {
        jQuery.colorbox.close();
    });
    jQuery('#delete-shipment-popup button[name="delete-shipment"]').click(function() {
        var suborder = jQuery(this).attr("rel");
        jQuery.ajax({
			url:ajaxurl,
			data: { action: 'delete_shipment', security: ajax_nonce, order_id: jQuery("#post_ID").val(), suborder_key: suborder },
			dataType:'json',
			timeout:15000,
            method: 'POST',
			success:function(res) {
                location.reload();
            }
		});
    });

    /* send shipment */
    jQuery('.send-shipment').click(function(e) {
        e.preventDefault();
        var suborder = jQuery(this).closest('.suborder').attr("data-suborder");
        jQuery.ajax({
			url:ajaxurl,
			data: { action: 'send_shipment', security: ajax_nonce, order_id: jQuery("#post_ID").val(), suborder_key: suborder },
            dataType:'json',
            method: 'POST',
            success:function() {
                jQuery(window).scrollTop(0);
                location.reload();
            }
		});
    });

    // update parcel dimensions form
    function rebuild_parcels_form(key)
    {
        var suborder = jQuery(".suborder[data-suborder='"+key+"']");
        var parcels = suborder.find(".emc-parcel");

        suborder.find(".emc-nb-parcels_"+key).val(parcels.length);

        // update parcels indexes
        parcels.each(function(index,node){
            jQuery(node).find("input").each(function(i,input){
                var name = jQuery(input).attr("data-name-template").replace("{id}",index+1);
                jQuery(input).attr("name",name);
            });
        });

        // we make sure the user do not remove the last parcel
        if (parcels.length == 1)
        {
            parcels.find(".remove-parcel").hide();
        }
        else
        {
            parcels.find(".remove-parcel").show();
        }
    }

    // add new parcel dimensions
    jQuery('.add-parcel').click(function(){
        var sufix = jQuery(this).attr("data-key");
        var key = jQuery(this).closest(".suborder").attr("data-suborder");
        var nb_parcels = parseInt(jQuery(".emc-nb-parcels_"+key).val());
        var id = nb_parcels+1;
        jQuery('<div class="emc-parcel">'+
        '<p class="form-field form-field-wide">Parcel <span class="parcel-id">'+id+'</span> <a class="remove-parcel">('+translations.remove+')</a> :</p>'+
        '<div class="form-field form-field-wide"><span><span>Total shipping weight:</span> <input type="text" size="3" value="0" id="_dims_'+id+'_weight_'+sufix+'" name="_dims_'+id+'_weight_'+sufix+'" data-name-template="_dims_{id}_weight_'+sufix+'" class="_dims_'+id+'_weight"> kg</span></div>'+
        '<div class="form-field form-field-wide"><span><span>Total shipping width:</span>  <input type="text" size="3" value="0" id="_dims_'+id+'_width_'+sufix+'" name="_dims_'+id+'_width_'+sufix+'" data-name-template="_dims_{id}_width_'+sufix+'" class="_dims_'+id+'_width"> cm</span></div>'+
        '<div class="form-field form-field-wide"><span><span>Total shipping length:</span> <input type="text" size="3" value="0" id="_dims_'+id+'_length_'+sufix+'" name="_dims_'+id+'_length_'+sufix+'" data-name-template="_dims_{id}_length_'+sufix+'" class="_dims_'+id+'_length"> cm</span></div>'+
        '<div class="form-field form-field-wide"><span><span>Total shipping height:</span> <input type="text" size="3" value="0" id="_dims_'+id+'_height_'+sufix+'" name="_dims_'+id+'_height_'+sufix+'" data-name-template="_dims_{id}_height_'+sufix+'" class="_dims_'+id+'_height"> cm</span></div>'+
        '</div>')
        .insertBefore(jQuery(this).parent());
        rebuild_parcels_form(key);
    });

    // remove a parcel dimensions
    jQuery('.edit_dimensions').delegate('.remove-parcel','click',function(){
        var key = jQuery(this).closest(".suborder").attr("data-suborder");
        var nb_parcels = parseInt(jQuery(".emc-nb-parcels_"+key).val());
        var id = jQuery(this).attr("data-id");
        var block = jQuery(this).closest(".emc-parcel");
        if (block.length)
        {
            block.remove();
            rebuild_parcels_form(key);
        }
    });

    /* download waybills and delivery waybills */
    jQuery(document).on('click', '.label_url a, .remise a', function(e) {
        e.preventDefault();
        var parentDiv = jQuery(this).closest('div');
        var order_id = jQuery("#post_ID").val();
        var suborder = jQuery(this).closest('.suborder').attr("data-suborder");
        var type = "";
        if (parentDiv.hasClass('label_url')) {
            type = 'waybill';
        } else if(parentDiv.hasClass('remise')) {
            type = 'delivery_waybill';
        }
        window.location.href = ajaxurl+"?action=download_document&order_id="+order_id+"&suborder="+suborder+"&type="+type;
    });
});
