var insuranceRate;
var insuranceLimit;
var minInsurance;

$(document).ready(function(){
	// Ajax Start/Stop indicator
	$('#loading').ajaxStart(function() {
		$(this).show();
		$("#addUpdateItemInsurance, #goToCheckout").attr( 'disabled', 'disabled' );
	}).ajaxStop(function() {
		$(this).hide();
		$("#addUpdateItemInsurance, #goToCheckout").removeAttr( 'disabled' );
	}).hide();
	
	// Insurance Calculator Form Validation
	$('#insuranceValue').validate({
		rules : { number : {required:true, number:true}},
		messages : {
			trackingNum: "Tracking number is required.",
			insuranceType: "Please select an insurance type.",
			shipType: "Please select a shipping method."
		}
	});

	$('#skipToCheckout').click(function(){
		return true;
	});
				
	// Hide update button from JS users
	$('input[name=formUpdate]').hide();
	
	// Update rates on item type change
	$('#insuranceType').change(function(){
		if ($('#insuranceType').val() == "Jewelry") {
			if ($('#shipType').val() == 'cod') { $('#shipType').val(''); }
			//$("#shipType option[value='cod']").hide();
			$("#shipType option[value='secured']").show();
		}
		else if ($('#insuranceType').val() == "General Cargo") {
			if ($('#shipType').val() == 'secured') { $('#shipType').val(''); }
			$("#shipType option[value='secured']").hide();
			//$("#shipType option[value='cod']").show();
		}
		if ( $('#insuranceType').val() != '' && $('#shipType').val() != '' ) {
			updateRate();
		} else {
			clearTotal();
		}
	});
	
	// Update rates on shipping change
	$('#shipType').change(function() {
		$("#shippingType").val( $("#shipType option:selected").text() );
		if ( $('#insuranceType').val() != '' && $('#shipType').val() != '' ) {
			updateRate();
		} else {
			clearTotal();
		}
	});
	
	// Update total when user keys amount in value input
	$('#insureValue').bind('blur keyup', function() {
		if ( $('#insuranceType').val() != '' && $('#shipType').val() != '' ) { updateTotal(); }
		else { clearTotal(); }
	}).bind('keypress', function(e) {
		return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
	});
	
	if ( $('#shipType') ) {
		var shipType = document.getElementById('shipType');
		for (var i=0; i < shipType.options.length; i++) {
			if ( shipType.options[i].getAttribute('selected') == 'selected' ) {
				shipType.selectedIndex = i;
				break;
			}
		}
	}
	
	if ( $('#insuranceType').val() != '' && $('#shipType').val() != '' && $("#insureValue").val() != '' ) { updateTotal(); }
	if ( $('#insuranceType').val() != '' ) { $('#insuranceType').change(); }
	
	$("#goToCheckout").click( function() { checkout(); } );
});	

function updateRate() {
	var item_type = $('#insuranceType').val();
	var ship_type = $('#shipType').val();
	
	$.post("main.php", { action: 'insRate', commodityType: item_type, shippingMethod: ship_type  }, function(data) {
		if ( data.substr(0,5) == 'Error' ) {
			alert(data);
		} else {
			data = data.split( '|' );
			insuranceRate = data[0];
			insuranceLimit = data[1];
			minInsurance = data[2];
			
			// Set limits
			//$('#insureValue').attr( 'max', insuranceLimit );
			$('#insureValueMsg').html( "&nbsp; Max: $" + addCommas( insuranceLimit ) );
			
			if ( $('#insureValue').val() != '' ) {
				updateTotal();
			}
		}
	});
}

// Function to update premium total
function updateTotal() {
	var item_calc = 0;
	var item_cost = 0;
	var item_max = 0;
	
	// Get insurance value
	var item_value = $('#insureValue').val();
	item_value = stripCommas( item_value );
	
	// Ensure Limits
	item_calc = Math.min( item_value, insuranceLimit );
	
	// Calculate it
	item_cost = ( item_calc * insuranceRate ).toFixed(2);
	if ( item_cost < parseInt ( minInsurance ) && readCookie('nomin') == 'n' ) {	//Min insurance $5
		item_cost = ( parseInt ( minInsurance ) ).toFixed(2);
	}
	
	// Update value on site and in form 
	$('span.totalCost').html('$' + item_cost + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
	$('input.insuranceCost').val( item_cost );
	
	if ( parseInt( item_value ) > parseInt( insuranceLimit ) ) {
		$('#insureValue').val( insuranceLimit );
		if ( $("#valueError").length == 0 ) {
			$("#insureValue").addClass( 'error' ).after( '<label id="valueError" class="error">Not a valid amount.</label>' );
			setTimeout( function() {
				$("#insureValue").removeClass( 'error' );
				$("#valueError").remove();
			}, 2000 );
		}
		return false;
	}
	return true;
}

function clearTotal() {
	//should this say something like 'select a shipping type, insurance type and value first!';
	$('span.totalCost').html( '' );
	$('input.totalCost').val( '' );
	hideLimits();
}

function addCommas( nStr ) {
	nStr += '';
	x = nStr.split( '.' );
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while ( rgx.test( x1 ) ) {
		x1 = x1.replace( rgx, '$1' + ',' + '$2' );
	}
	return x1 + x2;
}

function stripCommas( numString ) {
	var re = /,/g;
	return numString.replace( re, "" );
}

function hideLimits() {
	// Reset limits
	//$('#insureValue').attr( 'max','100000' );
	$('#insureValueMsg').html( '' );
}


function checkout() {
	if ( updateTotal() ) { 
		$('#insuranceValue').append( '<input type="hidden" name="goToCheckout" value="Checkout" />' );
		$('#insuranceValue').submit();
	} else {
		alert( 'Validation failed, make sure you are within the insurance limit and retry.' );
	}
}
