var AJAXURL = $('meta[name=modUrl]').attr("content");
var MODURL = $('meta[name=modUrl]').attr("content");

$(document).ready(function() {	
	estimateTax();
	$("img.continueShoppingButton").click(goToProductPage);
	$("input.applyZipButton").click(estimateTax);
	$("span.removeCartItemBtn").click(function(){
		var productID = $(this).attr("id").replace("remove_","");
		removeItem(productID);
	});
	$("img.checkOutButton").click(startCheckOut);
});

function goToProductPage() {
	var url = $("#continueShoppingURL").val();
	window.location.href = url;
}

function estimateTax() {
	var zip = $("#zipcode").val();
	var subTotal = $("#cartTotal").val();
	if(zip) {
		var url = AJAXURL + '/cartAjax/';
		// Do AJAX
		$.ajax({
			type: "GET",
			url: url,
			async: false,
			timeout: 30000,
			data: {"action": "estimateTax","zip": zip,"subTotal": subTotal},
			dataType: "html",
			success: function(data, textStatus) {
				// Write tax amount to DOM
				$("#cartTaxAmt").html("<b>$"+data+"</b>");
				// Adjust total, write out to DOM
				var adjTotal = formatCurrency(parseFloat(subTotal) + parseFloat(data));
				$("#cartTotalAmt").html("<b>$"+adjTotal+"</b>");
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
			}
		});
	}
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) {
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	}
	return (((sign)?'':'-') + num + '.' + cents);
}

function removeItem(productID) {
	if(productID) {
		var url = AJAXURL + '/cart/remove/' + productID;
		// Do AJAX
		$.ajax({
			type: "GET",
			url: url,
			async: false,
			timeout: 30000,
			data: {},
			dataType: "html",
			success: function(data, textStatus) {
				window.location.href= MODURL+'/cart'
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				
			}
		});
	}
}

function startCheckOut() {
	// Attempt to execute estimate tax in the event user added zip w/o applying
	estimateTax();
	// Check total, if null don't proceed to checkout, instead tell customer products required
	var total = $("#cartTotal").val();
	if(total == "0.00") {
		$("#checkoutDialog").dialog({
			title: 'Products Required',
			draggable: false,
			resizable: false,
			width: '400px',
			zIndex: '1000',
			modal: true,
			buttons: { 
				"Ok": function() {
					$(this).dialog('destroy');
				}
			},
			close: function() {
				$(this).dialog('destroy');
			}
		});
	} else {
		// Go to billing page
		window.location.href = AJAXURL + '/billingShipping';
	}
}

