jQuery(document).ready(function($) {
	'use strict';
	// Warehouse Repeater
	$('#warehouse-list').repeater({
		show: function () {
			$(this).slideDown();
		},
		hide: function (deleteElement) {
			if(confirm(wpcsrAjaxHandler.confirmDeleteWarehouse)) {
				$(this).slideUp(deleteElement);
			}
		},
		ready: function (setIndexes) {}
	});
	$('#wpcsr-rate-origin').on('change', function(){
		var origin = $(this).val();
		if( origin == '' ){
			$('#wpcsr-rate-weight').prop('disabled', true );
			$('#wpcsr-rate-weight').val('');
			$('#wpcsr-rate-destination').prop('disabled', true );
			$('#wpcsr-rate-destination').vale( '' );
			$('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-rate-destination option").each(function() {
						if( $(this).hasClass('default' ) ){
							$(this).text('Select Location');
							return;
						}else{
							$(this).remove();
						}
					});
					setTimeout(function(){
						$.each( data, function( index, value ){
							$('#wpcsr-rate-destination').append('<option value="'+index+'">'+value+'</option>');
						});
					}, 100 );
					$('#wpcsr-rate-destination').prop('disabled', false );
					$('#wpcsr-rate-weight').prop('disabled', false );
					$('body .wpc-loading').remove();
				}
			});
		}
	});
	$("#wpcsr-package-opt-wrapper").on('mousedown', '.package-type[type="radio"]', function(){
		var $self = $(this);
		if( $self.is(':checked') ){
			var uncheck = function(){
				setTimeout(function(){$self.removeAttr('checked');},0);
			};
			var unbind = function(){
				$self.unbind('mouseup',up);
			};
			var up = function(){
				uncheck();
				unbind();
			};
			$self.bind('mouseup',up);
			$self.one('mouseout', unbind);
		}
	});
	$('#wpcsr-find-rate').on('click', function( e ){
		e.preventDefault();
		var rateOrigin 	= $('#wpcsr-rate-origin').val();
		var packageType = $("#wpcsr-package-opt-wrapper .package-type[type='radio']:checked").val();
		var rateDestination = $('#wpcsr-rate-destination').val();
		var rateWeight 	= $('#wpcsr-rate-weight').val();
		packageType 	= packageType ? packageType : '';
		if( rateWeight == '' || rateDestination == '' || rateOrigin == '' ){
			alert( wpcsrAjaxHandler.rateMessage );
			return;
		}
		$.ajax({
			url : wpcsrAjaxHandler.ajaxurl,
			type : 'post',
			data : {
				action : 'wpcsr_find_rate',
				rateOrigin:rateOrigin,
				rateDestination:rateDestination,
				rateWeight:rateWeight,
				packageType: packageType
			},
			beforeSend:function(){
				$('body').append('<div class="wpc-loading">Loading...</div>');
				$('#wpcsr-rateresult-wrapper').html('');
			},
			success : function( data ) {
				$('#wpcsr-rateresult-wrapper .rates').remove();
				$('#wpcsr-rateresult-wrapper').prepend(data);
				$('body .wpc-loading').remove();
			}
		});
	});
	// Auto Calculation
	var taxPercentage   = wpcsrAjaxHandler.taxPercentage;
	var currenySymbol   = wpcsrAjaxHandler.currenySymbol;
	var pickupZone 		= wpcsrAjaxHandler.pickupZone;
	var pickupLabel 	= wpcsrAjaxHandler.pickupLabel;
	var dropOffLabel 	= wpcsrAjaxHandler.dropOffLabel;
	var referenceZone 	= wpcsrAjaxHandler.referenceZone;
	var currentZone;
	$('#wpcsr-rateresult-wrapper').on('click', '.rates', function(e){
		var rateID = $(this).attr('for');
		$(".rates input#"+rateID).prop('checked', true);
		$('#wpcsr-rateresult-wrapper').find('.rates').removeClass('selected');
		$('#wpcsr-rateresult-wrapper #shipment-cost').css('display', 'block');
		$(this).addClass('selected');
		get_pickup_rate();
		calculate_total_rate();
	});
	$('#pickup-address').on('change', 'input[name="pickup_method"]', function(){
		var value = $(this).val();
		var price = 0;
		var shipmentCostWrapper = $('#shipment-cost');
		if( value == dropOffLabel ){
			shipmentCostWrapper.find( '.pickup_rate' ).text( currenySymbol+price.toFixed(2) );
		}else if( value == pickupLabel ){
			get_pickup_rate();
		}
		calculate_total_rate();
	});
	
	if( $('#pickup-address #'+referenceZone).length != 0 ){
		$('#pickup-address #'+referenceZone).bind('change, paste, focusout', function(){
			var newZone = $(this).val();
			// Run this code if the value is changed
			if( $.trim(currentZone) != $.trim(newZone) ){
				get_pickup_rate();
			}
		});
		$('#pickup-address #'+referenceZone).bind('focus', function(){
			currentZone = $(this).val();
		});
		// Autocomplete pickup zone
		$( "#pickup-address #"+referenceZone ).autocomplete({
			source: pickupZone
		});
	}
	
	$("#wpcsr_location").keyup(function(){
		var text = $(this).val();
		text = text.toLowerCase();
		text = text.replace(/[^a-zA-Z0-9]+/g,'-');
		$("#wpcsr_location_slug").val(text);
	});
	$("#wpcsr_zone").change(function(){
		var wpcsr_rate = $("#wpcsr_zone option:selected").attr('data-rate');
		$("#wpcsr_rate").val(wpcsr_rate);
	});
	$("#shipment-rate-edit.modal").on('change', '#wpcsr_update_zone', function(){
		var wpcsr_rate = $("#wpcsr_update_zone option:selected").attr('data-rate');
		$("#wpcsr_update_rate").val(wpcsr_rate);
	});
	$('span.close-btn').click(function(){
		$('.modal').hide();
	});
	//** Validation for currentcy and number
	$("input.price, input.number").keydown(function (e) {
		validateCurrency(e)
	});
	$("input.qty").keydown(function (e) {
		validateNumber(e);
	});
	// Rate Type script
	$('body').on('change', '.wpcsr_rate_type, .wpcsr_update_rate_type', function(){
		if( $(this).val() == '1'){
			$(this).parents().eq(3).find('.weight_cost_row').css('display', 'table-row');
		}else{
			$(this).parents().eq(3).find('.weight_cost_row').css('display', 'none');
			$(this).parents().eq(3).find('.weight_cost_row input').val('');
		}
	});
	
	function get_pickup_rate(){
		var selectedRate        = $('#wpcsr-rateresult-wrapper .rates.selected');
		var deliveryMethod      = $('#pickup-address').find('input[name="pickup_method"]:checked').val();
		var shipmentCostWrapper = $('#shipment-cost');
		var zone                = $.trim(  $('#pickup-address').find('input[name="'+referenceZone+'"]').val() );
		var weight              = parseFloat( selectedRate.find('.rate-weight').text().replace(/[^\d\.]/g, '') );
		weight                  = isNaN( weight ) ? 0 : weight ;
		if( zone == '' || weight <= 0 || deliveryMethod == dropOffLabel ){
			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){
				var price = parseFloat( response.price );
				$('body .wpcargo-loading').remove();
				if( !response.price ){
					alert( response.message );
					shipmentCostWrapper.find( '.pickup_rate' ).text( currenySymbol+price.toFixed(2) );
				}else{
					shipmentCostWrapper.find( '.pickup_rate' ).text( currenySymbol+price.toFixed(2) );
				}
				calculate_total_rate();
			}
		});
	}
	
	function calculate_total_rate(){
		setTimeout(function(){
			var selectedRate 	= $('#wpcsr-rateresult-wrapper .rates.selected');
			var shipmentCostWrapper = $('#shipment-cost');
			var rate        	= selectedRate.find('input[name="protection"]:checked').data('rate');
			var protection  	= selectedRate.find('input[name="protection"]:checked').data('protect');
			var cost  			= selectedRate.find('input[name="protection"]:checked').data('cost');
			var pickup_rate 	= parseFloat( shipmentCostWrapper.find( '.pickup_rate' ).text().replace(/[^\d\.]/g, '') );
			pickup_rate     	= isNaN( pickup_rate ) ? 0 : pickup_rate ;
			protection          = isNaN( protection ) ? 0 : protection ;
			cost				+= pickup_rate;
			// Display calculated data
			shipmentCostWrapper.find( '.shipping_rate' ).text( currenySymbol+rate.toFixed(2) );
			shipmentCostWrapper.find( '.shipping_protection' ).text( currenySymbol+protection.toFixed(2) );
			shipmentCostWrapper.find( '.pickup_rate' ).text( currenySymbol+pickup_rate.toFixed(2) );
			shipmentCostWrapper.find( '.total_cost' ).text( currenySymbol+cost.toFixed(2) );
		}, 100);
	}
	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();
		}
	}
	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();
		}
	}
	//Search function
	$.urlParam = function(name){
		var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
		return results;
	}
	function getQueryVariable(url, variable) {
		var query = url.substring(1);
		var parameter = query.split('?');
		var split_parameter = parameter[1].split('&');
		for (var i=0; i < split_parameter.length; i++) {
			var pair = split_parameter[i].split('=');
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return false;
	}
	$('.wpcsr-search-section .wpcsr-search-button').click(function(){
		var search_text = jQuery('.wpcsr-search-section input').val();
		if($.urlParam('search-label') === null){
			window.location.href = window.location.href + '&search-label='+ search_text;
		}else{
			var url = window.location.href;
			var page_param = getQueryVariable(url, 'page');
			var params = { 'page':page_param, 'search-label':search_text };
			var new_url = url + '?' + jQuery.param(params);
			window.location.href = new_url;
		}
	});
});