
//event sniffer for button click on enter
if (document.layers) document.captureEvents(Event.KEYPRESS);
document.onkeypress = keyhandler;
function keyhandler(e) {
	var p = window.location.href;
	iStart = p.lastIndexOf('/') + 1;
	iEnd = p.indexOf('?');
	pageName = p.substring(iStart, iEnd);
	   
	var objEvent = e ? e : window.event; 
	
	pageName = pageName.toLowerCase(); 
	  
	switch(pageName) {
		case 'customerlogin.asp':
			if (objEvent.keyCode == 13) customer_login('frmCustomerLogin');
			break;
	}
}



// Adds product to cart

function jsAddToCart(iProductID, bCheckout, strBaseUrl, strToken, 
	strInventoryControlUse, strInventoryAllowBackordering, intUnits, form)
{

	var oQuery='';
	var pQuery='';
	var zQuery='';
	var fQuery='';
	var qQuery='';
	var cQuery='';
	
	var shipToZip = document.form.txtShipToZip;
	var selItemFriendlyName = document.form.selItemFriendlyName;
	var selProductOptions = document.form.selProductOptions;
	var txtItemFriendlyName = document.form.txtItemFriendlyName;
	var txtQuantity = document.form.txtQuantity;
	var iQuantity=1;
	
	var strErr='';
	
	var baseUrl = strBaseUrl + 'cartAdd.asp' + strToken;
	

	// optional postal code field
	if(shipToZip) {
		zQuery = '&shipToZip='+shipToZip.value;
		if(!jsIsValidPostalCode(shipToZip.value)) {
			strErr += '- Please enter a valid zip/postal code of the recipient with no spaces or dashes.\n'			
		}
	}
			
	// optional friendly name field
	if(selItemFriendlyName) {
		var strItemFriendlyName;
		if(txtItemFriendlyName.value.length>0) {
			strItemFriendlyName = txtItemFriendlyName.value;
		}
		else {
			strItemFriendlyName = selItemFriendlyName.value;		
		}	
		
		fQuery = '&ItemFriendlyName='+strItemFriendlyName;		
	}
	
	// optional quantity field
	if(txtQuantity) {
		iQuantity = txtQuantity.value;			
	}
	
	qQuery = '&Quantity='+ iQuantity;
	
	// product options	
	
	if (selProductOptions) {
		if (selProductOptions.type=='select-one') {  // Select Boxes
			oQuery = '&optionID='+selProductOptions.value;	
		}
		else { // Radios
			for(i=0;i<selProductOptions.length;i++) {
				if(selProductOptions[i].checked) oQuery = '&optionID='+selProductOptions[i].value;	
			}	
		}	
	}
	else {
		oQuery='';
	}
	
	// Product ID
	pQuery = 'productID='+iProductID;
	
	// additional error trapping	
	if (isNaN(iQuantity)) { 
		strErr += ' -Please enter a valid product quantity\n';	
	}
	
	if(bCheckout) cQuery = '&bCheckout=1';
	
	// Check inventory
	if (! checkInventory(strInventoryControlUse, strInventoryAllowBackordering, intUnits)) return false;
		
	// check for errors and alert or redirect and add
	if (strErr !='') {
		alert('Please review the form and check the following items:\n\n' + strErr);
		return false;
	}
	else {
		window.location.href=(baseUrl + pQuery + oQuery + zQuery + fQuery + qQuery + cQuery);
	}	
	
}	

function checkInventory(strInventoryControlUse, cstAllowBackordering, intMaxUnits) {
	if(strInventoryControlUse=="False") return true;
	var objForm = document.form;
	
	var iQuantity = objForm.txtQuantity.value;
	iQuantity = parseInt(iQuantity);
	var obj = objForm.txtQuantity;
	
	var strErr = '';
		
	if(iQuantity > intMaxUnits) {
		if(cstAllowBackordering=="False") {
			strIsOrAre = intMaxUnits > 1 ? "are" : "is";
			strErr += "You have requested " +iQuantity + " of this item, but ";
			strErr += "there " + strIsOrAre + " only " + intMaxUnits + " in stock.\n";
			strErr += "Your quantity will be changed to " + intMaxUnits + ".";
			if(obj) obj.value=intMaxUnits;			
			alert(strErr);			
		}
		// warn that some items are on backorder
		else {
			strIsOrAre = (iQuantity - intMaxUnits) > 1 ? "are" : "is";
			strErr += (iQuantity - intMaxUnits) + " of this item " + strIsOrAre + " ";
			strErr += "out of stock and must be backordered.\nWould you like to order ";
			strErr += "these additional items anyway?\nChoose 'Cancel' to order just the in-stock items ";
			strErr += "or 'OK' to order both the in-stock and backordered items.";
			if(!confirm(strErr)) {
				obj.value = intMaxUnits;			
			}
		}		
	}
	
	return true;
}

function jsCartSaveSingleItem(strFormID) {
	var form = document.getElementById(strFormID);
	var strErr = '';
	
	if (isNaN(form.Quantity.value)) strErr += '- Invalid Quantity';
	if (strErr !='') {
		alert('Please review the form and check the following items:\n\n' + strErr);
		return false;
	}
	else {
		form.submit();
	}	
}

//check for valid postal code
function jsIsValidPostalCode(value) {
	// RegExp to check for numeric only (US only transactions)
	//var re = /^\d{5}([\-]\d{4})?$/;
	//return (re.test(value));
	
	// loose validation: check for length only
	if(value.length>0 && value.length<=6) {
		return true;
	} else {
		return false;
	}
}

function jsCartPrepare(strFormID, strRedirectPage) {
	var form = document.getElementById(strFormID);

	var strErr= getQuantityInputErrors(strFormID);
	form.hdnRedirectPage.value=strRedirectPage;	
	
	if (strErr !='') {
		alert('Please review the form and check the following items:\n\n' + strErr);
		return false;
	}
	else {
		form.submit();		
	}	
}

function jsCartClearAll(strToken) {
	if(confirm('Are you sure you want to remove all items from your shoopping cart?')) {
		window.location.href='cartclear.asp'+strToken + 'page=cartReview.asp'
	}

}

function getQuantityInputErrors(strFormID) {
	var form = document.getElementById(strFormID);
	
	var strErr='';	
	var useDHTML = (document.layers ? false : true);	
	var errFlag=false;
		
	for(i=0; i<form.elements.length; i++) {
		strElement = form.elements[i];
		strElementName = strElement.name;
		strElementValue = strElement.value;
					
		if(strElementName.indexOf("|Quantity")>0) {
			if(isNaN(strElementValue)) {
				errFlag=true;
				strElement.focus();
				if(useDHTML) strElement.className='textboxError';
			}
			else {
				if(useDHTML) strElement.className='textbox-right';
			}			
		}	
	}
	
	if(errFlag) strErr += '- One or more quantities is invalid.\n';
	return strErr;	
}

function jsCheckInventoryOnChange(obj, intMaxUnits, strItemName, cstAllowBackordering) {
	var strErr = '';
	
	if(isNaN(intMaxUnits)) return;
	if(isNaN(obj.value) || obj.value==null || trim(obj.value)=='') obj.value=0;
	obj.value=trim(obj.value);
	
	intMaxUnits = parseInt(intMaxUnits);
	intQuantity = parseInt(obj.value);
	
	if(intQuantity > intMaxUnits) {
		if(cstAllowBackordering=="False") {
			strIsOrAre = intMaxUnits > 1 ? "are" : "is";
			strErr += "You have requested " + intQuantity + " of the " + strItemName + ", but ";
			strErr += "there " + strIsOrAre + " only " + intMaxUnits + " in stock.\n";
			strErr += "Your quantity will be changed to " + intMaxUnits + ".";
			obj.value=intMaxUnits;
			alert(strErr);
		}
		// warn that some items are on backorder
		else {
			strIsOrAre = (intQuantity - intMaxUnits) > 1 ? "are" : "is";
			strErr += (intQuantity - intMaxUnits) + " of the " + strItemName + " " + strIsOrAre + " ";
			strErr += "out of stock and must be backordered.\nWould you like to order ";
			strErr += "these additional items anyway?\nChoose 'Cancel' to order just the in-stock items ";
			strErr += "or 'OK' to order both the in-stock and backordered items.";
			if(!confirm(strErr)) obj.value = intMaxUnits;
		}		
	}
		
}

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

// -------------- Checkout Process -------------------

function jsIsShippingProblem(strFormID) {
	var form = document.getElementById(strFormID);
	if(!form.ShippingMethod) return false;
	if(!form.ShipToBuildingType) return false;
	
	if(jsIsBusinessOnlyShipping(jsGetSelectedRadioValue(form.ShippingMethod)) && form.ShipToBuildingType.value !='Business') {
		strBusinessError = jsGetSelectedRadioParsedValue(form.ShippingMethod) + ' delivery is for businesses only.\n';
		strBusinessError += 'Please re-select the correct building type or shipping method.';
		alert(strBusinessError);
		return true;
		}	
	else {	
		return false;
	}
}

function jsIsBusinessOnlyShipping(shippingMethod) {
	var intPos=-1;
	intPos = shippingMethod.search(/(2nd day air am)/gi);		
		
	if (intPos != -1)
		return true;
	else
		return false;
}

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) {
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; }
   }
  return -1;
} 

function jsGetSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) {
         return buttonGroup[i].value;
      } else { 
         return buttonGroup.value;
      }
   }
}

function jsGetSelectedRadioParsedValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   var strLabel;
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) {
         strLabel = buttonGroup[i].value;
      } else { 
         strLabel = buttonGroup.value;
      }
   }
   return strLabel.split('|')[0];
}


// populate shipping fields from select
function jsChangeShippingInfo(strFormID) {
	var form = document.getElementById(strFormID);
	
	//var fldShippingInfo = form.selCombinedShippingInfo;
	var fldShippingInfo = eval("form.selCombinedShippingInfo");
	
	if(fldShippingInfo) {
		if(fldShippingInfo.value) {
			strShippingData = fldShippingInfo.value;	
			arrShippingData = strShippingData.split("|");
			
			// get values from options
			strShipCity = arrShippingData[0]
			strShipStateProvince = arrShippingData[1]
			strShipCountry = arrShippingData[2]
			
			//establish fields
			fldShipCity = eval("form.ShipToCity");
			fldShipStateProvince = eval("form.ShipToStateProvince");
			fldShipCountry = eval("form.ShipToCountry");
			
			//set values
			
			//city
			fldShipCity.value = strShipCity;
			
			//state
			for(i=0;i<fldShipStateProvince.length;i++) {				
				if(fldShipStateProvince.options[i].value==strShipStateProvince) {
					fldShipStateProvince.options[i].selected = true;					
				}		
			}
			
			//country
			for(i=0;i<fldShipCountry.length;i++) {
				
				if(fldShipCountry.options[i].value==strShipCountry) {
					fldShipCountry.options[i].selected = true;					
				}			
			}
			
					
		}	
	}
}




// Removes specific item from cart
function jsRemoveItem(iRecordID, strBaseUrl, strToken)
{
	var baseUrl = strBaseUrl + 'cartRemoveItem.asp' + strToken;
	var pQuery = 'recordID='+iRecordID;
	
	if (confirm('Remove this item from your cart?')){				
		window.location.href=(baseUrl + pQuery);
	}
}	

function jsProductDetails(iProductID, selCategory, txtSearchText, selPriceRange, strBaseUrl, strToken)
{
	var baseUrl = strBaseUrl + 'productdetail.asp'+ strToken;
	var pQuery = 'productID='+iProductID;
	pQuery += 'selCategory='+selCategory;
	pQuery += 'txtSearchText='+selCategory;
	pQuery += 'selPriceRange='+selPriceRange;	
			
	window.location.href=(baseUrl + pQuery);
}					


function jsConcatFormVars(strVar, index) {
	return eval(form + "." + strVar + index)
}


// Customer Login

function jsCustomerLogin(strFormID)
{
	var form = document.getElementById(strFormID);
	var strErr = '';
	if (document.frmCustomerLogin.spUserName) {
		if (document.frmCustomerLogin.spUserName.value.length==0) {
			strErr +='Please enter a valid User Name\n';
		}
	}
	
	if (document.frmCustomerLogin.spPassword) {
		if (document.frmCustomerLogin.spPassword.value.length==0) {
			strErr +='Please enter a valid Password\n';
		}
	}
	
	if (strErr.length == 0) {
		document.frmCustomerLogin.submit();
	}
	else {
	alert(strErr);	
	}
}	


//Prints page
function DoPrint(text){
	text=document
	print(text)
}

// Counts textarea characters
function jsTextCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		// otherwise, update 'characters left' counter
	else 
	countfield.value = maxlimit - field.value.length;
}

function jsCheckoutVerifyForm(strFormID) {
	var form = document.getElementById(strFormID);
	var mode = '<%=cstShippingMethodID%>';

	// Check for invalid building type/shipping method combinations
	
	if(jsIsShippingProblem(strFormID)) return;
	
		
	// See if city/state/zip/country values have changed from load
	// if so recalculate shipping
	var bRecalcFlag=false;
	
	if(form.hdnShipToCity && form.ShipToCity) {
		//if(form.hdnShipToCity.value != form.ShipToCity.value) bRecalcFlag=true;
	}
	
	if(form.hdnShipToStateProvince && form.ShipToStateProvince) {
		//if(form.hdnShipToStateProvince.value != form.ShipToStateProvince.value) bRecalcFlag=true;
	}
	
	if(form.hdnShipToPostalCode && form.ShipToPostalCode) {
		if(form.hdnShipToPostalCode.value != form.ShipToPostalCode.value) bRecalcFlag=true;
	}
	
	if(form.hdnShipToCountry && form.ShipToCountry) {
		//if(form.hdnShipToCountry.value != form.ShipToCountry.value) bRecalcFlag=true;
	}
	
	if(bRecalcFlag && mode=='2') {
		strAction =  "CheckoutShipping.asp?Recalc=1&ShippingMode=" 
		strAction += form.hdnShippingMode.value + '&RecordID='+ form.hdnCartItemID.value;
		
		form.action=strAction;
	}
	else
	{
		form.action = "CheckoutUpdateCartItem.asp";
	}
	
		
	form.submit();

}


// Populate checkout form from address book
function jsPouplateCheckFormFromAddressBook(strFormID, strValue) {
	var form = document.getElementById(strFormID);
	if(strValue=='') return;	
	
	var arrValue = strValue.split("|");
	
	eval("form.ShipToFirstName").value=arrValue[0];
	eval("form.ShipToLastName").value=arrValue[1];
	eval("form.ShipToCompany").value=arrValue[2];
	eval("form.ShipToAddress1").value=arrValue[3];
	eval("form.ShipToAddress2").value=arrValue[4];
	eval("form.ShipToCity").value=arrValue[5];
	eval("form.ShipToStateProvince").value=arrValue[6];
	eval("form.ShipToPostalCode").value=arrValue[7];
	eval("form.ShipToCountry").value=arrValue[8];	
	eval("form.ShipToPhoneNumber").value=arrValue[9];	
	
	arrValue = '';
}


function jsCheckGuaranteedDelivery(strFormID, value) {
	var form = document.getElementById(strFormID);
	var elemTarget = document.getElementById("dvGuaranteedDelivery");
	if(!elemTarget) return;
	//if(!elemTarget.innerHTML) return;	
	elemTarget.innerHTML=value;
}

function submitFormByID(strFormID) {
	var form = document.getElementById(strFormID);
	form.submit();
}

