//checks to make sure customer wanted to put 0 for an item quantity
//submits form or focuses on the item quantity
var timeoutRunning=0;
var t="";
	function updateCart(field){
		focusedForm=field.form;
		if(field.value == "0"){
			if(confirm("Entering 0 for an item quantity will remove that item from your cart.\n\n"+
									"Do you want to remove this item from your cart?")){
				focusedForm.submit();
			}
			else{
				field.focus();
			}
		}
		else{
			focusedForm.submit();
		}
	}//end updateCart()
	
	function clearShipTo(form){
		for (x=0;x<form.length;x++){
			if(form.elements[x].name != "keyCode"){
				form.elements[x].value="";
			}
		}
		form.shipToId.value="0";
		form.elements['nextPage'].value="-1";
		form.elements['noValidate'].value="1";
		form.submit();
	}
//checks shipTo drop down on change
//submits cart or redirects to shipping.php
	function updateShipTo(field, site, page){
		var regularExpression = /([0-9]*)([a-zA-Z]*)/,cartId = regularExpression.exec(field.name),from,slashIndex;
		if(field.value == "new"){
			from = window.location.pathname;
			slashIndex = from.lastIndexOf("/");
			from = from.substring(slashIndex+1, from.length);
			if(page=="options"){
				window.location.replace(site+"checkout/addressBook.php?cartId="+cartId[1]);
			}else{
				window.location.replace(site+"checkout/shipTo.php?from="+from+"&cartId="+cartId[1]);
			}
		}
		else{
			getShipMethodOptions(field);
		}
	}//end updateShipTo()
	
	function getShipMethodOptions(field){
		var sendUrl="",options,json,id,shipMethodSelect,preValue,URL,cartId,
		regularExpression = /([0-9]*)([a-zA-Z]*)/,cartId = regularExpression.exec(field.name);
		if(field.form.name.toString() == "shipToForm"){
			sendUrl = "state="+field.value;
		}else if(field.form.name.toString() == "itemOptionsForm"){
			sku = field.form.elements[cartId[1]+'sku'];
			sendUrl="shipToId="+field.value;
			if(sku!=undefined){sendUrl+="&item="+sku.value;}
		}
		if(sendUrl!=""){
			URL = '/ajax/shipMethods.php';
			ajax = new Ajax.Request(URL,{method: 'POST', requestHeaders:{Accept: 'application/json'},parameters: sendUrl,onComplete:function(t) { 
				json = t.responseText.evalJSON(true);
				id = cartId[1].toString().concat('ShipMethod');
				shipMethodSelect = field.form.elements[id];
				preValue = shipMethodSelect.value;
				index=shipMethodSelect.selectedIndex;
				if(shipMethodSelect!=undefined){
					var length = shipMethodSelect.length; 
					removeOptions(shipMethodSelect,length);
					addOptions(shipMethodSelect,json.options,length)
					if(shipMethodSelect.options[index]!=undefined){
						if(shipMethodSelect.options[index].value==preValue){
							shipMethodSelect.selectedIndex = index;
						}
					}
				}
			}});
		}
	}
	
	function removeOptions(select,length){
		var i=0;
		length--;
		for (i = length; i>=0; i--) {
			select.remove(i);
		}
	}
	
	function addOptions(select,options){
		var i=0,nw="",length=options.length;
		if(page!="shipTo"){i=1;}
		for(i;i<length;i++){
			 var nw = document.createElement('option');
   		 nw.text = options[i].text;
    	 nw.value = options[i].value;
			  try {
    			select.add(nw, null); // standards compliant; doesn't work in IE
 				 }
  			catch(ex) {
    			select.add(nw); // IE only
  			}
		}
		
	}
	
//checks shipToName drop down on change
//reloads shipto.php with newly selected name
	function loadShipTo(field){
		thisValue=field.value;
		for (x=0;x<field.form.length;x++){
			if(field.form.elements[x].name != "ShipMethod"){
				field.form.elements[x].value="";
			}
		}
		field.value=thisValue;
		field.form.elements['nextPage'].value="-1";
		field.form.elements['noValidate'].value="1";
		field.form.submit();
	}//end updateShipTo()

//return index of current form element
	function getElementIndex(field){
		for(x=0;x<field.form.length;x++){
			if(field.form.elements[x].name==field.name){
				return x;
			}
		}
		return -1;//should never happen
	}//end getElementIndex()
	
//empies the payment fields and submits the form
//called when changing the type of payment method
	function changePaymentMethod(field){
		thisIndex = getElementIndex(field);
		for(x=thisIndex+1;x<field.form.length;x++){
			field.form.elements[x].value="";
		}
		if(field.form.elements['nextPage'])field.form.elements['nextPage'].value="-1";
		field.form.submit();
	}//end changePaymentMethod()
	
//changes the form action, submits the form
//returns nothing
	function addGiftWrap(field){
		field.form.action = "addGiftWrap.php";
		from = window.location.pathname;
		slashIndex = from.lastIndexOf("/");
		if(from.substring(slashIndex-8,slashIndex+1)=="checkout/"){
			slashIndex-=9;
			field.form.action="../"+"addGiftWrap.php";
		}
		from = from.substring(slashIndex+1, from.length);
		field.form.action+="?from="+from;
		field.form.submit();
	}//end addGiftWrap()
	
//makes sure at least one value in the form is filled out
//returns bool
	function blankFormCheck(formObject){
		if (submitted == true) {//keep the forms from being submitted more than once
			return false;
		}
		else {
			// everything is ok check the fields, ie using if (document.... .lenght == 0) alert...
			submitted = true ;
		}
		skippedFields = new RegExp("(prefixId|nextPage|shipToId|businessFlag)");
		for(x=0; x<formObject.length;x++){//loop through each form object
			if(!(skippedFields.test(formObject.elements[x].name))){
				if(formObject.elements[x].value.length > 0){
					return true;
				}
			}
		}
		//went through entire form and found no values entered
		return false;
	}//end blankFormCheck()
	
	function checkQty(formObject,skuList){
		return true;
	}
	
//makes sure at least the address is not a po box
//returns bool
	function isPOBox(field){
		return true;//don't worry about this for so
	}//end isPOBox()
	
//tests payment entered and updates next page value
//returns bool
	function applyPayment(field, amountDue){
		formObject = field.form;
		field.disbled = true;
		regularExpression = /(payment[0-9]{1,4})/;
		oldPayments = 0.0;
		newPayment = 0.0
		if(field.type == "image"){//adding a payment
				formObject.elements['IdNumberpayment'].value = formObject.elements['IdNumberAltpayment'].value;
		}
		field.form.elements['nextPage'].value=0;
		return true;
	}
	
	function decimalToString(floatToConvert, decimalPlaces){
		floatToConvert= floatToConvert+"";
		errorFlag = false;
		convertedString = "";
		
		if(floatToConvert.search(/^(-)?[0-9]*\.?[0-9]*$/) > -1){//make sure it is a decimal number
			decimalIndex = floatToConvert.lastIndexOf(".");
			intValue = floatToConvert.substr(0,decimalIndex);
			if(decimalIndex < 0){intValue=floatToConvert;}
			convertedString = intValue+".";
			decimalValue = floatToConvert.substr(decimalIndex+1, decimalPlaces);
			if(decimalIndex < 0){
				decimalValue = "";
				for(x=1;x<=decimalPlaces;x++){decimalValue+="0";}
			}
			startingLength = decimalValue.length
			if(startingLength<decimalPlaces){
				for(counter=0; counter<(decimalPlaces-startingLength);counter++){
					decimalValue+="0";
				}
			}
			convertedString+=decimalValue;
		}else errorFlag = true;
		return convertedString;
	}
	
	function changeShippingMethod(field, show){
		formObject = field.form;
		var pattern = /^[p,P](.){0,2}[o,O](.)*(BOX)?/i;
		var address ="";
		if(formObject.elements['streetAddress'] != undefined){
		address = formObject.elements['streetAddress'].value;
		}
		message = "";
		now = new Date;
		if(now.getUTCHours() >=18 || now.getUTCHours() < 5){
			message += "Orders placed after 1:00 p.m. (CST) are processed the next business day.";
		}
		if(show){
			message += "\nExpress shipping applies only to items currently in stock.";
		}
		if(field.value == "standard"){message = "";}
		if(field.value != "standard" && pattern.test(address)) {
			message += "\n\n Express shipping not allowed to a PO Box."
			field.value = "standard";
		}
		if(message.length > 0){
			alert(message);
		}
		//formObject.submit();
		return true;
	}
	
	function translateZip(xmlFile){
		// code for Mozilla, etc.
		if (window.XMLHttpRequest){
  		xmlhttp=new XMLHttpRequest();
  		xmlhttp.onreadystatechange=displayLocation;
  		xmlhttp.open("GET",xmlFile,true);
  		xmlhttp.send(null);
  	}
		// code for IE
		else if (window.ActiveXObject){
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  if (xmlhttp){
		  	xmlhttp.onreadystatechange=displayLocation;
		  	xmlhttp.open("GET",xmlFile,true);
		  	xmlhttp.send();
    	}
  	}
  	//else{alert("this browser doesn't support this feature");}
  	return true;
	}
	
	function displayLocation(){
		// if xmlhttp shows "loaded"
		if (xmlhttp.readyState==4){
  		// if "OK"
  		if (xmlhttp.status==200){
  			response=xmlhttp.responseText;
  			responseArray = response.split("\n");
  			if(responseArray[0]==""){startIndex = 1;}
  			else{startIndex = 0;}
  			if(document.forms[1].elements['city'].value=="" && responseArray[startIndex]!=""){
  				document.forms[1].elements['city'].value=responseArray[startIndex];
  				if(document.forms[1].elements['state'].value==""){
  					document.forms[1].elements['state'].value=responseArray[(startIndex+1)];
  				}
  			}
  			document.forms[1].elements['phoneNumber'].focus();
  		}
  	}
	}
	function MonthToDays(iMonth){
		str="";
		var d = new Date();
		days =  32 - new Date(d.getFullYear(), iMonth-1, 32).getDate();
		str+="<option value=\"0\">Day</option>";
		for(i=1;i<= days;i++){
			str+="<option value=\""+i+"\">"+i+"</option>";
		}
		$('birthDay').innerHTML=str;
	}
	function continueShopping(selector){
		//alert(selector.options[selector.selectedIndex].value);
		window.location = selector.options[selector.selectedIndex].value;
	}	
	function createItemOptions(item,size,color,qty,personalization,customText,lineItemIndex,wishlist){
		str="";
		str+="<a href=\"/detail.php?parentid="+item+"\" onclick=\"eybEvent(event,'"+item+"','"+size+"','"+color+"','"+qty+"','"+personalization+"','"+customText+"','"+lineItemIndex+"');return false;\">Edit</a>";
		if(!wishlist){
			str+="<a href=\"/detail.php?parentid="+item+"\" onclick=\"rfbEvent(event,'"+lineItemIndex+"','"+item+"');return false;\">Remove</a>";
			checkString="itemOptions|addressBook|billTo|payment";
			if(window.location.toString().match(checkString) || readCookie("customerId")){
				str+="<a href=\"/detail.php?parentid="+item+"\" onclick=\"sflEvent(event,'"+lineItemIndex+"','"+item+"');return false;\">Save For Later</a>";
			}
		}else{
		str+="<a href=\"/detail.php?parentid="+item+"\" onclick=\"rfwEvent(event,'"+lineItemIndex+"','"+item+"');return false;\">Remove</a>";
		}
		return str;
	}	
	function removePayment(payForm,lastFour){
		var links = "<a href=\"/checkout/payment.php\" onclick=\"document.forms[1].payment"+lastFour+".value=0;";
		links+= "document.forms[1].paymentTypeId.value='';";
		links+= "document.forms[1].submit();return false;\">remove</a>";
		//set up parent div
		parentDiv = $('p'+lastFour);
		var pos = findPos(parentDiv);
		var offsets = Array(45,10);
		setupProdOptions(links,parentDiv,pos,offsets);
	}
	
	var toR1=0;
	var to1="";
	function setupProdOptions(links,pos,offsets,wishlist){
		var wishlistWin="";
		var cart = "";
		prodOptions=$('prodOptions');
		if(prodOptions != null){
			prodOptions.parent.removeChild(prodOptions);
			prodOptions=null;
		}
			divScrollPos=0;
			var pattern = /(wishlist|search|detail)/i;
			page = getCurrentPage();
			if(pattern.test(page)){ 
				if(!wishlist){
					cart = $('quickCart');
					if(cart){divScrollPos = cart.scrollTop;}
				}else{
					wishlistWin = $('wishListItemsAjax');
					if(wishlistWin){divScrollPos = wishlistWin.scrollTop;}
				}
			}else{
				cart = $('cart');
				if(cart){divScrollPos = cart.scrollTop;}
				wishlistWin = $('wishListItemsAjax');
				if(wishlistWin){divScrollPos = wishlistWin.scrollTop;}
			}
			var newdiv = document.createElement('div');
  		var divIdName = 'prodOptions';
  		newdiv.setAttribute('id',divIdName);
 	 	 	newdiv.innerHTML = links;
  		newdiv.style.position = "absolute";
			newdiv.style.top = (pos[1]+offsets[1]-divScrollPos)+'px';
			newdiv.style.left = (pos[0]+offsets[0])+'px';
	  	newdiv.style.visibility = 'visible';
	  	if(wishlistWin){newdiv.style.zIndex=9999;}
	  	else{newdiv.style.zIndex=7;}
	  	newdiv.style.display='block';
	  	var body = $('body');
	  	newdiv.parent=body;
			body.appendChild(newdiv);
			//newdiv.focus();
			if(toR1!=1){
			to1=setTimeout("removeFocus()",3000);
			toR1=1;
		} else {
			clearTimeout(to1);
			to1=setTimeout("removeFocus()",3000);
			toR1=1;
		}
	}
	function removeFocus(){
		prodOptions=$('prodOptions');
		if(prodOptions != null){
			prodOptions.style.display='none';
			clearTimeout(to1);
			//document.body.removeChild(prodOptions);
		}
		toR1=0;
	}
	
	function addKeyCode(selectAlter){
		if(selectAlter.options[selectAlter.selectedIndex].value==5){
			var keyCodeText="Key Code:<br>";
			keyCodeText+="<input class=\"BInfoIn\" type=\"text\" maxlength=\"\" size=\"20\" value=\"\" name=\"keyCode\">";
			document.getElementById('keyCodeDiv').innerHTML = keyCodeText;
		}else{
			document.getElementById('keyCodeDiv').innerHTML = "";
		}
	}
	
	function displayGWPrice(price,lineItemId){
		if(price==0){
			document.getElementById('gwPrice'+lineItemId).innerHTML = '';
		}else{
			document.getElementById('gwPrice'+lineItemId).innerHTML = '(add '+price+'):';
		}
	}
	
	function shipCheck(shipForm,nextPage){
		if(shipForm.elements['ShipMethod'].value == ""){
			shipForm.elements['ShipMethod'].value = "standard";
		}
		shipForm.elements['nextPage'].value=nextPage;
		shipForm.submit();
	}
	
	function sourceCheck(sourceForm,nextPage){	
		if(sourceForm.elements['keyCode']){
			if(sourceForm.elements['keyCode'].value==""){
				sourceWin(nextPage);
			}else{
				sourceForm.elements['nextPage'].value=nextPage;
				sourceForm.submit();
			}
		}
		else{
			sourceForm.elements['nextPage'].value=nextPage;
			sourceForm.submit();
		}
	}
	function setPosition(divId){
			var shopping = $('shoppingInfo');
			var div = $("cntBut");
			var pos = findPos(shopping);
			div.style.top = (pos[1]-35)+'px';
		if(divId=="formWrapper"){
			document.getElementById("formWrapper").style.height = document.getElementById('cart').offsetHeight > 449 ? "500px" : "480px";
		}
	}
 
function pop(newwin) {flyout=window.open(newwin,"flyout","resizable=yes,scrollbars=yes,width=600,height=650,top=0,left=0,toolbar=no,status=no,menubar=no")}
function pop2(newwin,wi,hi,xpos,ypos) {flyout=window.open(newwin,"flyout","resizable=yes,scrollbars=no,width="+wi+",height="+hi+",top="+ypos+",left="+xpos+",toolbar=no,status=no,menubar=no")}

/*function addWishListToCart(wishForm,lineItemId){
	if(wishForm.elements['qtyPurch'+lineItemId].value==-1){
		//replace error
		$('wishlistError').innerHTML = '<span class=\"error\">Please enter a quantity before adding item '+wishForm.elements[lineItemId+'sku'].value+' to your cart.</span>';
	}else{
		cmCreatePageElementTag("add","WishList","","0",window.location.toString());  //coremetrics remove from bag
		window.location = "/wishlist.php?addToCart="+lineItemId+"&qtyPurch="+wishForm.elements['qtyPurch'+lineItemId].value;
	}
}*/
function NiftyCheck()
{
if(!document.getElementById || !document.createElement)
    return(false);
var b=navigator.userAgent.toLowerCase();
if(b.indexOf("msie 5")>0 && b.indexOf("opera")==-1)
    return(false);
return(true);
}

function Rounded(selector,bk,color,size){
var i;
var v=getElementsBySelector(selector);
var l=v.length;
for(i=0;i<l;i++){
    AddTop(v[i],bk,color,size);
    AddBottom(v[i],bk,color,size);
    }
}

function RoundedTop(selector,bk,color,size){
var i;
var v=getElementsBySelector(selector);
for(i=0;i<v.length;i++)
    AddTop(v[i],bk,color,size);
}

function RoundedBottom(selector,bk,color,size){
var i;
var v=getElementsBySelector(selector);
for(i=0;i<v.length;i++)
    AddBottom(v[i],bk,color,size);
}

function AddTop(el,bk,color,size){
var i;
var d=document.createElement("b");
var cn="r";
var lim=4;
if(size && size=="small"){ cn="rs"; lim=2}
d.className="rtop";
d.style.backgroundColor=bk;
for(i=1;i<=lim;i++){
    var x=document.createElement("b");
    x.className=cn + i;
    x.style.backgroundColor=color;
    d.appendChild(x);
    }
el.insertBefore(d,el.firstChild);
}

function AddBottom(el,bk,color,size){
var i;
var d=document.createElement("b");
var cn="r";
var lim=4;
if(size && size=="small"){ cn="rs"; lim=2}
d.className="rbottom";
d.style.backgroundColor=bk;
for(i=lim;i>0;i--){
    var x=document.createElement("b");
    x.className=cn + i;
    x.style.backgroundColor=color;
    d.appendChild(x);
    }
el.appendChild(d,el.firstChild);
}

function getElementsBySelector(selector){
var i;
var s=[];
var selid="";
var selclass="";
var tag=selector;
var objlist=[];
if(selector.indexOf(" ")>0){  //descendant selector like "tag#id tag"
    s=selector.split(" ");
    var fs=s[0].split("#");
    if(fs.length==1) return(objlist);
    return(document.getElementById(fs[1]).getElementsByTagName(s[1]));
    }
if(selector.indexOf("#")>0){ //id selector like "tag#id"
    s=selector.split("#");
    tag=s[0];
    selid=s[1];
    }
if(selid!=""){
    objlist.push(document.getElementById(selid));
    return(objlist);
    }
if(selector.indexOf(".")>0){  //class selector like "tag.class"
    s=selector.split(".");
    tag=s[0];
    selclass=s[1];
    }
var v=document.getElementsByTagName(tag);  // tag selector like "tag"
if(selclass=="")
    return(v);
for(i=0;i<v.length;i++){
    if(v[i].className==selclass){
        objlist.push(v[i]);
        }
    }
return(objlist);
}