// WebStore class

// Load required libraries
AppGlobal.loadClass("Ajax");

var WebStore;
if (!WebStore) WebStore = {};

WebStore.ajaxURL = "/ajax/webstore.aspx";
WebStore.timer = null;
WebStore.shipTaxZip = "";

 // Initializes the checkout form
WebStore.initCheckoutForm = function() {
	// Handle the password entry toggle
	$("#rbPasswordYes").click(function() {
		if ($(this).is(':checked')) {
			$("#trPasswordYes1, #trPasswordYes2").show();
			$("#trPasswordNo").hide();
		}
	});
	$("#rbPasswordNo").click(function() {
		if ($(this).is(":checked")) {
			$("#trPasswordYes1, #trPasswordYes2").hide();
			$("#trPasswordNo").show();
		}
	});
	// Handle changing of shipping selection
	$("#rbEconomyShipping, #rbStandardShipping, #rbPriorityShipping").click(function() {
		var tmpval = $(this).val(), shipmethod;
		if (tmpval == "rbEconomyShipping") shipmethod = "ECON";
		else if (tmpval == "rbPriorityShipping") shipmethod = "2DAY";
		else shipmethod = "GRND";
		$.ajax({
			   async: true,
			   type: "POST",
			   url: WebStore.ajaxURL,
			   dataType: "xml",
			   data: { a: "cts", o: $("#hdnOrderID").val(), sm: shipmethod },
			   beforeSend: function() { $("#trUpdatingTotals").show(); },
			   complete: function() { $("#trUpdatingTotals").hide(); },
			   success: function(xml) {
				   var total = $("GrandTotal", xml).text();
				   if (parseFloat(total.replace('$', '')) > 0) {
					   $("#trSalesTax, #trShipping, #trOrderTotal").show();
					   $("#lblShipMethod").text($("ShipMethodDescription", xml).text());
					   $("#lblSalesTax").text($("SalesTax", xml).text());
					   $("#lblShipping").text($("TotalShipping", xml).text());
					   $("#lblGrandTotal").text($("GrandTotal", xml).text());
				   } else $("#trSalesTax, #trShipping, #trOrderTotal").hide();
			   },
			   error: function(xhr, status, err) {
				   $("#vsSaveTemplate").text("Fatal error: " + xhr.statusText);
					var message = "";
					message = xhr.statusText;
					if (message.length == 0) message = "Unspecified error " + status;
					// Display error message
					alert(message);
			   }
		});
	});
	// Handle field enable/disable for billing address
	$("#cbGuestUseShipAddress").click(function() {
		if ($(this).is(":checked")) {
			$("#txtGuestBillToFirstName").val($("#hdnShipFirstName").val());
			$("#txtGuestBillToLastName").val($("#hdnShipLastName").val());
			$("#txtGuestBillToCompany").val($("#hdnShipCompany").val());
			$("#txtGuestBillToAddress1").val($("#hdnShipAddress1").val());
			$("#txtGuestBillToAddress2").val($("#hdnShipAddress2").val());
			$("#txtGuestBillToCity").val($("#hdnShipCity").val());
			$("#ddlGuestBillToState").val($("#hdnShipState").val());
			$("#txtGuestBillToZip").val($("#hdnShipZip").val());
			ValidatorEnable($id("rfvGuestBillToFirstName"), false);
			ValidatorEnable($id("rfvGuestBillToLastName"), false);
			ValidatorEnable($id("rfvGuestBillToAddress1"), false);
			ValidatorEnable($id("rfvGuestBillToCity"), false);
			ValidatorEnable($id("rfvGuestBillToState"), false);
			ValidatorEnable($id("rfvGuestBillToZip"), false);
			ValidatorEnable($id("revGuestBillToZip"), false);
			$("#txtGuestBillToFirstName, #txtGuestBillToLastName, #txtGuestBillToCompany, #txtGuestBillToAddress1, #txtGuestBillToAddress2, #txtGuestBillToCity, #ddlGuestBillToState, #txtGuestBillToZip").attr('disabled', 'disabled');
		} else {
			ValidatorEnable($id("rfvGuestBillToFirstName"), true);
			ValidatorEnable($id("rfvGuestBillToLastName"), true);
			ValidatorEnable($id("rfvGuestBillToAddress1"), true);
			ValidatorEnable($id("rfvGuestBillToCity"), true);
			ValidatorEnable($id("rfvGuestBillToState"), true);
			ValidatorEnable($id("rfvGuestBillToZip"), true);
			ValidatorEnable($id("revGuestBillToZip"), true);
			$("#txtGuestBillToFirstName, #txtGuestBillToLastName, #txtGuestBillToCompany, #txtGuestBillToAddress1, #txtGuestBillToAddress2, #txtGuestBillToCity, #ddlGuestBillToState, #txtGuestBillToZip").removeAttr('disabled');
		}
	});
	$("#cbCustomerUseShipAddress").click(function() {
		if ($(this).is(":checked")) {
			$("#txtCustomerBillToFirstName").val($("#hdnShipFirstName").val());
			$("#txtCustomerBillToLastName").val($("#hdnShipLastName").val());
			$("#txtCustomerBillToCompany").val($("#hdnShipCompany").val());
			$("#txtCustomerBillToAddress1").val($("#hdnShipAddress1").val());
			$("#txtCustomerBillToAddress2").val($("#hdnShipAddress2").val());
			$("#txtCustomerBillToCity").val($("#hdnShipCity").val());
			$("#ddlCustomerBillToState").val($("#hdnShipState").val());
			$("#txtCustomerBillToZip").val($("#hdnShipZip").val());
			ValidatorEnable($id("rfvCustomerBillToFirstName"), false);
			ValidatorEnable($id("rfvCustomerBillToLastName"), false);
			ValidatorEnable($id("rfvCustomerBillToAddress1"), false);
			ValidatorEnable($id("rfvCustomerBillToCity"), false);
			ValidatorEnable($id("rfvCustomerBillToState"), false);
			ValidatorEnable($id("rfvCustomerBillToZip"), false);
			ValidatorEnable($id("revCustomerBillToZip"), false);
			$("#txtCustomerBillToFirstName, #txtCustomerBillToLastName, #txtCustomerBillToCompany, #txtCustomerBillToAddress1, #txtCustomerBillToAddress2, #txtCustomerBillToCity, #ddlCustomerBillToState, #txtGuestBillToZip").attr('disabled', 'disabled');
		} else {
			ValidatorEnable($id("rfvCustomerBillToFirstName"), true);
			ValidatorEnable($id("rfvCustomerBillToLastName"), true);
			ValidatorEnable($id("rfvCustomerBillToAddress1"), true);
			ValidatorEnable($id("rfvCustomerBillToCity"), true);
			ValidatorEnable($id("rfvCustomerBillToState"), true);
			ValidatorEnable($id("rfvCustomerBillToZip"), true);
			ValidatorEnable($id("revCustomerBillToZip"), true);
			$("#txtCustomerBillToFirstName, #txtCustomerBillToLastName, #txtCustomerBillToCompany, #txtCustomerBillToAddress1, #txtCustomerBillToAddress2, #txtCustomerBillToCity, #ddlCustomerBillToState, #txtCustomerBillToZip").removeAttr('disabled');
		}
	});
	// Get page elements
	var form = $id("frmCheckout");
	var cbCreateAccount = $id("cbCreateAccount");
	var txtGuestPassword = $id("txtGuestPassword");
	var txtGuestVerifyPassword = $id("txtGuestVerifyPassword");
	var cbCustomerDefaultPartial = $id("cbCustomerDefaultPartial");
	var cbCustomerOtherPartial = $id("cbCustomerOtherPartial");
	var cbCustomerPartial = $id("cbCustomerPartial");
	var cbGuestPartial = $id("cbGuestPartial");
	var divCustomerDefaultPartial = $id("divCustomerDefaultPartial");
	var divCustomerOtherPartial = $id("divCustomerOtherPartial");
	var trCustomerPartial = $id("trCustomerPartial");
	var trGuestPartial = $id("trGuestPartial");
	var rblCustomerPaymentMethod = form.CustomerPaymentMethod;
	var rblGuestPaymentMethod = form.GuestPaymentMethod;
	var cbBlainCardPromo = $id("cbBlainCardPromo");
	var btnPlaceOrderNow = $id("btnPlaceOrderNow");
	if (cbCreateAccount && txtGuestPassword && txtGuestVerifyPassword) {
		var toggleCreateAccount = function() {
			txtGuestPassword.disabled = (cbCreateAccount.checked) ? false : true;
			txtGuestVerifyPassword.disabled = (cbCreateAccount.checked) ? false : true;
			if (cbCreateAccount.checked) txtGuestPassword.select();
		}
		cbCreateAccount.onclick = toggleCreateAccount;
		toggleCreateAccount();
	}
	if (cbCustomerDefaultPartial && divCustomerDefaultPartial) {
		var toggleCustomerDefaultPartial = function() { divCustomerDefaultPartial.style.display = (cbCustomerDefaultPartial.checked) ? "" : "none"; }
		cbCustomerDefaultPartial.onclick = toggleCustomerDefaultPartial;
		toggleCustomerDefaultPartial();
	}
	if (cbCustomerOtherPartial && divCustomerOtherPartial) {
		var toggleCustomerOtherPartial = function() { divCustomerOtherPartial.style.display = (cbCustomerOtherPartial.checked) ? "" : "none"; }
		cbCustomerOtherPartial.onclick = toggleCustomerOtherPartial;
		toggleCustomerOtherPartial();
	}
	if (cbCustomerPartial && trCustomerPartial) {
		var toggleCustomerPartial = function() { trCustomerPartial.style.display = (cbCustomerPartial.checked) ? "" : "none"; }
		cbCustomerPartial.onclick = toggleCustomerPartial;
		toggleCustomerPartial();
	}
	if (cbGuestPartial && trGuestPartial) {
		var toggleGuestPartial = function() { trGuestPartial.style.display = (cbGuestPartial.checked) ? "" : "none"; }
		cbGuestPartial.onclick = toggleGuestPartial;
		toggleGuestPartial();
	}
	if (rblCustomerPaymentMethod) {
		for (var x = 0; x < rblCustomerPaymentMethod.length; x++) rblCustomerPaymentMethod[x].onclick = WebStore.toggleCustomerPaymentMethod;
		WebStore.toggleCustomerPaymentMethod();
	}
	if (rblGuestPaymentMethod) {
		for (var x = 0; x < rblGuestPaymentMethod.length; x++) rblGuestPaymentMethod[x].onclick = WebStore.toggleGuestPaymentMethod;
		WebStore.toggleGuestPaymentMethod();
	}
	if (cbBlainCardPromo && btnPlaceOrderNow) {
		btnPlaceOrderNow.onclick = function() {
			if (cbBlainCardPromo.checked) return true;
			else {
				alert("You must check the checkbox agreeing to the terms of the Blain's Farm & Fleet Credit Card Promotion.");
				return false;
			}
		}
	}
}

WebStore.filterQtyInput = function(ev) {
	var e = ev || window.event;
	var code = e.charCode || e.keyCode;
	var c = String.fromCharCode(code);
	var field  = ev.target || ev.srcElement;
	
	// Handle modifier keys
	if (e.charCode == 0) return true;
	if (e.ctrlKey || e.altKey || e.shiftKey) {
		if (e.keyCode) e.keyCode = 0;
		if (e.preventDefault) e.preventDefault();
		if (e.returnValue) e.returnValue = false;
		field.onkeyup = null;
		return false;
	}
	if (code < 32) return true;
	
	if (isNaN(c)) {
		if (e.keyCode) e.keyCode = 0;
		if (e.preventDefault) e.preventDefault();
		if (e.returnValue) e.returnValue = false;
		field.onkeyup = null;
		return false;
	}
	field.onkeyup = WebStore.qtyListener;
}

WebStore.qtyListener = function(ev) {
	var e = ev || window.event;
	// Handle modifier keys
	if (e.keyCode == 13 || e.ctrlKey || e.altKey || e.shiftKey) return false;
	if (WebStore.timer != null) {
		clearTimeout(WebStore.timer);
		WebStore.timer = null;
	}
	var hasErrors = false;
	var qtyErrors = false;
	var form = $id("frmShoppingCart");
	var hdnOrderID = $id("hdnOrderID");
	var imgProgress = $id("imgProgress");
	var divError = $id("divError");
	if (form && hdnOrderID) {
		var params = "a=uq";
		params += "&o=" + encodeURIComponent(hdnOrderID.value);
		// Iterate through all quantity fields to get values and catch errors
		for (var x = 0; x < form.elements.length; x++) {
			var field = form.elements[x];
			// Remove leading zeroes
			while (field.value.charAt(0) == '0') field.value = field.value.substring(1, field.value.length);
			if (field.type == "text" && field.name.indexOf("txtQty") != -1) {
				var imgError = $id(field.name.replace("txtQty", "imgQty"));
				var vMaxQty = $id(field.name.replace("txtQty", "hdnQty"));
				if (!field.value.isInteger()) {
					hasErrors = true;
					if (imgError) imgError.style.visibility = 'visible';
					continue;
				} else if (vMaxQty && parseInt(field.value) > parseInt(vMaxQty.value)) {
					qtyErrors = true;
					if (imgError) imgError.style.visibility = 'visible';
					continue;
				} else {
					params += "&" + encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value);
					if (imgError) imgError.style.visibility = 'hidden';
				}
			}
		}
		if (hasErrors) {
			if (imgProgress) imgProgress.style.visibility = 'hidden';
			if (divError) {
				divError.style.visibility = 'visible';
				divError.innerHTML = "All of your items must have valid whole number quantities.";
			}
		} else if (qtyErrors) {
			if (imgProgress) imgProgress.style.visibility = 'hidden';
			if (divError) {
				divError.style.visibility = 'visible';
				divError.innerHTML = "Sorry, the quantity you want isn't available right now. Please try a lower quantity.";
			}
		} else {
			if (imgProgress) imgProgress.style.visibility = 'visible';
			if (divError) divError.style.visibility = 'hidden';
			WebStore.timer = setTimeout(function() { WebStore.updateQty(params) }, 750);
		}
	}
}

// Updates the quantities of items in the 
WebStore.updateQty = function(params) {
	var imgProgress = $id("imgProgress");
	if (imgProgress) imgProgress.style.visibility = 'visible';
	var request = Ajax.newRequest();
	request.open("POST", WebStore.ajaxURL, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-Length", params.length);
	request.setRequestHeader("Connection", "close");
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			// Display prices table
			if (request.status == 200) {
    	        var xmlDoc = request.responseXML;
				var vProducts = xmlDoc.getElementsByTagName("Product");
				var vGiftCards = xmlDoc.getElementsByTagName("GiftCard");
				var vID;
				var vLineTotal;
				var vPromoDealDescription;
				var vPromoDealDiscount;
				var lblLineTotal;
				var span1;
				var b;
				var span2;
				// Update the line total for products
				for (var x = 0; x < vProducts.length; x++) {
					vID = AppGlobal.getXMLValue(vProducts[x].getElementsByTagName("ID")[0]);
					vPromoDealDescription = AppGlobal.getXMLValue(vProducts[x].getElementsByTagName("PromoDealDescription")[0]);
					vPromoDealDiscount = AppGlobal.getXMLValue(vProducts[x].getElementsByTagName("PromoDealDiscount")[0]);
					vLineTotal = AppGlobal.getXMLValue(vProducts[x].getElementsByTagName("LineTotal")[0]);
					lblDiscount = $id("lblDiscount_P_" + vID);
					lblLineTotal = $id("lblLineTotal_P_" + vID);
					AppGlobal.setText(lblLineTotal, vLineTotal);
					// If there is a discount, display the discount details
					if (vPromoDealDescription.length > 0 && vPromoDealDiscount != "$0.00") {
						while (lblDiscount.firstChild) lblDiscount.removeChild(lblDiscount.firstChild);
						span1 = document.createElement("span");
						span1.className = "text-sm light";
						lblDiscount.appendChild(span1);
						span1.appendChild(document.createTextNode("Special Offer:"));
						lblDiscount.appendChild(document.createElement("br"));
						b = document.createElement("b");
						lblDiscount.appendChild(b);
						b.appendChild(document.createTextNode(vPromoDealDescription));
						lblDiscount.appendChild(document.createElement("br"));
						span2 = document.createElement("span");
						span2.className = "sale-price";
						lblDiscount.appendChild(span2);
						span2.appendChild(document.createTextNode("Total Discount: " + vPromoDealDiscount));
					} else AppGlobal.setText(lblDiscount, " ");
				}
				// Update the line total for gift cards
				for (var x = 0; x < vGiftCards.length; x++) {
					vID = AppGlobal.getXMLValue(vGiftCards[x].getElementsByTagName("ID")[0]);
					vLineTotal = AppGlobal.getXMLValue(vGiftCards[x].getElementsByTagName("LineTotal")[0]);
					lblLineTotal = document.getElementById("lblLineTotal_GC_" + vID);
					AppGlobal.setText(lblLineTotal, vLineTotal);
				}
				// Update the subtotal for the order
				var vTotalQty = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("TotalQty")[0]);
				var vEconomyShippingEligible = parseInt(AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("EconomyShippingEligible")[0]));
				var vSubtotal = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("OrderSubtotal")[0]);
				var lblSubtotal = $id("lblSubtotal");
				var lblOrderSubtotal = $id("lblOrderSubtotal");
				var hlCart = $id("ucHeader_hlCart");
				var trEconomyShipping = $id("trEconomyShipping");
				var lblNoEconomy = $id("lblNoEconomy");
				var rbEconomyShipping = $id("rbEconomyShipping");
				var rbStandardShipping = $id("rbStandardShipping");
				AppGlobal.setText(hlCart, vTotalQty + ((vTotalQty == 1) ? " item" : " items"));
				AppGlobal.setText(lblSubtotal, vSubtotal);
				AppGlobal.setText(lblOrderSubtotal, vSubtotal);
				if (trEconomyShipping && lblNoEconomy && vEconomyShippingEligible == 1) {
					trEconomyShipping.style.display = '';
					lblNoEconomy.style.display = 'none';
				} else if (trEconomyShipping && lblNoEconomy) {
					trEconomyShipping.style.display = 'none';
					lblNoEconomy.style.display = '';
					if (rbEconomyShipping.checked) rbStandardShipping.checked = true;
				}
			} else {
				// Get failed status error message
				var message = "";
				message = request.statusText;
				if (message.length == 0) message = "Unspecified error " + request.status;
				// Display error message
				alert(message);
			}
			if (imgProgress) imgProgress.style.visibility = 'hidden';
		}
	}
	request.send(params);
}

WebStore.bustFrames = function() {
	if (top.location != location) top.location.href = document.location.href;
}

// Toggles the active view for the payment page based on the selection
WebStore.toggleCustomerPaymentMethod = function() {
	var form = document.getElementById("frmCheckout");
	var divCustomerStoredCard = $id("divCustomerStoredCard");
	var divCustomerCreditCard = $id("divCustomerCreditCard");
	var divCustomerBlainCard = $id("divCustomerBlainCard");
	var divCustomerGiftCard = $id("divCustomerGiftCard");
	var rblCustomerPaymentMethod = form.CustomerPaymentMethod;
	if (rblCustomerPaymentMethod) {
		if (divCustomerStoredCard) divCustomerStoredCard.style.display = 'none';
		if (divCustomerCreditCard) divCustomerCreditCard.style.display = 'none';
		if (divCustomerBlainCard) divCustomerBlainCard.style.display = 'none';
		if (divCustomerGiftCard) divCustomerGiftCard.style.display = 'none';
		if (rblCustomerPaymentMethod.length == 4) {
			if (rblCustomerPaymentMethod[0].checked) divCustomerStoredCard.style.display = '';
			if (rblCustomerPaymentMethod[1].checked) divCustomerCreditCard.style.display = '';
			if (rblCustomerPaymentMethod[2].checked) divCustomerBlainCard.style.display = '';
			if (rblCustomerPaymentMethod[3].checked) divCustomerGiftCard.style.display = '';
		} else {
			if (rblCustomerPaymentMethod[0].checked) divCustomerCreditCard.style.display = '';
			if (rblCustomerPaymentMethod[1].checked) divCustomerBlainCard.style.display = '';
			if (rblCustomerPaymentMethod[2].checked) divCustomerGiftCard.style.display = '';
		}
	}
}

// Toggles the active view for the payment page based on the selection
WebStore.toggleGuestPaymentMethod = function() {
	var form = document.getElementById("frmCheckout");
	var divGuestCreditCard = $id("divGuestCreditCard");
	var divGuestBlainCard = $id("divGuestBlainCard");
	var divGuestGiftCard = $id("divGuestGiftCard");
	var rblGuestPaymentMethod = form.GuestPaymentMethod;
	if (rblGuestPaymentMethod) {
		if (divGuestCreditCard) divGuestCreditCard.style.display = 'none';
		if (divGuestBlainCard) divGuestBlainCard.style.display = 'none';
		if (divGuestGiftCard) divGuestGiftCard.style.display = 'none';
		if (rblGuestPaymentMethod[0].checked) divGuestCreditCard.style.display = '';
		if (rblGuestPaymentMethod[1].checked) divGuestBlainCard.style.display = '';
		if (rblGuestPaymentMethod[2].checked) divGuestGiftCard.style.display = '';
	}
}

// Popup window controls
WebStore.showShipTax = function() {
	if (document.getElementById("shiptax-popupobj")) {
		var txtZip = $id("txtZip");
		WebStore.setShipTaxDetailVisibility('hidden');
		AppGlobal.overlay = new Overlay("shiptax-popupobj");
		txtZip.focus();
		txtZip.select();
		WebStore.calcShipTax();
	}
	return false;
}

WebStore.showCVVHelp = function() {
	if ($id("cvv-popupobj")) {
		WebStore.closePopup();
		AppGlobal.overlay = new Overlay("cvv-popupobj");
	}
	return false;
}
WebStore.showGiftCardHelp = function() {
	if ($id("giftcard-popupobj")) {
		WebStore.closePopup();
		AppGlobal.overlay = new Overlay("giftcard-popupobj");
	}
	return false;
}
WebStore.showNoEconomy = function() {
	if ($id("noecon-popupobj")) {
		WebStore.closePopup();
		AppGlobal.overlay = new Overlay("noecon-popupobj");
	}
	return false;
}
WebStore.closePopup = function() {
	if (AppGlobal.overlay) {
		AppGlobal.overlay.remove();
		AppGlobal.overlay = null;
	}
}
WebStore.showProgress = function() {
	if ($id("progress-popupobj")) AppGlobal.overlay = new Overlay("progress-popupobj");
}

// ******* Shipping and tax calculator
WebStore.shipTaxKeyListener = function() {
	var txtZip = $id("txtZip");
	if (txtZip.value.length == 5 && txtZip.value != WebStore.shipTaxZip) {
		WebStore.shipTaxZip = txtZip.value;
		var imgProgress = $id("imgShipTaxProgress");
		if (imgProgress) imgProgress.style.visibility = 'visible';
		WebStore.setShipTaxDetailVisibility('hidden');
		WebStore.timer = setTimeout(WebStore.calcShipTax, 500);
	}
}
WebStore.setShipTaxDetailVisibility = function(val) {
		var tblTotals = $id("tblTotals");
		var tblArrival = $id("tblArrival");
		tblTotals.style.visibility = val;
		tblArrival.style.visibility = val;
}
WebStore.calcShipTax = function() {
	var txtZip = $id("txtZip");
	var trEconomyShipping = $id("trEconomyShipping");
	var rbEconomyShipping = $id("rbEconomyShipping");
	var rbStandardShipping = $id("rbStandardShipping");
	var rbPriorityShipping = $id("rbPriorityShipping");
	var shipchecked = true;
	if (rbEconomyShipping && rbStandardShipping && rbPriorityShipping) {
		if (!rbEconomyShipping.checked && !rbStandardShipping.checked && !rbPriorityShipping.checked) shipchecked = false;
	}
	if (txtZip.value.length == 5 && shipchecked) {
		WebStore.setShipTaxDetailVisibility('hidden');
		var imgProgress = $id("imgShipTaxProgress");
		var hdnOrderID = $id("hdnOrderID");
		if (imgProgress) imgProgress.style.visibility = 'visible';
		var request = Ajax.newRequest();
		var params = "a=ets";
		params += "&o=" + encodeURIComponent(hdnOrderID.value);
		params += "&z=" + encodeURIComponent(txtZip.value);
		if (rbEconomyShipping && rbStandardShipping && rbPriorityShipping) {
			if (trEconomyShipping.style.display != 'none' && rbEconomyShipping.checked) params += "&sm=ECON";
			else if (rbPriorityShipping.checked) params += "&sm=2DAY";
			else params += "&sm=GRND";
		} else params += "&sm=GRND";
		request.open("POST", WebStore.ajaxURL, true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.setRequestHeader("Content-Length", params.length);
		request.setRequestHeader("Connection", "close");
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				// Display prices table
				if (request.status == 200) {
    		        var xmlDoc = request.responseXML;
					var vSalesTax = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("TotalSalesTax")[0]);
					var vShipping = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("TotalShipping")[0]);
					var vGrandTotal = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("GrandTotal")[0]);
					var vArrival = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("EstimatedArrival")[0]);
					var vValidZipCode = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("ValidZipCode")[0]);
					var vValidLTLDestination = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("ValidLTLDestination")[0]);
					var vCalcError = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("CalcError")[0]);
					var vLTLNoQuote = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("LTLNoQuote")[0]);
					var lblSalesTax = $id("lblSalesTax");
					var lblShipping = $id("lblShipping");
					var lblGrandTotal = $id("lblGrandTotal");
					var lblArrival = $id("lblArrival");
					var lblError = $id("lblError");
					WebStore.shipTaxZip = txtZip.value;
					if (vValidZipCode == "0") {
						WebStore.setShipTaxDetailVisibility('hidden');
						lblError.style.display = '';
						AppGlobal.setText(lblError, "The zip code you entered does not appear to be valid.");
					} else if (vValidLTLDestination == "0") {
						lblError.style.display = '';
						WebStore.setShipTaxDetailVisibility('hidden');
						AppGlobal.setText(lblError, "Freight items cannot be shipped to Alaska or Hawaii.");
					} else if (vLTLNoQuote == "1") {
						lblError.style.display = '';
						WebStore.setShipTaxDetailVisibility('hidden');
						AppGlobal.setText(lblError, "Cannot calculate freight shipping to this zip code. Please call Customer Service at 1-800-210-2370 for assistance.");
					} else if (vCalcError == "1") {
						lblError.style.display = '';
						WebStore.setShipTaxDetailVisibility('hidden');
						AppGlobal.setText(lblError, "Sorry, but we cannot calculate an estimated shipping rate for you at this time. Please try again later.");
					} else {
						lblError.style.display = 'none';
						AppGlobal.setText(lblSalesTax, vSalesTax);
						AppGlobal.setText(lblShipping, vShipping);
						AppGlobal.setText(lblGrandTotal, vGrandTotal);
						AppGlobal.setText(lblArrival, vArrival);
						WebStore.setShipTaxDetailVisibility('visible');
					}
				} else {
					// Get failed status error message
					var message = "Sorry, but an unexpected error occurred with your shopping cart. Please refresh this page in your browser and try again. We apologize for the inconvenience.";
					// Display error message
					alert(message);
				}
				if (imgProgress) imgProgress.style.visibility = 'hidden';
			}
		}
		request.send(params);
		// Track virtual pageview in Google Analytics
		try { pageTracker._trackPageview("/cart/shiptax.aspx"); } catch(err) {}
	}
}

// ******* CLIENT-SIDE VALIDATORS

// Qty validator
WebStore.validateQty = function(sender, e) {
	var hdnMaxQty = $id("hdnMaxQty");
	if (e.Value.length == 0) e.IsValid = false;
	else {
		e.IsValid = (e.Value.isInteger() && parseInt(e.Value) != 0);
		if (hdnMaxQty) {
			var maxqty = parseInt(hdnMaxQty.value);
			if (maxqty < parseInt(e.Value) && maxqty > 0) e.IsValid = false;
		}
	}
}

// Checkout password validators
WebStore.validatePassword = function(sender, e) {
	var rbPasswordYes = $id("rbPasswordYes");
	if (rbPasswordYes.checked) {
		if (e.Value.length > 0) e.IsValid = true;
		else e.IsValid = false;
	} else e.IsValid = true;
}
WebStore.validateNewPassword = function(sender, e) {
	if (e.Value.length >= 5) e.IsValid = true;
	else e.IsValid = false;
}
WebStore.validateVerifyPassword = function(sender, e) {
    var txtPassword = $id("txtPassword");
    if (!txtPassword) txtPassword = $id("txtGuestPassword");
	if (txtPassword.value != e.Value) e.IsValid = false;
}

// PLCC validators
WebStore.validatePLCCFirstName = function(sender, e) {
	if (e.Value.length == 0) e.IsValid = false;
	else if (/([^A-Za-z\s]|\s{2})/.test(e.Value)) e.IsValid = false;
	else e.IsValid = true;
}
WebStore.validatePLCCLastName = function(sender, e) {
	if (e.Value.length == 0) e.IsValid = false;
	else if (/([^A-Za-z'\-\s]|\s{2})/.test(e.Value)) e.IsValid = false;
	else e.IsValid = true;
}
WebStore.validatePLCCAddress = function(sender, e) {
	if (e.Value.length == 0) e.IsValid = false;
	else if (/([^A-Za-z0-9\/\.'\-#\s]|\s{2})/.test(e.Value)) e.IsValid = false;
	else e.IsValid = true;
}
WebStore.validatePLCCCity = function(sender, e) {
	if (e.Value.length == 0) e.IsValid = false;
	else if (/([^A-Za-z\s]|\s{2})/.test(e.Value)) e.IsValid = false;
	else e.IsValid = true;
}
WebStore.validatePLCCPhone = function(sender, e) {
	if (e.Value.length == 0) e.IsValid = false;
	else e.IsValid = /^\d{3}(-)?\d{3}(-)?\d{4}$/.test(e.Value);
}

// State/zip validators
WebStore.validateNewStateZip = function(sender, e) {
	var ddlState = $id("ddlNewShippingState");
	if (ddlState.value != "") e.IsValid = FormValidation.validateStateZip(ddlState.value, e.Value);
	else e.IsValid = true;
}
WebStore.validateEditStateZip = function(sender, e) {
	var ddlState = $id("ddlEditShippingState");
	if (ddlState.value != "") e.IsValid = FormValidation.validateStateZip(ddlState.value, e.Value);
	else e.IsValid = true;
}
WebStore.validateGuestStateZip = function(sender, e) {
	var ddlState = $id("ddlGuestShippingState");
	if (ddlState.value != "") e.IsValid = FormValidation.validateStateZip(ddlState.value, e.Value);
	else e.IsValid = true;
}

// Check for a duplicate customer e-mail
WebStore.duplicateCustomerEmail = function(sender, e) {
	var scriptURL = "/ajax/customers.aspx";
	var cbCreateAccount = $id("cbCreateAccount");
	var email = e.Value;
	if (cbCreateAccount.checked) {
		var request = Ajax.newRequest();
		var params = "a=d&e=" + encodeURIComponent(email);
		// Call script syncronously
		request.open("POST", scriptURL, false);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.setRequestHeader("Content-Length", params.length);
		request.setRequestHeader("Connection", "close");
		request.send(params);
		if (request.status == 200) {
			var xmlDoc = request.responseXML;
			var valid = xmlDoc.getElementsByTagName("DupeExists");
			if (valid[0].firstChild.data == "1") e.IsValid = false;
			else e.IsValid = true;
		} else e.IsValid = false;
	} else e.IsValid = true;
}

// Partial amount validators
WebStore.customerDefaultPartialPaymentValidation = function(sender, e) {
	var cbPartial = $id("cbCustomerDefaultPartial");
	if (cbPartial.checked) {
		if (e.Value.length == 0) e.IsValid = false;
		else FormValidation.isCurrency(sender, e);
	} else e.IsValid = true;
}
WebStore.customerOtherPartialPaymentValidation = function(sender, e) {
	var cbPartial = $id("cbCustomerOtherPartial");
	if (cbPartial.checked) {
		if (e.Value.length == 0) e.IsValid = false;
		else FormValidation.isCurrency(sender, e);
	} else e.IsValid = true;
}
WebStore.customerPartialPaymentValidation = function(sender, e) {
	var cbPartial = $id("cbCustomerPartial");
	if (cbPartial.checked) {
		if (e.Value.length == 0) e.IsValid = false;
		else FormValidation.isCurrency(sender, e);
	} else e.IsValid = true;
}
WebStore.guestPartialPaymentValidation = function(sender, e) {
	var cbPartial = $id("cbGuestPartial");
	if (cbPartial.checked) {
		if (e.Value.length == 0) e.IsValid = false;
		else FormValidation.isCurrency(sender, e);
	} else e.IsValid = true;
}
WebStore.partialPaymentAmount = function(sender, e) {
	var hdnOrderBalance = $id("hdnOrderBalance");
	if (isNaN(hdnOrderBalance.value) || isNaN(e.Value)) {
		e.IsValid = false;
		return;
	}
	OrderBalance = parseFloat(hdnOrderBalance.value);
	var Amount = parseFloat(e.Value);
	if (Amount > OrderBalance || Amount <= 0) e.IsValid = false;
	else e.IsValid = true;
}

// Credit card validators
WebStore.validateEditCVV = function(sender, e) {
	var txtCardNum = $id("txtEditCardNum");
	var pattern = /^\d{3,4}$/;
	if (txtCardNum.value.indexOf("*") == 0) e.IsValid = true;
	else if (txtCardNum.value.length == 0) e.IsValid = false;
	else e.IsValid = pattern.test(e.Value);
}

// Gift card validators
WebStore.validateCustomerGiftCard = function(sender, e) {
	var hdnOrderID = $id("hdnOrderID");
	var txtGiftCardNum = $id("txtCustomerGiftCardNum");
	if (e.Value.length == 0 || txtGiftCardNum.value.length == 0) e.IsValid = false;
	else e.IsValid = FormValidation.validateGiftCard(hdnOrderID.value, txtGiftCardNum.value, e.Value);
}
WebStore.validateGuestGiftCard = function(sender, e) {
	var hdnOrderID = $id("hdnOrderID");
	var txtGiftCardNum = $id("txtGuestGiftCardNum");
	if (e.Value.length == 0 || txtGiftCardNum.value.length == 0) e.IsValid = false;
	else e.IsValid = FormValidation.validateGiftCard(hdnOrderID.value, txtGiftCardNum.value, e.Value);
}

// OnLoad method
WebStore.onLoad = function() {
	var cssprefix = AppGlobal.cssPrefix();
	// Set up item form
	if ($id("frmCheckout")) WebStore.initCheckoutForm();
	// Load background images
	if ($id("giftcard-popupobj") || $id("cvv-popupobj")) (new Image()).src = cssprefix + '/images/interface/cvv_bkg.png';
	if ($id("shiptax-popupobj")) (new Image()).src = cssprefix + '/images/interface/shiptax_popup_bkg.png';
	if ($id("progress-popupobj")) (new Image()).src = cssprefix + '/images/interface/progress_bkg.png';
	// Bust out of frames
	WebStore.bustFrames();
}

// DOM ready handler
$(function() {
	if ($id("btnPlaceOrderNow")) {
		$("#btnPlaceOrderNow").hide();
		$("#divPleaseWait").show();
		setTimeout(function() {
			$("#btnPlaceOrderNow").show();
			$("#divPleaseWait").hide();
		}, 5000);
	}
});

if (window.addEventListener) window.addEventListener("load", WebStore.onLoad, false);
else if (window.attachEvent) window.attachEvent("onload", WebStore.onLoad);
if (window.addEventListener) window.addEventListener("unload", WebStore.closePopup, false);
else if (window.attachEvent) window.attachEvent("onunload", WebStore.closePopup);


