var calculatedShippingCost = null;
var defaultShippingCost = 0;

var successfulCalculationCallback;

function displayShipping(zip, onSuccessfulCalculationCallback) {
	if (isNaN(parseInt(zip))) {
		document.getElementById("invalidState").style.display = "";
		return;
	}

	if (onSuccessfulCalculationCallback != null)
		successfulCalculationCallback = onSuccessfulCalculationCallback;

	document.getElementById("shippingSpinner").innerHTML = "<img src=\"/_images/wait.gif\" alt=\"Contacting USPS for your shipping rate.\" width=\"32\" height=\"32\" />";
	if (document.getElementById("shipping") != null)
		document.getElementById("shipping").innerHTML = "";

	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", "/store/getShippingRate.xml.php?zip=" + zip, true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			document.getElementById("shippingSpinner").innerHTML = "";
			if (xmlhttp.status == 200) {
				if (xmlhttp.responseXML.documentElement.nodeName == "error") {
					if (document.getElementById("shipping") != null)
						document.getElementById("shipping").innerHTML = "";
					document.getElementById("invalidState").style.display = "";
				} else {
					var rate = formatCurrency(xmlhttp.responseXML.documentElement.getAttribute("cost")) + "<br />" + xmlhttp.responseXML.documentElement.getAttribute("name");
					if (document.getElementById("shipping") != null)
						document.getElementById("shipping").innerHTML = rate;
					document.getElementById("invalidState").style.display = "none";
					if (document.forms["paypalForm"].handling_cart != null)
						document.forms["paypalForm"].handling_cart.value = xmlhttp.responseXML.documentElement.getAttribute("cost");

					calculatedShippingCost = parseFloat(xmlhttp.responseXML.documentElement.getAttribute("cost"));
					if (document.getElementById("totalShippingNote") != null)
						document.getElementById("totalShippingNote").style.display = "none";

					if (document.getElementById("estimatedOrderTotal") != null)
						if (totalBeforeShipping + calculatedShippingCost >= totalDiscount)
							document.getElementById("estimatedOrderTotal").innerHTML = formatCurrency(totalBeforeShipping + calculatedShippingCost - totalDiscount);
						else
							document.getElementById("estimatedOrderTotal").innerHTML = formatCurrency(0);

					if (successfulCalculationCallback != null)
						successfulCalculationCallback();
				}
			} else {
				if (document.getElementById("shipping") != null)
					document.getElementById("shipping").innerHTML = defaultShippingCost;
				document.getElementById("invalidState").style.display = "";
			}
		}
	}
	xmlhttp.send(null);
}

function formatCurrency(amount) {
	var i = parseFloat(amount);
	if (isNaN(i) || i == 0)
		return "$0";
	return "$" + i.toFixed(2); // Prevents floating point errors induced by i.toString() or new String(i).
}

