jQuery(document).ready(function($){
	$('#wpcsr-create-order .disable-input').attr('readonly', true);
	$('#parcel-dimension .package-type-label').click(function(){
		$('#parcel-dimension .package-type-label').removeClass('active');
		$(this).addClass('active');
	});
	
	var urlField 		= WPCSRAjaxHandler.urlField;
	var isDashboard     = WPCSRAjaxHandler.is_dashboard;
	var screenWidth 	= $(window).width(); 

	// Datetime Script - Non FM dashboard page
	if( isDashboard == 0 ){
		// Check if Frontend Manager Date Picker is disable
		$('.wpccf-datepicker').datetimepicker({
			timepicker:false,
			format: WPCSRAjaxHandler.dateFormat,
		});
		$('.wpccf-timepicker').datetimepicker({
			datepicker:false,
			format: WPCSRAjaxHandler.timeFormat
		});
	}

	function getSectionHeight( section ){
		setTimeout(function(){
			return section.innerHeight();
		}, 100 );	
	}
	$('#wpcsr-parcels').repeater({
		show: function () {
			$(this).slideDown();
		},
		hide: function (deleteElement) {
			if(confirm(WPCSRAjaxHandler.confirmDeleteRepeater)) {
				$(this).slideUp(deleteElement);
			}
		},
		ready: function (setIndexes) {
		}
	});
	function sortByKey(jsObj){
	    var sortedArray = [];

	    // Push each JSON Object entry in array by [key, value]
	    for(var i in jsObj)
	    {
	        sortedArray.push([jsObj[i], i ]);
	    }

	    // Run native sort function and returns sorted array.
	    return sortedArray.sort();
	}
    $('#wpcsr-origin').on('change', function(){
        var origin = $(this).val();
        if( origin == '' ){
            $('#wpcsr-weight').prop('disabled', true );
            $('#wpcsr-weight').val('');
            $('#wpcsr-destination').prop('disabled', true );
            $('#wpcsr-destination').val( '' );
            $('body .wpc-loading').remove();
        }else{
            $.ajax({
                url : WPCSRAjaxHandler.ajaxurl,
                type : 'post',
                data : {
                    action : 'wpcsr_get_destinations',
                    origin:origin
                },
                beforeSend:function(){
                    $('body').append('<div class="wpc-loading">Loading...</div>');
                },
                success : function( data ) {                	
                    var data = JSON.parse( data );
                    $("#wpcsr-destination option").each(function() {
                        if( $(this).hasClass('default' ) ){                            
                            return;
                            $(this).text('Select Location');
                        }else{
                            $(this).remove();
                        }
                        
                    });
                    setTimeout(function(){
                    	/* Convert into array */
      					var sortArr = [];					    
					    for (const [key, value] of Object.entries(data)) {
						  sortArr.push({"location" : value, "id": key});
						}
						/* Sort array by Ascending */
					    sortArr.sort(function(a, b) {					        
					        return (a[''] > b['location']) ? 1 : ((a['location'] < b['location']) ? -1 : 0);					        
					    });
						$.each(sortArr, function( index, data ){
							$('#wpcsr-destination').append('<option value="'+data.id+'">'+data.location+'</option>');				
					    });

                    }, 100 );
                    $('#wpcsr-destination').prop('disabled', false );
                    $('#wpcsr-weight').prop('disabled', false );
                    $('#wpcsr-package-list.repeater').removeClass('hide-element' );
                    $('#wpcsr-findrate #parcel-dimension').removeClass('hide-element' );
                    var dimesionSection = $('#rate-container #parcel-dimension').innerHeight();
                    if( screenWidth <= 991 ){
                    	$("#rate-container .quote_book").appendTo("#rate-container #parcel-dimension").css({'width':'100%'});
					}	
                    $('body .wpc-loading').remove();
                }
            });
        }
    });



    function sortData(key, data, type) {
	  let ordered = {};
	  let compareFunction = function(a, b) {
	    return data[b][key] - data[a][key];
	  };
	  if (type === "asc") {
	    compareFunction = function(a, b) {
	      return data[a][key] - data[b][key];
	    }
	  }
	  Object.keys(data).sort(compareFunction).forEach(function(key) {
	    ordered[key] = data[key];
	  });
	  return ordered;
	}

	// Radio buton Protection 
    $( '.wpcsr-check-icon' ).click( function(){   
        var protection          = $( 'input[name="protection"]:checked' ).val();     
        if(protection == 1 ){
            $( '.alert-popup' ).addClass( 'hide-element' );
            $( '.in-protection' ).removeClass( 'hide-element' );
        }else if(protection == 0) {
            $( '.alert-popup' ).removeClass( 'hide-element' );
            $( '.in-protection' ).addClass( 'hide-element' );
		}
		calculate_total_rate();
    });
	// Pickup Rate 
	var pickupLabel 	= WPCSRAjaxHandler.pickupLabel;
	var dropOffLabel 	= WPCSRAjaxHandler.dropOffLabel;
	var pickupZone 		= WPCSRAjaxHandler.pickupZone;
	var taxPercentage   = WPCSRAjaxHandler.taxPercentage;
	var currenySymbol 	= WPCSRAjaxHandler.currenySymbol;
	var referenceZone 	= WPCSRAjaxHandler.referenceZone;
	$('#wpcsr_delivery_methods').on('change', 'input[name="delivery_method"]', function(){
		var value = $(this).val();
		if( dropOffLabel == value ){
			$('#pickup-warehouse-option').css('display','block');
			$('#pickup-rates-option').css('display','none');
			$('.wpcsr-rate-list .wpcsr-payment-details table').find('#wpcsr-pickup-rate-cost').remove();
			$('#pickup-rates-option #pickup_address1' ).removeAttr('required');
			$('#pickup-rates-option #pickup_postcode' ).removeAttr('required');
			$('#pickup-rates-option #pickup_country' ).removeAttr('required');
			$('#pickup-address input[type="text"]').each(function(){
				$(this).val('');
			});
			$("#pickup-address").find("#"+referenceZone).prop('required',false).val('').trigger('change');
			calculate_total_rate();
		}else if( pickupLabel == value ){
			$('#pickup-rates-option').css('display','block');
			$('#pickup-warehouse-option').css('display','none');
			$('#pickup-rates-option #pickup_address1' ).attr('required', true);
			$('#pickup-rates-option #pickup_postcode' ).attr('required', true);
			$('#pickup-rates-option #pickup_country' ).attr('required', true);
			$("#pickup-address").find("#"+referenceZone).prop('required',true);
		}
	});
	$('#pickup-warehouse-option').on('click','.warehouse-address',function(){
		$('#pickup-warehouse-option').find('.warehouse-address').removeClass('selected');
        $(this).addClass('selected');
	});
	$("#pickup-address #"+referenceZone).on('change', function(){
		var zone = $.trim( $(this).val() );
		var weight = parseFloat( $( '.wpcsr-rate-list .weight' ).text().replace(/[^\d\.]/g, '') );
		$('.wpcsr-rate-list .wpcsr-payment-details table').find('#wpcsr-pickup-rate-cost').remove();
		// Run this code if the value is changed
		if( zone == '' ){
			return;
		}
		$.ajax({
			type 	: 'post',
			dataType : 'json',
			url 	: WPCSRAjaxHandler.ajaxurl,
			data 	: {
				action : 'wpcsr_get_pickuprate',
				zone : zone,
				weight: weight
			},
			beforeSend:function(){
				$('body').append('<div class="wpcargo-loading">Loading...</div>');
			},
			success:function(response){
				$('body .wpcargo-loading').remove();
				if( !response.price ){
					alert( response.message );
					return;
				}else{
					$('.wpcsr-payment-details').find('table').append('<tr id="wpcsr-pickup-rate-cost">'+
											'<th><span class="label"><strong>'+WPCSRAjaxHandler.pickupRateLabel+'</span>: </strong></th>'+
											'<td><span class="pickup_rate float_right">'+currenySymbol+response.price+'</span></td>'+
											'</tr>');
					calculate_total_rate();
				}
			}
		});
	});
	//  Date and Time Picker / Autocomplete pickup zone
	function calculate_total_rate(){
		setTimeout(function(){
			var shipping_rate       = parseFloat( $( '.wpcsr-rate-list .shipping_rate' ).text().replace(/[^\d\.]/g, '') );
			var shipping_protection = parseFloat( $( '.wpcsr-rate-list .shipping_protection' ).text().replace(/[^\d\.]/g, '') );
			// var shipping_vat        = parseFloat( $( '.wpcsr-rate-list .shipping_vat' ).text().replace(/[^\d\.]/g, '') );
			var pickup_rate        	= parseFloat( $( '.wpcsr-rate-list .pickup_rate' ).text().replace(/[^\d\.]/g, '') );
			var isProtected 		= $('.protection-option[name="protection"]:checked').val();
			var protection 			= 0;
			if( isProtected == 1 ){
				protection 			= isNaN( shipping_protection ) ? 0 : shipping_protection ;
			}
			var shipping 			= isNaN( shipping_rate ) ? 0 : shipping_rate ;
			// var vat 				= isNaN( shipping_vat ) ? 0 : shipping_vat ;
			var pickup 				= isNaN( pickup_rate ) ? 0 : pickup_rate ;
			var subtotal_rate  		= shipping + protection + pickup;
			var vat 				= subtotal_rate * ( taxPercentage / 100 );
			var total_rate  		= subtotal_rate + vat;
			// Set Vat value
			$( '.wpcsr-rate-list .shipping_vat' ).text( currenySymbol+vat.toFixed(2) );
			$('#total_rate .t_rate ').text(total_rate.toFixed(2));
		},100);
	}
	//** Validation for currentcy and number
	$("input.price, input.number").keydown(function (e) {
		validateCurrency(e)
	});
	$("#wpcsr-qoute-wrapper").on('keydown', "input.price, input.number, input.qty", function(e){
		validateCurrency(e);
	});
	// Create Order Feature
	$( '.wpcsr-card').on( 'click', '.wpcargo-btn-sm', function(){
		$( this ).parent().parent().parent().parent().addClass( 'scale' );
	} );
	function validateCurrency(e){
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
             // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
             // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
	}
	//** Script for number
	function validateNumber(e){
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
             // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
             // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105) ) {
            e.preventDefault();
        }
    }
    function objectKeys(obj) {
	    var data = [];
	    if (!obj) return data;
	    for (var key in obj) {
	        
	        data.push([key, obj[key]]);
	      
	    }
	    return data;
	}
});