//set some omniture defaults
//set some omniture defaults a
var products = "";
var evar9Key = "";
var haveReviews = "false";
var zcAI2Cp = null;//used to track addItemTocart pointer while displaying zipcodelayer.

function getBaseURL() {
	if(requestIsSecure == "true"){
		return secureBaseUrl;
	} else {
		return unsecureBaseUrl;
	}
}

function goToPage(address) {
	location.href = getBaseURL() + address;
}

function fixSelect(state) {
	var ie6 = /MSIE 6.0/i.test(navigator.appVersion);
	if(ie6) {
		if ($.browser.msie) {
			if (state == true) {
				$("#globalNav[select]").css("visibility","hidden");
			} else {
				$("#globalNav[select]").css("visibility","visible");
			}
		}
	}
}

$(function(){ swapImg($(".rollover"),"both"); });

function swapImg(o,s){ // assumes "_on" and "_off" as the two states
   if (o.attr("src")) {
		o.unbind();
		imgExt = o.attr("src").substr(o.attr("src").lastIndexOf('.'),o.attr("src").length);
		imgPath = o.attr("src").substr(0,o.attr("src").lastIndexOf('/')) + '/';
		if (s == "both") {
			o.each(function(){
				$(this).hover(function(){
					$(this).attr("src",imgPath + $(this).attr("id") + "_on" + imgExt);
				},function(){
					$(this).attr("src",imgPath + $(this).attr("id") + "_off" + imgExt);
				});
			});
		} else if (s == "on") {
			o.attr("src",imgPath + o.attr("id") + "_on" + imgExt);
		} else if (s == "off") {
			o.attr("src",imgPath + o.attr("id") + "_off" + imgExt);
		}
	}
}



function showTabCom(objComDivId) {
     var imgPath = "<util:envurl path="/assets/images/shopping/" env=\"images\" />";
     var objComDivArr = new Array("tab-more-info","tab-files","tab-review","tab-email-friend","tab-products");
     for (i = 0; i < objComDivArr.length; i++) {
          if (document.getElementById(objComDivArr[i] + "-img")) {
               document.getElementById(objComDivArr[i] + "-img").src = imgPath + objComDivArr[i] + "-off.gif";
               document.getElementById(objComDivArr[i]).style.display = "none";
          }
     }
     document.getElementById(objComDivId + "-img").src = imgPath + objComDivId + ".gif";
     document.getElementById(objComDivId).style.display = "block";
}

utilityBrowserVer = parseInt(navigator.appVersion);

function imgOn(imgName) {
  	if (utilityBrowserVer >= 3) {
		imgOnString = eval(imgName + "_on.src");
		document.images[imgName].src = imgOnString;
	}
}

function imgOff(imgName) {
	if (utilityBrowserVer >= 3) {
		imgOffString = eval(imgName + "_off.src");
		document.images[imgName].src = imgOffString;
	}
}

function goToLink(address) {
	var linkURL = address.options[address.selectedIndex].value;
	window.top.location.href = linkURL;
	address.selectedIndex=0;
}



function openWindow(address, width, height,features)
{
	
	if(features)
		features = features.toLowerCase();
	else
		features = "";

	var toolbar = (features == "all" ? 1 : 0);
	var menubar = (features == "all" ? 1 : 0);
	var location = (features == "all" ? 1 : 0);
	var directories = (features == "all" ? 1 : 0);
	var status = (features == "all" ? 1 : 0);
	var scrollbars = (features == "all" ? 1 : 0);
	var resizable = (features == "all" ? 1 : 0);


	if(features != "all")
	{
		//split features
		var feature = features.split(",");
		for(i = 0; i < feature.length; i++)
		{
		 	if(feature[i] == "toolbar")
			   toolbar = 1;
			else if(feature[i] == "menubar")
			   menubar = 1;
			else if(feature[i] == "location")
			   location = 1;
			else if(feature[i] == "directories")
			   directories = 1;
			else if(feature[i] == "status")
			   status = 1;
			else if(feature[i] == "scrollbars")
			   scrollbars = 1;
			else if(feature[i] == "resizable")
			   resizable = 1;
		}

	}
	features = "toolbar=" + toolbar + ",";
	features += "menubar=" + menubar + ",";
	features += "location=" + location + ",";
	features += "directories=" + directories + ",";
	features += "status=" + status + ",";
	features += "scrollbars=" + scrollbars + ",";
	features += "resizable=" + resizable;

	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',"' + features + '"');
	newWindow.focus();
}


function confirmWindow(url, text) {

	if (confirm(text)) {
		window.go = url;
		window.location = url;
	}
}


function redirectOpener(url, setOpenerFocus, closeWindow) {
	window.opener.location = url;
	if ((setOpenerFocus != null) && (setOpenerFocus)) {
		window.opener.focus();
	}
	if ((closeWindow != null) && (closeWindow)) {
		window.close();
	}
}


function setAddTo(addToType) {
	document.productForm.addTo.value = addToType;
}

// This is an example of sending product data from the server
// to the client, then formatting the variants on the client-side
// based on certain criteria.
function cbFormatter(list, attribute, opt)
{
	// Get the price for this variant.. If this is the primary list, get all related
	// variants from the group and get their prices as well so we can build a range.
	var pvds = list.productVariantDropdownSupport;

	// Get all of the product variants for this attribute
	var variantGroup = attribute.getVariant().getProductVariantGroup();
	var groupVariants = variantGroup.getAllVariants();

	// Are all of the prices the same within the group?
	var lowGroupPrice = 999999.00;
	var highGroupPrice = -1.00;

	for (var idx = 0; idx < groupVariants.length; idx++)
	{
      lowGroupPrice = groupVariants[idx].numericPrice < lowGroupPrice ? groupVariants[idx].numericPrice : lowGroupPrice;
		highGroupPrice = groupVariants[idx].numericPrice > highGroupPrice ? groupVariants[idx].numericPrice : highGroupPrice;
   }

	// Are all of the prices the same within the variant?
	var variants = variantGroup.getVariantsMatching(attribute.name, attribute.value);
	var lowVariantPrice = 999999.00;
	var highVariantPrice = -1.00;

	var lowVariantDisplay = variants[0].displayPrice;
	var highVariantDisplay = variants[0].displayPrice;

   for (var idx = 0; idx < variants.length; idx++)
   {
		// Display really needs to be done before the re-assignment...
      lowVariantDisplay = variants[idx].numericPrice < lowVariantPrice ? variants[idx].displayPrice : lowVariantDisplay;
      lowVariantPrice = variants[idx].numericPrice < lowVariantPrice ? variants[idx].numericPrice : lowVariantPrice;
      highVariantDisplay = variants[idx].numericPrice > highVariantPrice ? variants[idx].displayPrice : highVariantDisplay;
		highVariantPrice = variants[idx].numericPrice > highVariantPrice ? variants[idx].numericPrice : highVariantPrice;
   }

	if (lowGroupPrice != highGroupPrice)
	{
		// Primary list should display a range
		if (pvds.isPrimary)
			if (lowVariantPrice != highVariantPrice)
				opt.text = opt.text + " " + lowVariantDisplay + " - " + highVariantDisplay;
			else
				opt.text = opt.text + " " + attribute.getVariant().displayPrice;
		else  // Secondary lists should show exact price
			opt.text = opt.text + " " + attribute.getVariant().displayPrice;
	}

   return opt;
}


	function setSubject(thisRef)
	{
		var formRef = document.forms["contactUsForm"];
		//set subject value
		formRef.elements["subject"].value = (thisRef.options[thisRef.selectedIndex]).text;
	}



function doSearchFocus(component) {

		var searchVal = component.value;//document.searchForm.keyword.value;
		if (searchVal == "Product Name or Item #") {
			//document.searchForm.keyword.value = "";
			component.value = "";
		}
	return true;
	}
	function doSearchBlur(component) {
		var searchVal = component.value;//document.searchForm.keyword.value;
		if (strTrim(searchVal) == '') {
			//document.searchForm.keyword.value = "enter keyword or item #";
			component.value = "Product Name or Item #";
			return false;
		}
		return true;
	}

function doSearchSubmit() {
		var searchVal = document.searchForm.keyword.value;
		if (searchVal == "Product Name or Item #" || strTrim(searchVal) == '' ) {
			document.searchForm.keyword.value = "Product Name or Item #";
			return false;
		}
	document.searchForm.submit();
	return true;
	}
	function strTrim(s) {
		// Remove leading spaces and carriage returns
		while (s.substring(0, 1) == ' ') {
			s = s.substring(1, s.length);
		}
        // Remove trailing spaces and carriage returns
		while (s.substring(s.length - 1, s.length) == ' ') {
			s = s.substring(0, s.length - 1);
		}
		return s;
	}


// Returns the number of allowed characters remaining for a field.
// If the length of the field exceeds the total number of allowed
// characters the value will be truncated to the total allowed.

function getCharactersRemaining(field, totalCharacters) {
     var len = 0;
     if (field != null) {
       len = field.value.length;
     }
     if (len > totalCharacters) {
       field.value = field.value.substring(0, totalCharacters);
       len = totalCharacters;
     }
     return (totalCharacters - len);
}

function updateRemainingCharacters(field, displayElement, totalCharacters) {
	var remainingCharacters = getCharactersRemaining(field, totalCharacters);
	if (displayElement != null) {
	  displayElement.innerHTML = remainingCharacters;
	}

	return remainingCharacters;
}



	var targetId = "";
	var target = "";

	function showHideDetails(targetId){
	if(document.getElementById) {
		if(document.getElementById(targetId)) {
			target = document.getElementById(targetId);
				if (target.className == "hide") {
								target.className = "show";
				}else{
								target.className = "hide";
				}
			}
		}
	}


	function showDetails(targetId){
		if(document.getElementById) {
			if(document.getElementById(targetId)) {
				target = document.getElementById(targetId);
				target.className = "show";
			}
		}
	}

	function hideDetails(targetId){
		if(document.getElementById) {
			if(document.getElementById(targetId)) {
				target = document.getElementById(targetId);
					if (target.className == "show") {
						target.className = "hide";
					}
				}
		}
	}


function openZipCodeWindow() {
	// url_zipcode is defined in common_js.jsp
	openWindow(url_zipcode, 300, 200, "menubar=no, location=no, directories=yes, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no");
}

function setOperation(opType,needSubmit,addressIndex) {
	document.addUpdateDeleteAddressForm.operation.value = opType;
	if(addressIndex) {
		document.addUpdateDeleteAddressForm.selectedAddressIndex.value = addressIndex;
		if(needSubmit) {
			if(opType == "EDIT") {
				// url_address_book is defined in common_js.jsp
				window.location = url_address_book + addressIndex;
			} else {
				document.addUpdateDeleteAddressForm.submit();
			}
		}
	}
}

function zipCodeVal() {
	$("input[@name=zipCode]").blur(function() {
		valInput = $.trim($(this).val());
		if (valInput == "") {
			$(this).attr("value","ZIP Code");
		}
	});
	$("input[@name=zipCode]").focus(function() {
		valInput = $.trim($(this).val());
		if (valInput == "ZIP Code" || valInput == "") {
			$(this).attr("value","");
		}
	});
}

function hideShowFavoriteImage(clickedClass, favoriteImageId) {
   if (document.getElementById(favoriteImageId) != null) {
	   if (clickedClass == "add-fav") {
	      document.getElementById(favoriteImageId).className = "bursts show";
	   } else if (clickedClass == "rem-fav") {
	      document.getElementById(favoriteImageId).className = "hide";
	   }
   }
   //$("#favoriteImageId").hide();
}

function injectProcessing(el,inProcess,processClass,customData) {
	clickedClass = "";
	if(processClass != null)
		clickedClass = processClass;

	if (inProcess == true) {
		$(el).hide();
		if ($(el).prev() && $(el).prev().attr("class") == 'addedCartAjax') {
			$(el).prev().remove();
		}
		$("<p class='processing " + clickedClass + "' type='processing'>Processing...</p>").insertBefore($(el));
	} else {
		if ($(el).prev() && $(el).prev().attr("type") == "processing") {
			$(el).prev().remove(); //remove processing message
		}
		if (clickedClass == "add-fav") {
			//the call is from a add-fav button
			var typeToMatch = "remove_fav";
			//test if it's from the nutritional view
			if ($(el).attr("type").indexOf("nutr") >= 0)
				typeToMatch = "nutr_remove_fav";
			if ($(el).next().attr("type") == typeToMatch) {
				//if the remove button is already there, just show it
				$(el).next().show();
			} else {
				//add the remove from fav after the hidden add to fav button in the DOM
				if (typeToMatch == "nutr_remove_fav") {
					$("<a href='javascript:void(0);' onclick='" + customData + "' type='nutr_remove_fav'><img src='" + imagesBaseUrl + "buttons/btn_remove_from_fav-narrow.gif' alt='Remove From Favorites' /></a>").insertAfter($(el));
				} else {
					$("<a href='javascript:void(0);' onclick='" + customData + "' type='remove_fav'><img src='" + imagesBaseUrl + "buttons/btn_remove_fav.gif' alt='Remove From Favorites' /></a>").insertAfter($(el));
				}
			}
			return; // don't show the original el (the add to fav button)
		} else if (clickedClass == "rem-fav") {
			//the call is from a rem-fav button
			//test if it's from the layer favs
			if ($(el).attr("type").indexOf("layer") >= 0){
				var favADD = 'favadd_' + customData;
				var favRM = 'favrm_' + customData;
				if(document.getElementById(favRM)){
					document.getElementById(favRM).style.display = "none";
				}
				if(document.getElementById(favADD)){
					document.getElementById(favADD).style.display = "block";
				}
				return;//no need to place an add link back in
			}
			var typeToMatch = "add_fav";
			//test if it's from the nutritional view
			if ($(el).attr("type").indexOf("nutr") >= 0)
				typeToMatch = "nutr_add_fav";
			if ($(el).prev().attr("type") == typeToMatch) {
				//if the add button is already there, just show it
				$(el).prev().show();
			}
			return; // don't show the original el (the add to fav button)
		} else if (clickedClass == "add-cart") {
			//message that the cart has been added
			if ($(el).prev() && $(el).prev().attr("class") == 'addedCartAjax') {
				$(el).prev().remove();
			}
			//omniture tracking
			if($(el).attr("class") && $(el).attr("class").indexOf("scTrack:") > 0){
				s.eVar11=$(el).attr("class").substring($(el).attr("class").lastIndexOf(":") + 1);
			}
			$("<p class='addedCartAjax'>This item has been added to your cart.</p>").insertBefore($(el));

		} else if(clickedClass == "meal-fav"){
			//if meal is add to fav then don't show remove link.
			return;
		}
		$(el).show();
	}
}

function injectLoader(el,state) {
	if (state) {
		$(el).html("<div class='loader'></div>");
		fixLayerCartIframe('open'); //keeps the iframe height in sync
	} else {
		$(".loader",el).remove();
	}
}


var oldState = 'off';
var changeLayerCartState = function(newState) {
	clearLCTimer(); //ensure the timer is cleared from previous actions
	if (newState == 'off'){
		$("#layerCart").hide();
		$("#layerCartBody").hide();
		$("#layerFavBody").hide();
		$("#layerCartBody").html('');
		$("#layerFavBody").html('');
		$("#layerCart_tabs").removeClass().addClass("lc_status_off");
		fixLayerCartIframe('close');
		unbindListeners();
	} else {
		if (newState == "fav") {
			$("#layerCart").show();
			$("#layerFavBody").show();
			$("#layerCartBody").hide();
			$("#layerCartBody").html('');
			$("#layerCart_tabs").removeClass().addClass("lc_status_fav");
		} else if (newState == "cart") {
			$("#layerCart").show();
			$("#layerCartBody").show();
			$("#layerFavBody").hide();
			$("#layerFavBody").html('');
			$("#layerCart_tabs").removeClass().addClass("lc_status_cart");
		}
		if (oldState == 'off') {
			//prevents us from rebinding while switching between cart and favs without closing
			$("#wrapper").bind('click', function(e) { layerClickOff(e);} );
			//only open iframe if the layer was previously off
			fixLayerCartIframe('open');
		}
	}
	oldState = newState;
};

function layerClickOff(event) {
	var clickedEl = event.target;
	var targetEl = clickedEl;
	while (targetEl.id != undefined && targetEl.id != 'wrapper') {
		if (targetEl.id == 'layerCart') {
			//the user has clicked inside of the layerCart, so we need to allow that link to execute
			break;
		} else {
			targetEl = targetEl.parentNode;
		}
	}
	if (targetEl.id == 'wrapper'){
		event.preventDefault();
		changeLayerCartState('off');
	}
};

function layerScrollerInit(mode) {
	var key;
	if (mode == "cart")
		key = "lc_cart";
	else if (mode == "favs")
		key = "lc_fav";

	if (key != null) {
		var arrItemsHeight = new Array();
		var itemsHeight = 0;
		$(".lc_item").each(function(i){
			arrItemsHeight[i] = $(this).height();
			if (i < 4) {
				itemsHeight += $(this).height();
			}
		});
		$("#"+key+"_scroll").height(itemsHeight);
		//need to add extra pix for justAdded class
	
	//	$(".mid","#layerCart").height($(".inner","#layerCart").height());
		if (arrItemsHeight.length > 4) {
			$("#"+key+"_down img").attr("src",imagesBaseUrl+"layercart/scroll_down_on.gif");
		}
		var animating = false;
		var sCount = 4;
		var itemsCount = arrItemsHeight.length;
		$("#"+key+"_down a").click(function() {
			if (!animating && (sCount + 1 <= itemsCount)) {
				animating = true;
				var curPos = parseInt($("#"+key+"_scroll_inner").css("top"));
				var animateTop = curPos - arrItemsHeight[sCount];
				$("#"+key+"_scroll_inner").animate({top: animateTop},"normal",function(){
					$(this).css("top",animateTop);
				});
				sCount++;
				animating = false;
			}
			if (sCount > 4) {
				$("#"+key+"_up img").attr("src",imagesBaseUrl+"layercart/scroll_up_on.gif");
			}
			if (sCount == itemsCount) {
				$("#"+key+"_down img").attr("src",imagesBaseUrl+"layercart/scroll_down_off.gif");
			}
			return false;
		});

		$("#"+key+"_up a").click(function() {
			if (!animating && (sCount > 4)) {
				animating = true;
				sCount--;
				var curPos = parseInt($("#"+key+"_scroll_inner").css("top"));
				var animateTop = curPos + arrItemsHeight[sCount];
				$("#"+key+"_scroll_inner").animate({top: animateTop},"normal",function(){
					$(this).css("top",animateTop);
					animating = false;
				});
			}
			if (sCount == 4) {
				$("#"+key+"_up img").attr("src",imagesBaseUrl+"layercart/scroll_up_off.gif");
			}
			if ((sCount != itemsCount) && (arrItemsHeight.length > 4)) {
				$("#"+key+"_down img").attr("src",imagesBaseUrl+"layercart/scroll_down_on.gif");
         }

			return false;
		});
		fixLayerCartIframe('open');//this ensures the iframe height is reset once the new data has been writted into layercart
		setLayerCartTimer();
	}
}

function fixLayerCartIframe(key) {
	var iframe = document.getElementById('layerCart_iframe');
	if (iframe != null) {
		if (key == 'open') {
			var lcHeight = $("#layerCart").height();
			$("#layerCart_iframe").height(lcHeight);
			$("#layerCart_iframe").show(); //this line has nothing to do with nonsecure warnings
			//document.getElementById("layerCart_iframe").style.display="inline"; // this ensures that the cart layer will not cause nonsecure items warning on IE6
		}
		if (key == 'close') {
			$("#layerCart_iframe").height(1);
			$("#layerCart_iframe").hide();
		}
	}
}

var lcTimer = null;
var totalTimerCount = 0;

function timerAction() {
	changeLayerCartState('off');
	//sCount = 4;
	totalTimerCount = 0;
}

function adjustTimer() {
	if (totalTimerCount > 0) {
		clearLCTimer();
		adjustTimer();
	}
	if (totalTimerCount == 0) {
		lcTimer = setTimeout("timerAction()", 5000);
		totalTimerCount++;
	}
}

function clearLCTimer() {
	if (totalTimerCount > 0) {
		clearTimeout(lcTimer);
		totalTimerCount--;
	}
}

function setLayerCartTimer() {
	return; //uncomment to kill timer
	adjustTimer();

	$("#layerCart").bind("mouseleave", function() {
		adjustTimer();
	} );
	$("#layerCart").bind("mouseenter", function() {
		clearLCTimer();
	});
	$("#layerCart_tabs").bind("mouseenter", function() {
		clearLCTimer();
	} );
}

function unbindListeners() {
	$("#wrapper").unbind();
	$("#layerCart").unbind("mouseleave");
	$("#layerCart").unbind("mouseenter");
	$("#layerCart_tabs").unbind("mouseenter");
}

//function getLayerCart(clickObject,addedData,isZipCodeLayer) {
//	var cartPath = getContextPath() + "checkout/basket.aspx";
//	changeLayerCartState('cart');
//	injectLoader("#layerCartBody",true);
//	
//	$.ajax({
//		type: "GET",
//		url: cartPath,
//		cache: false,
//		success:function(data) {
//			if (clickObject != null)
//				injectProcessing(clickObject,false,"add-cart");
//			$("#layerCartBody").html(data);
//			sentAjaxImage = "true";
//			layerScrollerInit("cart");
//		}
//	});
//}

function getLayerFavs(clickObject,addedData) {
	var addedObj = null;
	var cartPath = getContextPath() + "includes/layer_favs.jsp";
	var isMeal = false;
	if (addedData != null) {
		addedObj = eval("(" + trimString(addedData)+ ")");
		cartPath += "?itemAdded=" + addedObj.itemAdded;
		
		try{
			if(addedObj.mealPIds != null){
				cartPath += "&mealPIds=" + addedObj.mealPIds;
				isMeal = true;
			}
			if(addedObj.mealMessage != null){
				cartPath += "&mealMsg=" + addedObj.mealMessage;
			}
		}catch(e){
			//ignore
		}
	}
	changeLayerCartState('fav');
	injectLoader("#layerFavBody",true);
	$.ajax({
		type: "GET",
		url: cartPath,
		cache: false,
		success: function(data) {
			if (addedData != null && clickObject != null)
				
				if(!isMeal){
					injectProcessing(clickObject,false,'add-fav','removeFromFavs(this,"' + addedObj.itemAdded + '");');
				}else{
					injectProcessing(clickObject,false, 'meal-fav');
				}
			$("#layerFavBody").html(data);
			layerScrollerInit("favs");
		}
	});
}

function updateItemCount(addedObj) {
	
}

function addToFavs(pId,pTypeId,pQuantity,buttonObj){
	var addPath = getContextPath() + "checkout/add_item_ajax.cmd?productId="+pId+"&productVariantId=0&productTypeId="+pTypeId+"&quantity="+pQuantity+"&loadType=AJAX&addTo=2";
	$.ajax({
		type: "GET",
		url: addPath,
		cache: false,
		success: function(data) {
			getLayerFavs(buttonObj,data);
		}
	});
}

function addToCart(pId,pVarId,pQuantity,buttonObj, isMoveToCart){
	//var addPath = getContextPath() + "checkout/add_item_ajax.cmd?"+"productId="+pId+"&productVariantId="+pVarId+"&quantity="+pQuantity+"&loadType=AJAX" + (queryString != "" ? ("&" + queryString) : "") +  (isMoveToCart ? ("&isMoveFromWishlist=" + isMoveToCart) : "");
	var addPath = getContextPath() + "addToCart.ashx?" + "productId=" + pId + "&quantity=" + pQuantity;
	$.ajax({
		type: "GET",
		url: addPath,
		cache: false,
		success: function(data) {
			getLayerCart(buttonObj,data);
		}
	});
}

function removeFromCart(buttonObj,itemIndex,orderIndex,itemUUID) {
	sentAjaxImage = "false";
	injectProcessing(buttonObj,true);
	var path = getContextPath() + "checkout/delete_item_from_order.cmd?itemIndex=" + itemIndex + "&orderIndex=" + orderIndex + "&itemUUID=" + itemUUID + "&loadType=AJAX";
	changeLayerCartState('cart');
	injectLoader("#layerCartBody",true);
	$.ajax({
		type: "GET",
		url: path,
		cache: false,
		success: function(data) {
			injectProcessing(buttonObj,false,'rem-cart');
			$("#layerCartBody").html(data);
			sentAjaxImage = "true";
			layerScrollerInit("cart");
		}
	});
}

function removeFromFavs(buttonObj,productId) {
	injectProcessing(buttonObj,true);
	var path = getContextPath() + "user/delete_item_from_wishlist_ajax.cmd?itemIndex=" + productId;
	changeLayerCartState('fav');
	injectLoader("#layerFavBody",true);
	$.ajax({
		type: "GET",
		url: path,
		cache: false,
		success: function(data) {
			injectProcessing(buttonObj,false,'rem-fav', productId);
			$("#layerFavBody").html(data);
			layerScrollerInit("favs");
		}
	});
}

	function validateZipCode(formName) {
		var zipCode = document.forms[formName != null ? formName : "zipCodeForm"].zipCode.value;
		zipCode = strTrim(zipCode);
		if (zipCode.length == 0) {
			return 1; // missing
		}

		if (zipCode.length == 5) {
			if (!isNaN(zipCode)) {
				return 0; // valid
			}
		} else if (zipCode.length > 5) {
			if(zipCode == 'Enter ZIP Code'){
				return 1; // missing
			}
			if (zipCode.charAt(5) == '-') { // Make sure the sixth char is a '-'
				zipCode = zipCode.replace("-", "");
				if (zipCode.length == 9 && !isNaN(zipCode)) {
					return 0; // valid
				}
			}
		}
		return 2; // invalid ZIP code
	}

var isProcessingZipCodeData = false; //Prevents multiple submission of same form
	function processData(formName) {
		if(isProcessingZipCodeData){
			return false;
		}
		isProcessingZipCodeData = true;
		var errorCode = 0;
		if(formName == ""){
			formName = null;
		}
		errorCode = validateZipCode((formName == 'catalogOrderForm' ? null : formName));
		if (errorCode == 1) // missing ZIP code
		{
			showZipCodeError("Please enter a ZIP code.");
		} else if (errorCode == 2) // invalide ZIP code
		{
			showZipCodeError("Please enter a valid ZIP code.");
		} else if(errorCode == 0){
			var hasError = false; // fix for case: we open the schwans site from a link in the email or something like that
			try {
				if (window.opener) {
					window.opener.document.getElementsByName("zipCode")[0].value = document.forms[formName != null ? formName : "zipCodeForm"].zipCode.value;
					window.opener.submitData();
					window.close();
					isProcessingZipCodeData = false;
					return false;
				}
			} catch (e) {
				hasError = true;
			}
			if (hasError || window.opener == null) {
				
				if(formName != null){
					
					if(formName == "catalogOrderForm"){
						document.forms[formName].zipCode.value = document.forms["zipCodeForm"].zipCode.value;
						var qsProductStyle = getQSProductStyle();
						var qsProductQuantity = getQSProductQuantity();
						document.forms[formName].styles.value = qsProductStyle;
						document.forms[formName].qty.value = qsProductQuantity;
						document.forms[formName].submit();
						isProcessingZipCodeData = false;
						return false;
					}
				}
				document.forms[formName != null ? formName : "zipCodeForm"].submit();
				isProcessingZipCodeData = false;
				return true;
			}
		}
		isProcessingZipCodeData = false;
		return false;
	}




	
	function showZipCodeError(message){
		var isZipCodeLayerMode = true;
		try{isZipCodeLayerMode = $("#overlayPanel").css("display") == "block" ? true : false;}catch(e){}
		if(isZipCodeLayerMode){
			try{$("#zipcodeLayerError")[0].innerHTML = message;}catch(e){}
			try{$("#zipcodeLayerError").show();}catch(e){}
		}else{
			try{$("#errorMessage")[0].innerHTML = message;}catch(e){}
			try{$("#divError").show();}catch(e){}
		}
	}

    
	function hideErrorMessage() {
		var isZipCodeLayerMode = true;
		try{isZipCodeLayerMode = $("#overlayPanel").css("display") == "block" ? true : false;}catch(e){}
		if(isZipCodeLayerMode){
			try{$("#zipcodeLayerError")[0].innerHTML = "";}catch(e){}
			try{$("#zipcodeLayerError").css("class","hide");}catch(e){}
			document.zipCodeForm.zipCode.value = "";
			document.zipCodeForm.zipCode.maxLength = 5;
		}else{
			try{$("#errorMessage")[0].innerHTML = "";}catch(e){}
			try{$("#divError").hide();}catch(e){}
			document.DeliveryModuleForm.zipCode.value = "";
			document.DeliveryModuleForm.zipCode.maxLength = 5;
		}

	}


	function preventDuplicateZipCodeSubmission(){

	}

function clearDefaultMsg(textBox) {
	if (textBox != null && textBox.value.toLowerCase().indexOf("enter") > -1)
		textBox.value = "";
}

function addDefaultMsg(textBox) {
	if (textBox != null && trimString(textBox.value) == ""){
		var isZipCodeLayerMode = true;
		try{isZipCodeLayerMode = $("#overlayPanel").css("display") == "block" ? true : false;}catch(e){}
		if(isZipCodeLayerMode){
			document.zipCodeForm.zipCode.maxLength = 14;
			document.zipCodeForm.zipCode.value = "Enter Zip Code";
		}else{
			document.DeliveryModuleForm.zipCode.maxLength = 14;
			document.DeliveryModuleForm.zipCode.value = "Enter Zip Code";
		}
	}
}


function trimString(str) {
  return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};


function replace(string,text,by) {
   // Replaces text with by in string
   var strLength = string.length, txtLength = text.length;

   if ((strLength == 0) || (txtLength == 0)) {
      return string;
   }

   var i = string.indexOf(text);

   if ((!i) && (text != string.substring(0, txtLength))) {
      return string;
   }

   if (i == -1) {
      return string;
   }

   var newstr = string.substring(0, i) + by;

   if (i + txtLength < strLength) {
      newstr += replace(string.substring(i + txtLength, strLength), text, by);
   }

   return newstr;
}

function replaceHREF(context, host) {
   var anchorTags = document.getElementsByTagName("a");

   for (var i = 0; i < anchorTags.length ; i++) {
       hrefVal = anchorTags[i].href;

		if(context && hrefVal.substring(0, 10).toUpperCase() != "JAVASCRIPT"){
			//if we are local and the context is missing -> add it.
			if(hrefVal.indexOf(context) == -1) {
				//if there is a full url
				if(hrefVal.indexOf(host) != -1) {
					hrefVal = replace(hrefVal, host, host + context);
				}else {
					hrefVal = context + hrefVal;
				}
			}
		}
		anchorTags[i].href = hrefVal;
	}
}


function replaceIMGHREF(unsecure, secure, isSecure, context, host) {
   var imgTags = document.getElementsByTagName("img");

   for (var i = 0; i < imgTags.length ; i++) {
      src = imgTags[i].src;
		if(src.indexOf(host) != -1){
			if (isSecure  == "true") {
				src = replace(src, unsecure, secure);
			} else {
				src = replace(src, secure, unsecure);
			}
		}
		if(context && src.substring(0, 10).toUpperCase() != "JAVASCRIPT"){
			//if we are local and the context is missing -> add it.
			if(src.indexOf(context) == -1) {
				//if there is a full url
				if(src.indexOf(host) != -1) {
					src = replace(src, host, host + context);
				}else {
					src = context + src;
				}
			}
		}
		imgTags[i].src = src;
	}
}


function fixAllLinks(unsecure, secure, isSecure, context, host){
	 //replaceIMGHREF(unsecure, secure, isSecure, context, host);
	 replaceHREF(context, host);

}

function SetCookie (name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
   var today = new Date();
   today.setTime( today.getTime() );

   // if the expires variable is set, make the correct
   // expires time, the current script below will set
   // it for x number of days, to make it for hours,
   // delete * 24, for minutes, delete * 60 * 24

   if (expires) {
      expires = expires * 1000 * 60 * 60 * 24;
   }

   var expires_date = new Date( today.getTime() + (expires) );
	var cookieString = name + "=" + escape (value);
	cookieString += ";" +
      ((expires) ? "; expires=" + expires_date.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
	//document.cookie = cookieString;

	 document.cookie = name + "=" + escape (value) +
      ((expires) ? "; expires=" + expires_date.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}

function GetCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function ShowZipCodeForm() {
	document.getElementById("zipDelivery").style.display = "none";
	document.getElementById("zipCodeFm").style.display = "block";
	document.zipCodeForm.zipCode.value = "Enter Zip Code";

}
function getOmnitureProductsString(product, qty, sku, price, haveRatings, source){
	var returnStr = "";
	var ratingString = "No Rating";
	if(haveRatings == "true"){
		ratingString= "Has Rating";
	}
	if(products && products != ""){
		returnStr = ",;";
	} else {
		returnStr = ";";
	}
	if(source == "cart"){
		returnStr += product + ";;;;"//evar5=" + sku;
	}else if(source == "product"){
		returnStr += product + ";;;;evar9="+ ratingString;
	}else {
		//thumnbnail
		returnStr += product;
	}

	return returnStr;
}


function isZipCodeSet(){
	var status = synchronousHttpRequest(getContextPath() + "/user/isZipCodeSet.ashx",null);
	if(status != "true"){
		return false;
	}else{
		return true;
	}
}



function performAddFavs(buttonObj,productId,usagePrefix,isMeal) {
	performAdd(buttonObj,productId,usagePrefix,true,isMeal);
}



function performMove(buttonObj,productId,isMove,usagePrefix) {
   performAdd(buttonObj,productId,usagePrefix,false,false,isMove);
}



function performAdd(buttonObj,productId,usagePrefix,addToFavFlag,isMeal, isMoveToCart) {
	usagePrefix = (usagePrefix == null ? "#" : "#" + usagePrefix);

	var variantSelectorObj = $((usagePrefix + "varId_" + productId));
	var quantity = $((usagePrefix + "qty_" + productId)).val();
	var errorMsgId = $((usagePrefix + "varError_" + productId));
	var qtyErrorMsgId =  $((usagePrefix + "qtyError_" + productId));
	var quantityObj = $((usagePrefix + "qty_" + productId));

	
	if (!addToFavFlag) {
		var variantId = null;
		if(variantSelectorObj != null){
			variantId = variantSelectorObj.val();
			
			if(parseInt(variantId) == 0){
				if(errorMsgId != null){
					errorMsgId.show();
					return;
				}else{
					return; //Can't proceed the variant drop down is shown but doesn't have a valid variant selected.
				}
			}
		}

		if(variantId == null){
			variantId = $((usagePrefix + "varId_" + productId)).val();
		}

		if(isNaN(quantity) || quantity < 1){
			qtyErrorMsgId.show();
			return;
		}
	}


	
	var injectClass = addToFavFlag ? "add-fav" : "add-cart";
	injectProcessing(buttonObj,true,injectClass);

	if(quantity == null || quantity == ""){
			$("input[@name=quantity]").val($((usagePrefix + "qty_" + productId + "_bottom")).val());
	}

	if (!addToFavFlag) {
		//add to cart is the default behavior
//		if(!isZipCodeSet()){
//			$("input[@name=productId]").val(productId);
//			$("input[@name=productVariantId]").val(variantId);
//			$("input[@name=quantity]").val(quantity);
//			
//			zcAI2Cp = buttonObj;
//			showZipCodeLayer();
//		} else {
			addToCart(productId,variantId,quantity,buttonObj,isMoveToCart);
//		}
	} else {
		var typeId = $((usagePrefix + "typeId_" + productId)).val();
		addToFavs(productId,typeId,quantity,buttonObj);
	}
}

function performAddBundle(buttonObj, productId, iQty, isMeal, isMoveToCart) {
    
    var injectClass = "add-cart";
    injectProcessing(buttonObj, true, injectClass);

    if (iQty == null || iQty == "") {
        $("input[@name=quantity]").val($((usagePrefix + "qty_" + productId + "_bottom")).val());
    }

    addToCart(productId, productId, iQty, buttonObj, isMoveToCart);
}


function performUpdate(buttonObj,productId,usagePrefix,actionPath){
	
	usagePrefix = (usagePrefix == null ? "#" : "#" + usagePrefix);

	var variantSelectorObj = $((usagePrefix + "varId_" + productId));
	var quantity = $((usagePrefix + "qty_" + productId)).val();
	var errorMsgId = $((usagePrefix + "varError_" + productId));
	var qtyErrorMsgId =  $((usagePrefix + "qtyError_" + productId));
	var quantityObj = $((usagePrefix + "qty_" + productId));


	
	var variantId = null;
	if(variantSelectorObj != null){
		variantId = variantSelectorObj.val();
		if(parseInt(variantId) < 1){
			if(errorMsgId != null){
				errorMsgId.show();
				return;
			}else{
				return; //Can't proceed the variant drop down is shown but doesn't have a valid variant selected.
			}
		}
	}

	if(variantId == null){
		variantId = $((usagePrefix + "varId_" + productId)).val();
	}
	if(typeof(quantityObj) != 'object'){
			quantity = $((usagePrefix + "qty_" + productId + "_bottom")).val();
			quantityObj = $((usagePrefix + "qty_" + productId + "_bottom"));
	}


	if(isNaN(quantity) || quantity < 1){
		//quantity = "1";
		//ry{quantityObj.val("1");}catch(e){}
		qtyErrorMsgId.show();
		return;
	}




	
	updateForm = document.forms["updateItemForm"];//Ensure to keep the name in synch with the template_main hidden update form
	if(actionPath != null ){
		updateForm.action = actionPath;
	}
	updateForm.elements["productId"].value = productId;
	updateForm.elements["productVariantId"].value = variantId;
	updateForm.elements["quantity"].value = quantity;
	updateForm.method = "POST";
	updateForm.submit();
}

function quantityChanged(thisObj,productId,usagePrefix){
	usagePrefix = (usagePrefix == null ? "#" : "#" + usagePrefix);
	try{ $((usagePrefix + "qtyError_" + productId)).hide();}catch(e){}
}


function selectProduct(thisObj,productId,usagePrefix){
	usagePrefix = (usagePrefix == null ? "#" : "#" + usagePrefix);
	var errorMsgPanel = $((usagePrefix + "varError_" + productId));
	var qtyErrorMsgPanel =  $((usagePrefix + "qtyError_" + productId));
	if (errorMsgPanel != null){
		errorMsgPanel.hide();
	}
	try{qtyErrorMsgPanel.hide();}catch(e){}

	
	var currentSelection = (thisObj != null ? thisObj.options[thisObj.selectedIndex].value : "");
	var qtySelector = $((usagePrefix + "qty_" + productId));
	if(qtySelector != null){
		qtySelector.val(currentSelection == "0" ? 0 : 1);
	}
	
	
	if(currentSelection == "0"){
		try{$((usagePrefix  + "pgvp"+ productId)).hide();}catch(e){}
		try{$((usagePrefix  + "pgvw"+ productId)).hide();}catch(e){}
		try{$((usagePrefix  + "pgvs"+ productId)).hide();}catch(e){}
		try{$((usagePrefix + "palink" + productId)).hide();}catch(e){}
		try{$((usagePrefix + "varQtyError_" + productId)).hide();}catch(e){}
	}else{
		try{$((usagePrefix  + "pgvp"+ productId))[0].innerHTML = $((usagePrefix + productId + "pgsvprice" + currentSelection))[0].innerHTML;}catch(e){}
		try{$((usagePrefix  + "pgvw"+ productId))[0].innerHTML = $((usagePrefix + productId + "pgsvweight" + currentSelection))[0].innerHTML;}catch(e){}
		try{$((usagePrefix  + "pgvs"+ productId))[0].innerHTML = $((usagePrefix + productId + "pgsvserving" + currentSelection))[0].innerHTML;}catch(e){}
		try{$((usagePrefix  + "pgvp"+ productId)).show();}catch(e){}
		try{$((usagePrefix  + "pgvw"+ productId)).show();}catch(e){}
		try{$((usagePrefix  + "pgvs"+ productId)).show();}catch(e){}
		try{$((usagePrefix + "palink" + productId)).show();}catch(e){}
	}
}

function showOverlay(thisObj,overlayMask,overlayPanel) {
    overlayMask = '#' + overlayMask;
    overlayPanel = '#' + overlayPanel;
    
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		$(overlayMask).width($(document).width());
		$(overlayMask).height($(document).height());
		toggleSelects(true);
		centerInViewport($(overlayPanel));
		$(window).scroll(function () {
			centerInViewport($(overlayPanel));
		 });
		}
	$(overlayMask).show();
	$(overlayPanel).show();
	//$("#zipCodeLayerField").focus();
}

function hideOverlay(thisObj,overlayMask,overlayPanel) {
    overlayMask = '#' + overlayMask;
    overlayPanel = '#' + overlayPanel;
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		toggleSelects(false);
		$(window).unbind('scroll');
	}
	$(overlayMask).hide();
	$(overlayPanel).hide();
}

function showZipCodeLayer(){
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		$("#overlayMask").width($(document).width());
		$("#overlayMask").height($(document).height());
		toggleSelects(true);
		centerInViewport($("#overlayPanel"));
		$(window).scroll(function () {
			centerInViewport($("#overlayPanel"));
		 });
		}
	$("#overlayMask").show();
	$("#overlayPanel").show();
	$("#zipCodeLayerField").focus();
}

function hideZipCodeLayer(){
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		toggleSelects(false);
		$(window).unbind('scroll');
	}
	$("#overlayMask").hide();
	$("#overlayPanel").hide();
	
	try{
		if(zcAI2Cp != null){
			injectProcessing(zcAI2Cp,false);
			zcAI2Cp = null;
		}
	}catch(e){
		zcAI2Cp = null;
	}
}

function toggleSelects(hide) {
	if (hide == true)
		$('select').addClass("invisible");
	else
		$('select').addClass("visible");
}

function centerInViewport(el) {
	//centers el in the viewport (ie6 only), other browsers use fixed positioning in the css
   var vpTop = document.documentElement.scrollTop;
	var vpHeight = document.documentElement.clientHeight;
	var vpYCenter = vpTop + (vpHeight/2);
	el.css({top:vpYCenter+"px"});
}


function doCatalogQuickOrder(clickObject){
	changeLayerCartState('off');
	var qsProductStyle = getQSProductStyle();
	var qsProductQuantity = getQSProductQuantity();
	if(!isZipCodeSet()){
		injectProcessing(clickObject,true, "button_image");
		showZipCodeLayer();
	}else{ 
		var productStyle = getProductStyle();
		var productQuantity = getProductQuantity();
		if(productStyle == "") {
			//we will have errors, submit the form
			injectProcessing(clickObject,true, "button_image");
			document.forms["catalogOrderForm"].submit();
		}else{
			var addPath = getContextPath() + "checkout/add_catalog_order_item.cmd?zipCode=" + getZipCodeVal()  + productStyle + productQuantity + "&dest=/checkout/add_catalog_order_item.cmd?&source=/catalog/catalog_order.jsp&loadType=AJAX&itemAdded=0&isCatalogQuickOrder=1&styles=" + qsProductStyle + "&qty=" + qsProductQuantity;
			injectProcessing(clickObject, true, "button_image");
			$.ajax({
				type: "GET",
				url: addPath,
				cache: false,
				success: function(data) {
					if(data.indexOf("itemAdded") > 2){
						getLayerCart(clickObject,data);
						clearCatOrderData();
					} else {
						document.location.href= getContextPath() + "checkout/item_not_added_to_catalog_order.jsp?styles=" + qsProductStyle + "&qty=" + qsProductQuantity;
					}
				}
			});
		}
		//document.forms["catalogOrderForm"].submit();
	}
	//getLayerCart(clickObject,null,false);
}

function getZipCodeVal() {
	if(document.getElementById("coZipCode") && document.getElementById("coZipCode").value != null){
		return document.getElementById("coZipCode").value;
	}else {
		return '';
	}
}

function setQuantity(index){
		var quantityArray = $("select[id*=qty]");
		if (quantityArray != null && quantityArray[index] != null && quantityArray[index].value == ""){
			$(quantityArray[index]).val("1");
		}
		var itemArray =  $("input[id*=itemNumber]");
		if (itemArray && itemArray[index] != null && itemArray[index].value == ""){
			$(quantityArray[index]).val("");
		}
	}

	function getProductStyle(){
		// create a comma separated string of productids
		var itemReturn = "";
		var itemArray =  $("input[@name=itemNumber]");
		for(index = 0; index < 10; index++) {
			if(itemArray && itemArray[index] != null && itemArray[index].value != ""){
				itemReturn += "&itemNumber=";
				itemReturn += $(itemArray[index]).val();
			}
		}
		return itemReturn;
	}

	function getQSProductStyle(){
		// create a comma separated string of productids
		var itemReturn = "";
		var itemArray =  $("input[@name=itemNumber]");
		for(index = 0; index < 10; index++) {
			if(itemArray && itemArray[index] != null && itemArray[index].value != ""){
				itemReturn += $(itemArray[index]).val();
			}
			 itemReturn += ",";
		}
		return itemReturn;
	}

	function getProductQuantity(){
		// create a comma separated string of productids
		var quantityReturn = "";
		var quantityArray = $("select[@name=quantity]");
		var itemArray =  $("input[@name=itemNumber]");
		for(index = 0; index < 10; index++) {

			if(quantityArray && quantityArray[index] != null && quantityArray[index].value != ""){
				if(itemArray && itemArray[index] != null && itemArray[index].value != ""){
					quantityReturn += "&quantity=";
					quantityReturn += $(quantityArray[index]).val();
				}
			}
		}

		return quantityReturn;
	}

function getQSProductQuantity(){
		// create a comma separated string of productids
		var quantityReturn = "";
		var quantityArray = $("select[@name=quantity]");
		var itemArray =  $("input[@name=itemNumber]");
		for(index = 0; index < 10; index++) {

			if(quantityArray && quantityArray[index] != null && quantityArray[index].value != ""){
				if(itemArray && itemArray[index] != null && itemArray[index].value != ""){
					quantityReturn += $(quantityArray[index]).val() + ",";
				}else {
					quantityReturn += ",";
				}
			}else {
				quantityReturn += ",";
			}
		}

		return quantityReturn;
	}


 function clearCatOrderData(){
		var itemArray =  $("input[@name=itemNumber]");
	   var quantityArray = $("select[@name=quantity]");
		for(index = 0; index < 10; index++) {
			if(itemArray && itemArray[index] != null && itemArray[index].value != ""){
				itemArray[index].value = "";
			}
			if(quantityArray && quantityArray[index] != null && quantityArray[index].value != ""){
				quantityArray[index].value = "";
			}
		}
	 if(document.getElementById("gEE")){
		 document.getElementById("gEE").style.display="none";
	 }
	 if(document.getElementById("gE")){
		 document.getElementById("gE").style.display="none";
	 }
	 if(document.getElementById("pcE")){
		 document.getElementById("pcE").style.display="none";
	 }
	 if(document.getElementById("qtyE")){
		 document.getElementById("qtyE").style.display="none";
	 }
 }

function populateCatOrderData(styles, quantities) {
	var arrayStyles = styles.split(",");
	var itemArray =  $("input[@name=itemNumber]");
	for(index = 0; index < 10; index++){
		itemArray[index].value = arrayStyles[index];
	}

	var arrayQuantities = quantities.split(",");
	var quantityArray = $("select[@name=quantity]");
	for(index = 0; index < 10; index++){
		quantityArray[index].value = arrayQuantities[index];
	}
}








function synchronousHttpRequest(url, param){
	return invokeHttpRequest(url,null,null);
}


function asynchronousHttpRequest(url,param,responseHandler){
	return invokeHttpRequest(url,param,responseHandler);
}

function invokeHttpRequest(url,param,responseHandler){
	var httpRequest = getHttpRequest();
	if(httpRequest == null){
		return false;
	}
	httpRequest.open((param != null ? "POST" : "GET"), url, (responseHandler != null ? true : false));
	if(responseHandler != null) {
		httpRequest.onreadystatechange = responseHandler;
	}
	httpRequest.send(param);
	return  httpRequest.responseText;
}


function getHttpRequest(){
	return window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
}

function submitenter(myForm,e) {
	var keycode;
	if(window.event) {
		keycode = window.event.keyCode;
	}else if(e) {
		keycode = e.which;
	}
	if(keycode == 13){
		var newInput = document.createElement('input');
		newInput.type = 'hidden';
		newInput.name = '-find';
		newInput.value = 'Log-In';
		myForm.appendChild(newInput);
		myForm.submit();
	}
}

function submitorder (el) {
	$(el).hide();
	if(document.getElementById("revSubmitOrder1")){
		document.getElementById("revSubmitOrder1").style.display = "none";
	}
	if(document.getElementById("revSubmitOrder2")){
		document.getElementById("revSubmitOrder2").style.display = "none";
	}
}

function confirmCancelOrder(orderNumber, message){
	if(confirm(message)){
		alert("Test message: User accepted to cancel the order(" + orderNumber + ")");
		//Todo: submit to server side logic to actually invoke a webservice to cancel the order.
	}
}

function doZipFocus(component) {
    var zipVal = component.value;
    if (zipVal == "Enter Zip Code") {
        component.value = "";
    }
    return true;
}

function doZipBlur(component) {
    var zipVal = component.value;
    if (strTrim(zipVal) == '') {
        component.value = "Enter Zip Code";
        return false;
    }
    return true;
}
