/*try {
  console.log("init");
} catch(e) {
   console = { log: function() {} };
}*/
/* v5 fix bug in show price
   v6 add support for deposits on MAD Fiber
   v8 add ajax call to clear expired cache
   v9 fix bug in new clear cache ajax call
   v10 new makeCloseout(), makeGoingGone(), and addProductList() functions for admininfo
   v12 addProductList() wasn't actually added in v10, add it here.
   v13 update notifyMe to support optin. add support for optin checkbox. Add support for customapparel form
   v14 add priorSpecial() for autodiscount support
   v15 use shipCalc to determine if shipping calculation has been performed. Also changes to code to determine when to show
   		shipping calculations on shipinfo page.
   v16 add updateACN to update the autodiscount customernum cookie
   v17 add addSpecialOrder. This is similar to addToCart but is designed to check special order form.
   	   add confirmation popup when Make Closeout and Make Going Gone are clicked in Admin
   v18 reset product page partno select on page load, update comboproductlist for !combocustomize combos
   v19 minor fix to checkqty for outofstock items
   v20 fix bug for showinstock() when only 1 left is displayed
   v21 better support for specialorder items, admin addtopicklist
   v22 support fot varient select on product page load
   v23 add requestCount for admin inventory counts on product page
   v24 changes on product page to deal with new discount handling
   v25 check shipping restriction before replacing shipnote
   v26 support for ajax/stock to update the productdetail stock status
   v27 add ajax call to productlinks
   v28 add skuInStock definition
   v29 don't update product page productlinks if prevnext doesn't exist (daily special page)
   v30 add checkVarient() call to updateSelect
   v31 fix bugs with msrp display on product detail page
   v32 don't show skus that are out of stock and not on order
   v33 add updateecn()
*/
/* suggest variables */
var scnt = 0;
var suggestCount = -1;
var sugVisible = false;
var lastSuggest = "";
/* pricematch variables */
var calculatedPrice = 0;
var pmprice = "";
var shipCalc = false;
var skuInStock;

function checkCookies() {
	setCookie ("test","none","","/","","");
	if (getCookie("test") == false) {
		document.getElementById("nocookies").style.display = "block";
	}	
}

function selectManufacturer() {
	var loc = document.getElementById("manselect").options[document.getElementById("manselect").selectedIndex].value;
	if (loc.length > 0) {window.location.assign(loc);}
}

function clearSearchBox()
{	
	if (document.getElementById("search1").value == 'Search') {document.getElementById("search1").value = ''}
	if (document.getElementById("search1").value.length > 1){document.getElementById("suggestions").style.visibility = "visible";}
	return true;
}

function checkSearchBox() {
	if (document.getElementById("search1").value == '') {document.getElementById("search1").value = 'Search';}
}
function checkSuggest() {
	if(suggestCount >=0) {return false;}
}
function hideSuggestions()
{
	document.getElementById("suggestions").style.visibility = "hidden";
}

function myEncode(str) {
	str = escape(str);
	str = str.replace('%','%*');
    return str;
}

function debugInfo(str) {
	debugxmlHttp = GetXmlHttpObject();
	debugxmlHttp.open("GET", "/ajax/debuginfo?msg="+URLEncode(str).toLowerCase(), true);		
	debugxmlHttp.send(null)
}

function getSuggestions(str,keycode) {
	str = myEncode(document.getElementById("search1").value);
	if (keycode == 40 && sugVisible) {
		suggestCount++;
		if(document.getElementById("sug"+suggestCount)) {
			document.getElementById("sug"+suggestCount).style.backgroundColor="#1f4594";
			document.getElementById("sug"+suggestCount).style.color="white";
			if(document.getElementById("sug"+(suggestCount-1))) {
				document.getElementById("sug"+(suggestCount-1)).style.backgroundColor="#ffffff";
				document.getElementById("sug"+(suggestCount-1)).style.color="#717b86";
			}
		} else {suggestCount--;}
		return;
	}
	if (keycode == 38 && sugVisible) {
		if(document.getElementById("sug"+suggestCount)) {
			document.getElementById("sug"+suggestCount).style.backgroundColor="#ffffff";
			document.getElementById("sug"+suggestCount).style.color="#717b86";
		}
		if (suggestCount >= 0) {
			suggestCount--;
			if(document.getElementById("sug"+suggestCount)) {
				document.getElementById("sug"+suggestCount).style.backgroundColor="#1f4594";
				document.getElementById("sug"+suggestCount).style.color="white";
			} 
		}
		return;
	}
	if (keycode == 13 && suggestCount >=0) {
//		alert(document.getElementById("sug"+suggestCount).href);
		window.location=document.getElementById("sug"+suggestCount).href;
		return false;
	}
	if(str.length >= 6) {
		if (str.substr(0,6) == 'Search') {str = str.substring(6);document.getElementById("search1").value = str;}
	}
	if(str.length < 2) {
		// hide the suggestions area
		document.getElementById("suggestions").style.visibility = "hidden";
		suggestCount = -1;
	} else {
		scnt = 0;
		suggestDelay(str);
	}			
}

function suggestDelay(str) {
	scnt++;
	if (scnt < 10) {setTimeout("suggestDelay('" + str + "');",50);}
	if (scnt >= 10 && str == myEncode(document.getElementById("search1").value)) {
		getSuggestion();
	} 
}

function getSuggestion() {
	var thisSuggest = myEncode(document.getElementById("search1").value);
	if (thisSuggest != lastSuggest && thisSuggest.length >= 2){
		lastSuggest = thisSuggest;
		xmlHttp = GetXmlHttpObject();
		xmlHttp.onreadystatechange = showSuggestion;
		var suggestURL = "/ajax/suggest?q="+thisSuggest.toLowerCase();
		xmlHttp.open("GET", suggestURL, true);		
		xmlHttp.send(null)
	}	
}	

function goSearch() {
	if(suggestCount < 0 && document.getElementById("search1").value != 'Search') {
		window.location.assign("/search?kw2="+document.getElementById("search1").value.toLowerCase());
	}
	if(suggestCount >= 0) {
		window.location=document.getElementById("sug"+suggestCount).href;
	}
}	
	
function showSuggestion() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		// query has returned
		var xmlResponseText = checkAjax2(xmlHttp.responseText)
		if (xmlResponseText != "-" && xmlResponseText.length > 0)
		{
			document.getElementById("suggestions").innerHTML=xmlResponseText;
			document.getElementById("suggestions").style.visibility = "visible";
			sugVisible = true;
		}
		else
		{
			document.getElementById("suggestions").style.visibility = "hidden";
			sugVisible = false;
			suggestCount = -1;
		}	
	} 
} 
		
// wrapper to create an xmlHttp object cross-browser
function GetXmlHttpObject(handler) { 
	var objXMLHttp = null;
	
	if (window.XMLHttpRequest) {
		// we're in mozilla or ie7+
		objXMLHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// we're in IE6 or less
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(objXMLHttp == null) {alert("Your browser does not support the javascript features required for our site to function properly. Consider upgrading your browser or downloading the Firefox browser.");}
	return objXMLHttp;
}

function checkAjax(retString) {
	if(retString.substr(0,8) == ajaxCheckCode) {
		retString = retString.substr(8)
	} else {
		debugInfo('ajaxerror, alert msg, checkcode='+ajaxCheckCode+', returncode='+retString.substr(0,8));
		if (retString.length > 0) {
			alert('An error occured when retrieving information from our server. Please click refresh on your browser.');
			retString='';
		}
	}
	return retString
}

function checkAjax2(retString) {
	if(retString.substr(0,8) == ajaxCheckCode) {retString = retString.substr(8)} 
	else {debugInfo('ajaxerror, checkcode='+ajaxCheckCode+', returncode='+retString.substr(0,8));retString='';}
	return retString
}

function updateVipIcon(vip) {
	if(document.getElementById("vip")) {
		document.getElementById("navviplogo").src = "/images/vip-member-logo-hp.jpg";
		if(vip.length == 0) {
			document.getElementById("navvip1").innerHTML = "You have up to 500 points";
			document.getElementById("navvip2").innerHTML = "Save up to $5.00 on<br />your Next Order";
		} else {
			document.getElementById("navvip1").innerHTML = "You have " + vip + " points";
			document.getElementById("navvip2").innerHTML = "Save " + formatCurrency(parseInt(vip)/100) + " on<br />your Next Order";
		}
	}
}

function initSearch() {
	document.getElementById("search1").value = 'Search';
}

function checkbox(cbid) {
	if (document.getElementById(cbid).value == "on") {
		document.getElementById("cbimg_"+cbid).src = checkbox_unchecked;
		document.getElementById("cbstr_"+cbid).style.fontWeight = "normal";
		document.getElementById(cbid).value = "";
	} else {
		document.getElementById("cbimg_"+cbid).src = checkbox_checked;
		document.getElementById("cbstr_"+cbid).style.fontWeight = "bold";
		document.getElementById(cbid).value = "on";
	}
}
	
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) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function getCookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
				
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )	{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) {
		return null;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  ALTTXT V1.2
//  BY: BRIAN GOSSELIN OF SCRIPTASYLUM.COM
//  ADDED FADING EFFECT FOR IE4+ AND NS6+ ONLY AND OPTIMIZED THE CODE A BIT.
//  SCRIPT FEATURED ON DYNAMIC DRIVE (http://www.dynamicdrive.com)
//  Modifed by DD for doctype bug on Nov 13th, 2003


var dofade=true;     // ENABLES FADE-IN EFFECT FOR IE4+ AND NS6 ONLY
var center=false;     // CENTERS THE BOX UNER THE MOUSE, OTHERWISE DISPLAYS BOX TO THE RIGHT OF THE MOUSE
var centertext=false; // CENTERS THE TEXT INSIDE THE BOX. YOU CAN'T SIMPLY DO THIS VIA STYLE BECAUSE OF NS4.
                     // OTHERWISE, TEXT IS LEFT-JUSTIFIED. 


////////////////////////////// NO NEED TO EDIT BEYOND THIS POINT //////////////////////////////////////

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

var NS4 = (navigator.appName.indexOf("Netscape")>=0 && !document.getElementById)? true : false;
var IE4 = (document.all && !document.getElementById)? true : false;
var IE5 = (document.getElementById && document.all)? true : false;
var NS6 = (document.getElementById && navigator.appName.indexOf("Netscape")>=0 )? true: false;
var W3C = (document.getElementById)? true : false;
var w_y, w_x, navtxt, boxheight, boxwidth, mx, my, mabsx, mabsy;
var ishover=false;
var isloaded=false;
var ieop=0;
var op_id=0;
function getwindowdims(){
w_y=(NS4||NS6||window.opera)? window.innerHeight : (IE5||IE4)? document.body.clientHeight : 0;
w_x=(NS4||NS6||window.opera)? window.innerWidth : (IE5||IE4)? document.body.clientWidth : 0;
}

function getboxwidth(){
if(NS4)boxwidth=(navtxt.document.width)? navtxt.document.width : navtxt.clip.width;
if(IE5||IE4)boxwidth=(navtxt.style.pixelWidth)? navtxt.style.pixelWidth : navtxt.offsetWidth;
if(NS6)boxwidth=(navtxt.style.width)? parseInt(navtxt.style.width) : parseInt(navtxt.offsetWidth);
}

function getboxheight(){
if(NS4)boxheight=(navtxt.document.height)? navtxt.document.height : navtxt.clip.height;
if(IE4||IE5)boxheight=(navtxt.style.pixelHeight)? navtxt.style.pixelHeight : navtxt.offsetHeight;
if(NS6)boxheight=parseInt(navtxt.offsetHeight);

}

function movenavtxt(x,y){
if(NS4)navtxt.moveTo(x,y);
if(W3C||IE4){
navtxt.style.left=x+'px';
navtxt.style.top=y+'px';
}}

function getpagescrolly(){
if(NS4||NS6)return window.pageYOffset;
if(IE5||IE4)return ietruebody().scrollTop;
}

function getpagescrollx(){
if(NS4||NS6)return window.pageXOffset;
if(IE5||IE4)return ietruebody().scrollLeft;
}

function writeindiv(text){
if(NS4){
navtxt.document.open();
navtxt.document.write(text);
navtxt.document.close();
}
if(W3C||IE4)navtxt.innerHTML=text;
}

//**** END UTILITY FUNCTIONS ****//

function writetxt(text,imgid){
if(document.getElementById(imgid)) {document.getElementById(imgid).alt="";}
if(isloaded){
if(text!=0){
ishover=true;
if(NS4)text='<div class="navtext">'+((centertext)?'<center>':'')+text+((centertext)?'</center>':'')+'</div>';
writeindiv(text);
getboxheight();
if((W3C || IE4) && dofade){
ieop=0;
incropacity();
}}else{
if(NS4)navtxt.visibility="hide";
if(IE4||W3C){
if(dofade)clearTimeout(op_id);
navtxt.style.visibility="hidden";
}
writeindiv('');
ishover=false;
}}}

function incropacity(){
if(ieop<=100){
ieop+=10;
if(IE4 || IE5) {navtxt.style.filter="alpha(opacity="+ieop+")";}
if(NS6) {navtxt.style.MozOpacity=ieop/100;}
op_id=setTimeout('incropacity()', 50);
}}



if(NS4)document.captureEvents(Event.MOUSEMOVE);
document.onmousemove=moveobj;
window.onresize=getwindowdims;

function moveobj(evt){
	if (NS4){
		mx=evt.pageX
		my=evt.pageY
	}
	else if (NS6){
		mx=evt.clientX
		my=evt.clientY
	}
	else if (IE5){
		mx=event.clientX
		my=event.clientY
	}
	else if (IE4){
		mx=0
		my=0
	}

	if(NS4){
		mx-=getpagescrollx();
		my-=getpagescrolly();
	}

	if(isloaded && ishover){
		margin=(IE4||IE5)? 1 : 23;
		if(NS6)if(document.height+27-window.innerHeight<0)margin=15;
		if(NS4)if(document.height-window.innerHeight<0)margin=10;

		xoff=(center)? mx-boxwidth/2 : mx+5;
//		yoff=(my+boxheight+30-getpagescrolly()+margin>=w_y)? -15-boxheight: 30;
		yoff=(my+boxheight+25-getpagescrolly()+margin>=w_y)? -5-boxheight: 25;		
		movenavtxt( Math.min(w_x-boxwidth-margin , Math.max(2,xoff))+getpagescrollx() , my+yoff+getpagescrolly());
		if(NS4)navtxt.visibility="show";
		if(W3C||IE4) {navtxt.style.visibility="visible";}
	}  
	
}

/* This code is to allow product positioning to be adjusted in admin search results */
/***********************************************
* Drag and Drop Script: © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
var dragid;
var dragobject={
z: 0, x: 0, y: 0, offsetx : null, offsety : null, targetobj : null, dragapproved : 0,
initialize:function(){
document.onmousedown=this.drag
document.onmouseup=function(){
	if (this.dragapproved == 1) {
		if (Math.abs(parseInt(this.targetobj.style.left.replace('pt',''))) > 10 || Math.abs(parseInt(this.targetobj.style.top.replace('pt',''))) > 10) {
			document.getElementById(dragid.replace("img_","a_")).removeAttribute("href");
			document.getElementById("imgx").value = this.targetobj.style.left;
			document.getElementById("imgy").value = this.targetobj.style.top;
			document.getElementById("searchForm").submit();
		}
	}	
	this.dragapproved=0;
}
},
drag:function(e){
var evtobj=window.event? window.event : e
this.targetobj=window.event? event.srcElement : e.target
if (this.targetobj.className=="dpproductadmin" || this.targetobj.className == "dspimgadmin"){
this.dragapproved=1
this.targetobj.style.zIndex = 5;
dragid = this.targetobj.id;
document.getElementById("imgid").value = dragid;
if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0}
if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0}
this.offsetx=parseInt(this.targetobj.style.left)
this.offsety=parseInt(this.targetobj.style.top)
this.x=evtobj.clientX
this.y=evtobj.clientY
if (evtobj.preventDefault)
evtobj.preventDefault()
document.onmousemove=dragobject.moveit
}
},
moveit:function(e){
var evtobj=window.event? window.event : e
if (this.dragapproved==1){
this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px"
this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px"

return false
}
}
}

dragobject.initialize()

var shrs;
var smin;
var ssec;
var hourOffset;
function initShipTime() {
	ourDate = new Date();
	hourOffset = ourDate.getHours() + parseInt(shrs);
	if (hourOffset<0) {hourOffset = hourOffset+24;}
	timeToShip();
}
function timeToShip() {
	ourDate = new Date();
	ssec = 60 - parseInt(ourDate.getSeconds());
	smin = 60 - parseInt(ourDate.getMinutes());
	shrs = hourOffset - parseInt(ourDate.getHours());
	if (shrs < 0) {
		document.getElementById("shiptime").style.display = "none";
		return;
	}
	
	displaytime(shrs,"shiphours");
	displaytime(smin,"shipminutes");
	displaytime(ssec,"shipseconds");

	setTimeout("timeToShip();",100);
}
function displaytime(t,tid) {
	var timestr = t.toString();
	if (timestr.length == 1) {timestr = '0'+timestr;}
	document.getElementById(tid).innerHTML = timestr;
}
function whyBuy() {
	if(typeof whyBuyWindow == "object") {if (!whyBuyWindow.closed) {whyBuyWindow.close();}}
	whyBuyWindow = window.open("/whybuy","whybuy","toolbar=0,menubar=0,scrollbars=1,width=747px,height=1240px");
}
function showArticle(anum,winHeight){
	if(typeof articleWindow == "object") {if (!articleWindow.closed) {articleWindow.close();}}
	if (typeof winHeight == 'undefined') {winHeight = 1505;}
	articleWindow = window.open(siteURL+"/articlewindow?a="+anum+"&h="+(winHeight-10),"article"+anum,"toolbar=0,menubar=0,scrollbars=1,resizable=1,width=774px,height="+winHeight+"px");
	return false;
}

function DPLink(dpn) {
	document.getElementById("dpform"+dpn).submit();
	return false;
}
function GCaddToCart() {
	
	var amount = document.getElementById("giftamount").value;
	if (amount.length == 0 || amount == "Amount") {
		alert("Please enter a gift amount");
		return false;
	}
	if (parseInt(amount) < 5 || parseInt(amount) > 5000) {
		alert("Please enter a dollar amount between $5.00 and $5000.00");
		return false;
	}
	var message = document.getElementById("giftmessage").value;
	if (message.length == 0 || message == "Enter your message here.") {
		alert("Please enter a gift message");
		return false;
	}
	document.getElementById("prodform").submit();
	return true;
}

function addSpecialOrder() {
	
	var item = document.getElementById("so-item").value;
	if (item.length < 5) {
		alert("Please enter an item description. The item description may be too short.")
		return false;
	}
	var qty = document.getElementById("so-qty").value;
	if (qty.length == 0) {
		alert("Please enter a qty");
		return false;
	}
	if (parseInt(qty) < 0 || parseInt(qty) > 100) {
		alert("Please enter a qty between 1 and 100.");
		return false;
	}
	var cost = document.getElementById("so-cost").value;
	if (cost.length == 0) {
		alert("Please enter a cost");
		return false;
	}
	if (parseInt(cost) < 0 || parseInt(cost) > 10000) {
		alert("Please enter a cost between 1 and 10000.");
		return false;
	}
	var price = document.getElementById("so-price").value;
	if (price.length == 0) {
		alert("Please enter a price");
		return false;
	}
	if (parseInt(price) < 0 || parseInt(price) > 15000) {
		alert("Please enter a price between 1 and 15000.");
		return false;
	}
	document.getElementById("specialorderform").submit();
	return true;
}

function clearMessage() {
	if (document.getElementById("giftmessage").value == "Enter your message here.") {
		document.getElementById("giftmessage").value = "";
		document.getElementById("gcmessage").innerHTML = "";
		
	}
}

var ie = (navigator.appName.indexOf('Microsoft Internet Explorer')>-1);

function giftMessage() {
	var message = document.getElementById("giftmessage").value;
	var fontsize;
	if (ie) {fontsize = getStyle("gcmessage","fontSize");} else {fontsize = getStyle("gcmessage","font-size");}
	fontsize = fontsize.replace("px","");
	fontsize = parseInt(fontsize);
	
	var message2 = message.replace(/(\r\n|\r|\n)/g, '</p><p>');
	document.getElementById("gcmessage").innerHTML = "<p>"+message2+"</p>";
	var height = document.getElementById("gcmessage").offsetHeight;
	
	if (parseInt(height) > 200) {
		if (fontsize < 14) {
			message = message.substr(0,message.length-1);
			document.getElementById("giftmessage").value = message;
			message2 = message.replace(/(\r\n|\r|\n)/g, '</p><p>');
			document.getElementById("gcmessage").innerHTML = "<p>"+message2+"</p>";
		} else {
			document.getElementById("gcmessage").style.fontSize = (fontsize-1) + "px";
		}
	}
	if (parseInt(height) < 160 && fontsize < 20) {
		document.getElementById("gcmessage").style.fontSize = (fontsize+1) + "px";
	}
}


	

function getStyle(el,styleProp)
{
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}



function clearAmount() {
	if (document.getElementById("giftamount").value == "Amount") {
		document.getElementById("giftamount").value = "";
		document.getElementById("gc5").innerHTML = "$TBD";
		document.getElementById("price").innerHTML = "$TBD";
	}
}
function blurAmount() {
	if (document.getElementById("giftamount").value == "") {
		document.getElementById("giftamount").value = "Amount";
		document.getElementById("gc5").innerHTML = "$50.00";
		document.getElementById("price").innerHTML = "$5.00 - $5000.00";
	}
}

var lastGoodAmount = "";
function giftAmount() {
	var amount = document.getElementById("giftamount").value;
	if (validAmount(amount)) {
		lastGoodAmount = amount;
	} else {
		amount = lastGoodAmount;
		document.getElementById("giftamount").value = amount;
	}
	if (amount.length >0) {
		document.getElementById("gc5").innerHTML = formatCurrency(amount);
		document.getElementById("price").innerHTML = formatCurrency(amount);
	} else {
		document.getElementById("gc5").innerHTML = "$TBD";
		document.getElementById("price").innerHTML = "$TBD";
	}
}

function validAmount(sText) {
   var validChars = "0123456789";
   var isValid=true;
   var qchar;

   for (i = 0; i < sText.length && isValid == true; i++) 
   { 
      qchar = sText.charAt(i); 
      if (validChars.indexOf(qchar) == -1) {isValid = false;}
   }
   if (sText.length > 4) {isValid = false;}
   return isValid;
}


/*	Product Detail */

var lastGoodQty = '1';
var imageNum = 1;
var skuPhotoSelected = -1;
var borderFade = 0;
var borderFadeDelay = 5;
var borderFadeSteps = 5;
var hiLiteVarient = '';
var showZoom = false;
var selectIndex = new Array();
var stockArray = new Array();
var inStock = false;
var notify = false;
var optionCnt;
var skuIndex;

function productdetailLoad() {
	if (document.getElementById("tabs")) {document.getElementById("tabs").style.display = "block";}
	if(productCombo && comboCustomize) {
		updatedata();
		if(comboAltSku) {document.getElementById("comboconfignote").style.display = "inline-block";}
	}

	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = updateSelect;
	xmlHttp.open("GET", "/ajax/stock?p="+manprodcode+"&vt="+varientType, true);		
	xmlHttp.send(null);
	
	if (document.getElementById("prevnext")) {
		xmlHttp5 = GetXmlHttpObject();
		xmlHttp5.onreadystatechange = updateProductLinks;
		xmlHttp5.open("GET", "/ajax/productlinks?p="+manprodcode, true);		
		xmlHttp5.send(null);
	}
	
	xmlHttp2 = GetXmlHttpObject();
	xmlHttp2.onreadystatechange = updateRecentlyViewed;
	xmlHttp2.open("GET", "/ajax/recent?p="+manprodcode, true);		
	xmlHttp2.send(null);
	
	if (store != 'mad') {
		xmlHttp3 = GetXmlHttpObject();
		xmlHttp3.onreadystatechange = updateAlsoBought;
		xmlHttp3.open("GET", "/ajax/alsobought?p="+manprodcode, true);		
		xmlHttp3.send(null);
	}

	fixSpacer();
	if (dailySpecial) {countDown();}
	if (photoLarge.length > 0 && document.getElementById("zoomImage")) {document.getElementById("zoomImage").src = static2url + "/productimages/imageslarge/"+photoLarge+".jpg";}
}

function updateSelect() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		stockArray = checkAjax(xmlHttp.responseText).split("|");
		if (varientType == 0) {
			if (stockArray[0] == 'true') {inStock = true;skuInStock = true;}
			else if (stockArray[1] != 'false') {
				notify = true;
				if (stockArray[1] != 'true') {
					document.getElementById("pexpdate").innerHTML = "Expected " + stockArray[1];
					document.getElementById("pexpdate").style.display = "inline";
					document.getElementById("qtydiv").style.display = "none";
				}
			}
		} else { 
			document.getElementById("partno").options.length = 0;
			stockArray = checkAjax(xmlHttp.responseText).split("|");
			document.getElementById("partno").options[0] = new Option(varientSelectText,'');
			optionCnt = 1;
			var optionText;
			var oosmsg;
			for(i=0;i < varientCode.length;i++) {
				oosmsg = '';
				if (stockArray[i] == 'true' || stockArray[i+varientCode.length] != 'false' || skuSpecial[i] || amode) {
					optionText = varientText[i];
					selectIndex[optionCnt] = i;
					if (stockArray[i] == 'true') {inStock = true;}
					if (stockArray[i+varientCode.length] != 'false') {
						notify = true;
						if (stockArray[i+varientCode.length] == 'true') {oosmsg = ' (OutOfStock)';} else {oosmsg = ' (Due ' + stockArray[i+varientCode.length] + ')';}
					}
					if (stockArray[i] == 'false' && !skuSpecial[i]) {optionText = optionText + oosmsg;}
					if (!dailySpecial && (skuSalePrice[i] - discountprice) > 0.01) {optionText = optionText + ' +' + formatCurrency2(skuSalePrice[i]-discountprice);}
					document.getElementById("partno").options[optionCnt] = new Option(optionText,manprodcode+varientCode[i]);
					if (stockArray[i] == 'false' && !skuSpecial[i]) {document.getElementById("partno").options[optionCnt].style.color = '#808080';}
					optionCnt++;
				}
			}
			checkVarient();
		}
		if (inStock) {showInStock();} 
		else if (specialOrder) {showSpecialOrder(); }
		else if (notify) {showNotifyMe();}
		else {showOutOfStock();}	
	}
}
function updateRecentlyViewed() {
	if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") {
		document.getElementById("recentdiv").innerHTML = checkAjax(xmlHttp2.responseText);
		fixSpacer();
	}
}
function updateAlsoBought() {
	if (xmlHttp3.readyState==4 || xmlHttp3.readyState=="complete") {
		document.getElementById("alsoboughtdiv").innerHTML = checkAjax(xmlHttp3.responseText);
		fixSpacer();
		
		if (store != 'mad') {
			xmlHttp4 = GetXmlHttpObject();
			xmlHttp4.onreadystatechange = updateRelated;
			xmlHttp4.open("GET", "/ajax/related?p="+manprodcode, true);		
			xmlHttp4.send(null);
		}
	}
}		
function updateRelated() {
	if (xmlHttp4.readyState==4 || xmlHttp4.readyState=="complete") {
		document.getElementById("relateddiv").innerHTML = checkAjax(xmlHttp4.responseText);
		fixSpacer();
	}
}
function updateProductLinks() {
	if (xmlHttp5.readyState==4 || xmlHttp5.readyState=="complete") {
		document.getElementById("prevnext").innerHTML = checkAjax(xmlHttp5.responseText);
	}
}
function validQty(sText) {
   var validChars = "0123456789";
   var isValid=true;
   var qchar;

   for (i = 0; i < sText.length && isValid == true; i++) 
   { 
      qchar = sText.charAt(i); 
      if (validChars.indexOf(qchar) == -1) {isValid = false;}
   }
   if (sText.length > 2) {isValid = false;}
   return isValid;
}
function inStoreOnly() {
	alert('The manufacturer of this product has requested that we sell this product only in our retail store and not over the internet. You can still order this product, but your order will need to be picked up at our store in Portland, OR.');
}
function checkQty() {
	document.getElementById("qty").style.backgroundColor = "#ffffff";
	var qtyForm = document.getElementById("qty");
	if (validQty(qtyForm.value)) {lastGoodQty = qtyForm.value;}else{qtyForm.value=lastGoodQty;}
	updatePrice();
}
function checkVarient() {
	if (varientType > 0) {
		skuIndex = document.getElementById("partno").selectedIndex;
		document.getElementById("partno").style.backgroundColor = "#ffffff";
		if (pricevaries == true) {updateMSRP();}
		updatePrice();
	}
	if (varientType > 0 && (!productCombo || !comboCustomize)) {
		if((skuIndex > 0 && (amode || stockArray[selectIndex[skuIndex]] == 'true')) || (skuIndex == 0 && inStock)) {
			skuInStock = true;
			showInStock();
		} else {	
			if (skuSpecial[selectIndex[skuIndex]] || (skuIndex === 0 & specialOrder)) {
				skuInStock = true;
				showSpecialOrder();
				if (skuIndex === 0 & specialOrder) {document.getElementById("stockNote").innerHTML = "This is a special order item, but is usually available within several days. We will contact you with order confirmation once availability has been determined.";}
			} else {
				skuInStock = false;
				showNotifyMe();
			}
		}
	}
	if (varientType > 0 && productCombo && !comboCustomize) {comboProductList = skuComboCodes[skuIndex];}
	if (varientType == 0 && productCombo) {
		if (comboInStock > 0) {
			skuInStock = true;
			showInStock();
		} else {
			skuInStock = false;
			showNotifyMe();
			document.getElementById("stockNote").innerHTML = "This configuration is currently out of stock. Select the Customize tab below to change your options or click Notify Me for availability.";
		}
			
	}
	if (varientType > 0){
		if (skuPhotoSelected >= 0 && document.getElementById("thumb"+skuPhotoSelected)) {document.getElementById("thumb"+skuPhotoSelected).style.border = "double 3px #d0d0d0";}
		
		if (skuPhoto[selectIndex[skuIndex]] > 0 && document.getElementById("thumb"+skuPhoto[selectIndex[skuIndex]])) {
			if(skuPhotoVersion[selectIndex[skuIndex]]==0) {displayImage(document.getElementById("partno").value.substr(0,5),skuPhoto[selectIndex[skuIndex]]);}
			if(skuPhotoVersion[selectIndex[skuIndex]]>0) {displayImage(document.getElementById("partno").value.substr(0,5)+skuPhotoVersion[selectIndex[skuIndex]],skuPhoto[selectIndex[skuIndex]]);}
			document.getElementById("thumb"+skuPhoto[selectIndex[skuIndex]]).style.border = "solid 3px #ff0000";
			skuPhotoSelected = skuPhoto[selectIndex[skuIndex]];
			borderFade = 0;
			setTimeout("fadeToGold("+skuPhoto[selectIndex[skuIndex]]+");",100);
		} else {
			skuPhotoSelected = -1;
		}
//		Highlight the specifications for this varient
		if (hiLiteVarient.length == 7) {
			var hli = 0;
			while (document.getElementById(hiLiteVarient + hli)) {
				document.getElementById(hiLiteVarient+hli).style.color = "#4D606C";
				hli++;
			}
		}
		if (skuIndex>0) {
			hiLiteVarient = document.getElementById("partno").value.substr(5);
			var hli = 0;
			while (document.getElementById(hiLiteVarient + hli)) {
				document.getElementById(hiLiteVarient+hli).style.color = "#c81c22";
				hli++;
			}
		}
	}
//	added 6/15/09
	var calcQty;
	if (lastGoodQty.length > 0) {calcQty = parseInt(lastGoodQty);} else {calcQty = 0;}
	
//	end 6/15/09 added code	
}

function fadeToGold(thumbNum) {
	borderFade++;
	if(borderFade>borderFadeDelay) {
		var red = parseInt(255*(borderFadeSteps-(borderFade-borderFadeDelay))/borderFadeSteps + 25*(borderFade-borderFadeDelay)/borderFadeSteps);
		var green = parseInt(60*(borderFade-borderFadeDelay)/borderFadeSteps);
		var blue = parseInt(142*(borderFade-borderFadeDelay)/borderFadeSteps);
		document.getElementById("thumb"+thumbNum).style.borderColor = "rgb("+red+","+green+","+blue+")";
	}
	if (borderFade<(borderFadeSteps+borderFadeDelay)) {setTimeout("fadeToGold("+thumbNum+");",100);}
}
function showInStock() {
	if (document.getElementById("instockicon")) {
		document.getElementById("instockicon").src="/images/instock.jpg";
		document.getElementById("instockicon").alt="In Stock";
	}
	document.getElementById("addtocartImage").src = "/images/addtocart.png";
	if (document.getElementById("icon")) {document.getElementById("icon").style.display = "inline-block";}
	document.getElementById("stockMsgBox").style.display = "none";	
	document.getElementById("specialorder").value = "false";
	document.getElementById("qtydiv").style.visibility = "visible";
}

function showSpecialOrder() {
	if (document.getElementById("icon")) {document.getElementById("icon").style.display = "none";}
	document.getElementById("instockicon").src="/images/special-order.jpg";
	document.getElementById("instockicon").alt="Special Order";
	document.getElementById("addtocartImage").src = "/images/addtocart.png";
	document.getElementById("stockNote").innerHTML = "The " + varientSelectType + " you selected is a special order item but is usually available within several days. We will contact you with order confirmation.";
	document.getElementById("stockMsgBox").style.display = "inline-block";
	document.getElementById("specialorder").value = "true";
	document.getElementById("qtydiv").style.visibility = "visible";
}

function showNotifyMe() {
	if (document.getElementById("icon")) {document.getElementById("icon").style.display = "none";}
	document.getElementById("addtocartImage").src = "/images/notifyme.png";	
	document.getElementById("stockNote").innerHTML = "Sorry, but the " + varientSelectType + " you selected is currently out of stock. Click Notify Me to be informed when the item is back in stock.";
	document.getElementById("stockMsgBox").style.display = "inline-block";
	document.getElementById("instockicon").src="/images/outofstock.jpg";
	document.getElementById("instockicon").alt="Out of Stock";	
	document.getElementById("qtydiv").style.visibility = "hidden";
}

function showOutOfStock() {
	if (document.getElementById("icon")) {document.getElementById("icon").style.display = "none";}
	document.getElementById("selectbox").style.display = "none";	
	document.getElementById("stockNote").innerHTML = "Sorry, but this product is currently out of stock.";
	document.getElementById("stockMsgBox").style.display = "inline-block";
	document.getElementById("instockicon").src="/images/outofstock.jpg";
	document.getElementById("instockicon").alt="Out of Stock";	
}

function showDeposit() {
	if (document.getElementById("icon")) {document.getElementById("icon").style.display = "none";}
	document.getElementById("addtocartImage").src = "/images/addtocart.png";
	document.getElementById("stockNote").innerHTML = "This product is currently out of stock, but we are accepting deposits so you can be one of the first to receive this product when it becomes available.";
	document.getElementById("stockMsgBox").style.display = "inline-block";
	document.getElementById("instockicon").src="/images/accepting-deposits.gif";
	document.getElementById("instockicon").alt="Accepting Deposits";	
}


function updateMSRP() {
	if (pricevaries) {
		if (skuIndex > 0) {msrpPrice = skuMSRP[selectIndex[skuIndex]]} else {msrpPrice = minMSRP;}
		if (document.getElementById("msrp")) {document.getElementById("msrp").innerHTML =  formatCurrency(msrpPrice);}
	}
}

function updatePrice() {
	var regularPrice = ourprice;
	var discountPrice = discountprice;
	var qdiscount = 0;
	var qtyCalc;if (lastGoodQty.length > 0) {qtyCalc = parseInt(lastGoodQty);} else {qtyCalc = 1;}
	if (qtyDiscounts) {for(i=0;i<=quanBreak.length;i+=1) {if (qtyCalc >= quanBreak[i]) {qdiscount = quanDisc[i];}}}
	if (productCombo && comboCustomize) {discountPrice = ourprice*(1-discountAmt/100);}
	if(pricevaries) {
		if (skuIndex > 0) {
			discountPrice = skuSalePrice[selectIndex[skuIndex]];
			regularPrice = skuPrice[selectIndex[skuIndex]];
			mip = skuMin[selectIndex[skuIndex]];
		} else {
			discountPrice = discountprice;
			regularPrice = ourprice;
		}
		
		if (document.getElementById("pricetext")) {
			if (skuIndex == 0) {
				if (ourprice > discountprice) {
					document.getElementById("pricetext").innerHTML = pd_salelowas;
				} else {
					document.getElementById("pricetext").innerHTML = pd_lowas;
				}
			} else {
				if (ourprice > discountprice) {
					document.getElementById("pricetext").innerHTML = pd_sale;
				} else {
					document.getElementById("pricetext").innerHTML = pd_reg;
				}
			}
		}
	}

	discountPrice = discountPrice*(1-qdiscount);
	discountPrice = roundCurrency(discountPrice);
	calculatedPrice = discountPrice;
	if (isCurrency(pmprice)) {discountPrice = pmprice;}		//use price-match price instead
	var totalDiscount = 0;
	if (msrpPrice > 0 ) {totalDiscount = 100*((msrpPrice-discountPrice)/msrpPrice);}
	var totalPrice = discountPrice*qtyCalc;
	if(totalDiscount >= showDiscPercent || (msrpPrice-discountPrice) >= showDiscDollar) {
		document.getElementById("savingsinfo").innerHTML = "You Save:&nbsp;";
		document.getElementById("savingsinfo").style.visibility = "visible";
		document.getElementById("savings").innerHTML = formatCurrency(qtyCalc*msrpPrice-totalPrice) + ' (' + parseInt(totalDiscount+0.000001) + '%)'; 
		if (document.getElementById("msrp")) {
			document.getElementById("msrplabel").innerHTML = "MSRP:&nbsp;";
			document.getElementById("msrplabel").style.visibility = "visible";
			document.getElementById("msrp").innerHTML = formatCurrency(msrpPrice);
		}	
	} else {
		document.getElementById("savingsinfo").innerHTML = "";
		document.getElementById("savingsinfo").style.visibility = "hidden";
		document.getElementById("savings").innerHTML = "";
		if (document.getElementById("msrp")) {
			document.getElementById("msrplabel").innerHTML = "";
			document.getElementById("msrplabel").style.visibility = "hidden";
			document.getElementById("msrp").innerHTML = "";
		}
	}
	if (document.getElementById("regularprice")) {
		document.getElementById("regularprice").innerHTML = formatCurrency(regularPrice);
	}	
	document.getElementById("price").innerHTML = formatCurrency(discountPrice);

	document.getElementById("units").style.visibility = "visible";
	
	if(document.getElementById("shipnote") && shippingRestriction != 3) {
		if(gndShipPromo >= 0 && totalPrice >= gndShipPromo && !shipOverweight) {
			document.getElementById("shipnote").innerHTML = "Qualifies for Free Shipping!";
		} else if (shipOverweight) {
			document.getElementById("shipnote").innerHTML = "Overweight Shipping Charges Apply";
		} else if (gndShipPromo >= 0) {
			document.getElementById("shipnote").innerHTML = "Free Shipping on Orders Over $" + gndShipPromo +"*";
		}
	}
	
	if(document.getElementById("priceCalc")) {
		if (qtyCalc > 1) {
			document.getElementById("priceCalc").innerHTML =  formatCurrency(discountPrice)+' x '+lastGoodQty+' = ' + formatCurrency(totalPrice);
			document.getElementById("priceinfo2").style.height = "85px";
			document.getElementById("priceinfo2").style.backgroundImage = "url(/images/292x85-box.gif)";
		} else {
			document.getElementById("priceCalc").innerHTML = "";
			document.getElementById("priceinfo2").style.height = "59px";
			document.getElementById("priceinfo2").style.backgroundImage = "url(/images/292x59-box.gif)";
		}
	}
	if (VIPtype > 0 && document.getElementById("earnVIP")) {
		document.getElementById("earnVIP").style.display="block";
		document.getElementById("VIPpoints").innerHTML = parseInt(10*totalPrice*VIPtype);
	}
	if (pricedisplay == 2) {document.getElementById("enterQty").style.display="none";}
	
}

function clearEmailBox()
{	
	if (document.outofstock.notifyemail.value == 'Your email')
	{
		document.outofstock.notifyemail.value = ''
	}
	return true;
}

function displayImage(mpc,pic) {
	if(document.getElementById("prodImage")) {
		document.getElementById("prodImage").src = static2url + "/productimages/images450/"+mpc+"-"+String(pic)+".jpg";
		document.getElementById("prodImage").alt = document.getElementById("thumb"+pic).alt;
		document.getElementById("prodImage").title = document.getElementById("thumb"+pic).title;
		document.getElementById("zoomImage").src = static2url + "/productimages/imageslarge/"+mpc+"-"+String(pic)+".jpg";
		document.getElementById("zoomImage").alt = document.getElementById("thumb"+pic).alt;
		document.getElementById("zoomImage").title = document.getElementById("thumb"+pic).title;
	}
	imageNum = pic;
	if(photoZoom[imageNum-1]) {
		if(showZoom) {
			showZoom = false;
			zoom_off();
		}
		document.getElementById("zoom").innerHTML = "Click image above to zoom.";
	} else {
		zoom_off();
		showZoom = false;
		document.getElementById("zoom").innerHTML = "";
	}
}

var xx;
var yy;
var lastxx = 0;
var lastyy = 0;
var zoomw = 1200;
var zoomh = 800;
var imagew = 450;
var imageh = 300;
var itop;
var ileft;
var clipstring;
var zrectw;
var zrecth;
var zleft;
var ztop;

function zoomToggle() {
	if(photoZoom[imageNum-1]) {
		if(showZoom) {
			showZoom = false;
			zoom_off();
			document.getElementById("zoom").innerHTML = "Click image above to zoom.";
		} else {
			showZoom = true;
			zoom_on();
			document.getElementById("zoom").innerHTML = "Click image to disable zoom.";
		}
	}
}

function zoom_on() {
	if(photoZoom[imageNum-1] && showZoom) {
//		zoomw = photoWidth[imageNum-1];
//		zoomh = photoHeight[imageNum-1];
		document.getElementById("prodImage").style.display = "none";
		document.getElementById("zoomImage").style.display = "inline";
		document.getElementById("zoomImage").alt = "";
		document.getElementById("zoomImage").title = "";
		if(document.getElementById("rect"+imageNum)) {document.getElementById("rect"+imageNum).style.visibility = "visible";}

	}
	if (ie) {
		var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1])
		if (version >= 6 && version < 7) {ieox = document.body.scrollLeft; ieoy = document.body.scrollTop;}
		if (version >= 7) {ieox = document.documentElement.scrollLeft; ieoy = document.documentElement.scrollTop;}
	} 
}

function zoom_off() {
	document.getElementById("prodImage").style.display = "inline";
	document.getElementById("zoomImage").style.display = "none";
	if(document.getElementById("rect"+imageNum)) {document.getElementById("rect"+imageNum).style.visibility = "hidden";}
}

function zoom_move() {
	if(typeof(window['mx']) != "undefined") {
		var voffset = 0;
		var vroffset = 0;
		if(storeGroup == 2) {voffset=77;vroffset = 3;}
		if(ie) { xx = mx-232; yy = my-223;
		} else {
			xx = mx-231; yy = my-220;}	//220
		yy = yy + voffset;
		yy = yy + getpagescrolly();
		xx = xx + getpagescrollx();
		itop = parseInt(yy/imageh*zoomh-yy);
		if (itop<0) {itop=0}
		ileft = parseInt(xx/imagew*zoomw-xx);
		if (ileft<0) {ileft=0}
		clipstring = "rect("+itop+"px,"+(ileft+imagew)+"px,"+(itop+imageh)+"px,"+ileft+"px)";
		zrectw = 50*450/zoomw;
		zrecth = 33*300/zoomh;
		//alert(parseInt(yy/300*(67-zrecth)));
		ztop = parseInt(yy/300*(33-zrecth));
		zleft = parseInt(xx/450*(50-zrectw));
		if(ie) {zleft=zleft-59;ztop=ztop+2;} else {zleft=zleft-1;ztop=ztop-42;}
		ztop = ztop+vroffset;
		document.getElementById("zoomImage").style.clip = clipstring;
		document.getElementById("zoomImage").style.marginLeft=-ileft+"px";
		document.getElementById("zoomImage").style.marginTop=-itop+"px";
		
		if(document.getElementById("rect"+imageNum)) {
			document.getElementById("rect"+imageNum).style.marginLeft = zleft+"px";
			document.getElementById("rect"+imageNum).style.marginTop = ztop+"px";
		}
	}
	return false;
}

var shipWindow;
var sizeWindow;
var qtyWindow;
var whyBuyWindow;

function shipQuote(mpc) {
	if(typeof shipWindow == "object") {if (!shipWindow.closed) {shipWindow.close();} }
	var partno="";
	if(document.getElementById("partno")) {partno=document.getElementById("partno").value;}
	shipWindow = window.open("/shipquote?p="+mpc+"&q="+lastGoodQty+"&pn="+partno,"shipquote"+mpc,"toolbar=0,menubar=0,scrollbars=0,width=758px,height=608px");
}

function sizeInfo(mpc) {
	if(typeof sizeWindow == "object") {if (!sizeWindow.closed) {sizeWindow.close();} }
	sizeWindow = window.open("/sizechart.asp?p="+mpc,"sizechart"+mpc,"toolbar=0,menubar=0,scrollbars=0,width=650px,height=350px");
}

function qtyDiscInfo(mpc) {
	if(typeof qtyWindow == "object") {if (!qtyWindow.closed) {qtyWindow.close();} }
	var partno="";
	if(document.getElementById("partno")) {partno=document.getElementById("partno").value;}	
	qtyWindow = window.open("/qtydiscounts?p="+mpc+"&pn="+partno,"qtydiscounts"+mpc,"toolbar=0,menubar=0,scrollbars=0,width=608px,height=408px");
}



function vipPage(mpc) {
	if(typeof vipPageWindow == "object") {if (!vipPageWindow.closed) {vipPageWindow.close();} }
	vipPageWindow = window.open("/doublevip","vippage"+mpc,"toolbar=0,menubar=0,scrollbars=1,width=762px,height=850px");
}

function addCommas(nStr)
		{
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}	

function outOfStock() {
	if(typeof oosWindow == "object") {if (!oosWindow.closed) {oosWindow.close();} }
	var p = document.getElementById("partno").value
	if(p == "") {p = manprodcode;} 
	var q = "?p="+p.toLowerCase();
	if(productCombo) {q = q + "&c="+comboProductList.toLowerCase()+"&d="+dp;}
	oosWindow = window.open("/outofstock"+q,"oos"+p,"location=0,toolbar=0,menubar=0,scrollbars=0,width=758px,height=433px");
}

function getAdmin(vt) {
	if (document.getElementById("admininfo").innerHTML == "") {
		document.getElementById("admininfo").innerHTML = "Retreiving Admin Info ..."
		AdminxmlHttp = GetXmlHttpObject();
		AdminxmlHttp.onreadystatechange = updateAdmin;
		AdminxmlHttp.open("GET", "/commonfiles/admininfo.asp?p="+manprodcode+"&v="+vt, true);		
		// send the request
		AdminxmlHttp.send(null);
	}
}

function updateAdmin() {
	if (AdminxmlHttp.readyState==4 || AdminxmlHttp.readyState=="complete") {
		document.getElementById("admininfo").innerHTML = AdminxmlHttp.responseText;
		fixSpacer();
	}
}

function showVisitors() {
	if (document.getElementById("visitors").innerHTML == "") {
		AdminxmlHttp = GetXmlHttpObject();
		AdminxmlHttp.onreadystatechange = updateVisitors;
		AdminxmlHttp.open("GET", "/commonfiles/visitors.asp?p="+manprodcode, true);		
		AdminxmlHttp.send(null);
	} else {
		document.getElementById("visitors").innerHTML = '';
	}
	return false;
}

function updateVisitors() {
	if (AdminxmlHttp.readyState==4 || AdminxmlHttp.readyState=="complete") {
		document.getElementById("visitors").innerHTML = AdminxmlHttp.responseText;
		fixSpacer();
	}
}

function adminForm(adminlink) {
	document.getElementById("prodform").action = adminlink;
}

function explainVIP() {
	alert("VIP Points give you cash savings on this and future orders. We give you 500 points for joining ($5.00 off this order if you're not already a member) and when you buy this product, we'll add points to your balance for future use. Click on the VIP Buyers Club logo for more information.");
}

function cartForm(instock) {
	if (instock) {
		document.getElementById("cartforms").style.display = "inline";
		document.getElementById("outofstock").style.display = "none";
	} else {	
		document.getElementById("cartforms").style.display = "none";
		document.getElementById("outofstock").style.display = "inline";
	}
}

function countDown() {
	tsec = tsec - 1;
	if (tsec < 0) {
		tsec = 59;
		tmin = tmin - 1;
		if (tmin < 0) {
			tmin = 59;
			thrs = thrs - 1;
			if (thrs < 0) {
				thrs = 0;
				tmin = 0;
				tsec = 0;
				document.getElementById("hurry").innerHTML = "Sorry, this daily special is over.";
				displayCount();
				return;
			}
		}
	}
	displayCount();
	setTimeout("countDown();",1000);
}

function displayCount() {
	document.getElementById("timer").innerHTML = thrs + "<span class='tt'>hrs</span> : " + tmin + "<span class='tt'>min</span> : " + tsec + "<span class='tt'>sec</span>";
}

function createReview() {
	if(typeof reviewWindow == "object") {if (!reviewWindow.closed) {reviewWindow.close();} }
	reviewWindow = window.open("/review?p="+manprodcode.toLowerCase(),"review"+manprodcode,"location=0,toolbar=0,menubar=0,scrollbars=1,width=775px,height=800px");
}
function reviewHelpful(rn,v) {
	if (reviewVotes.match(rn+' ')) {
		document.getElementById("thank"+rn).style.display = "none";
		document.getElementById("onevote"+rn).style.display="inline-block";
	} else {
		reviewVotes = reviewVotes + rn + ' ';
		xmlHttp = GetXmlHttpObject();
		xmlHttp.open("GET", "/ajax/reviewvote?rn="+rn+"&v="+v, true);		
		xmlHttp.send(null)
		document.getElementById("thank"+rn).style.display = "inline-block";
	}
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

var shipAmount = 0;
var orderTotal = 0;
var tax = 0;
var duty = 0;
var taxRate = 0;
var canada = false;
var gndOnly = false;
var validShip = false;
var international = false;
var shipCodeSelected = "UPSGnd";
var lastGoodZip = "";


function pageloadShipping() {
	var zipCodeForm = document.getElementById("zipinput");
	if(validZip(postalCode)) { 
		zipCodeForm.value = postalCode;
		canada = false;
		lastGoodZip = postalCode;
		if (lastGoodZip.length == 5) {checkZipCode();}
	}
	else if (validPostal(postalCode)) {
		zipCodeForm.value = postalCode;
		canada = true;
		lastGoodZip = postalCode;
		if (lastGoodZip.length == 6 ) {checkZipCode();}
	} 
	else {lastGoodZip = "";}
	blurZipCode();
}

function focusZipCode() {
	var zipCodeForm = document.getElementById("zipinput");
	if (zipCodeForm.value == 'Enter Zip/Postal Code') {
		zipCodeForm.value = '';
		lastGoodZip = '';
	}
}

function blurZipCode() {
	var zipCodeForm = document.getElementById("zipinput");
	if ((!canada && zipCodeForm.value.length != 5) ||  (canada && zipCodeForm.value.replace(' ','').length != 6)){
		zipCodeForm.value = 'Enter Zip/Postal Code';
		clearShippingQuote();
	} 
}

function checkZipCode() {
	if (!document.getElementById("zipinput")) {return;}
	var zipCodeForm = document.getElementById("zipinput");
	if (validZip(zipCodeForm.value)) {
		lastGoodZip = zipCodeForm.value;
		canada = false;
	}
	else if (validPostal(zipCodeForm.value)) {
		lastGoodZip = zipCodeForm.value;
		canada = true;
	}
	else {
		zipCodeForm.value = lastGoodZip;
	}
	if (lastGoodZip.length == 5 && !canada) {
		getShipInfo();
		validShip = true;
	}
	else if (lastGoodZip.replace(" ","").length == 6 && canada) {
		getShipInfo();
		validShip = true;
	}
	else {	
		clearShippingQuote();
	}
}

function clearShippingQuote() {
	if (document.getElementById("shippingcostamt")) {
		document.getElementById("quotedisplay").innerHTML = "";
		if(document.getElementById("shippingcostamt")) {document.getElementById("shippingcostamt").innerHTML = "TBD"; }
		if(document.getElementById("taxcost")) {document.getElementById("taxcost").style.visibility = "hidden"; }
		shipAmount = 0;
		tax = 0;
		duty = 0;
		taxRate = 0;
		if(document.getElementById("ordertotalamt")) {document.getElementById("ordertotalamt").innerHTML = "TBD";}
		fixSpacer('viewcart');
	}
}

function keyZipCode(keycode) {
	if (keycode == 13) {return;}
	checkZipCode();
}

function goShip() {
	validShip = false;
	checkZipCode();
	if (!validShip){alert("Please enter a valid US ZipCode or Canadian Postal Code");}
}

function validZip(sText) {
   var validChars = "0123456789";
   var isValid=true;
   var qchar;

   for (i = 0; i < sText.length && isValid == true; i++) 
   { 
      qchar = sText.charAt(i); 
      if (validChars.indexOf(qchar) == -1) {isValid = false;}
   }
   if (sText.length > 5) {isValid = false;}
   return isValid;
}

function validPostal(sText) {
	var validNums = "0123456789";
	var validFirstChar = "ABCEGHJKLMNPRSTVXY";
	var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var isValid = true;
	var qchar;
	if (sText.substr(3,1) == " ") {sText = sText.substr(0,3)+sText.substr(4,3);}
	for (i = 0; i < sText.length && isValid == true; i++) 
	{ 
		qchar = sText.charAt(i).toUpperCase();
		switch(i)
		{
		case 0:
			if (validFirstChar.indexOf(qchar) == -1) {isValid = false;}
			break
		case 1:
			if (validNums.indexOf(qchar) == -1) {isValid = false;}
			break
		case 2:
			if (validChars.indexOf(qchar) == -1) {isValid = false;}
			break
		case 3:
			if (validNums.indexOf(qchar) == -1) {isValid = false;}
			break		
		case 4:
			if (validChars.indexOf(qchar) == -1) {isValid = false;}
			break
		case 5:
			if (validNums.indexOf(qchar) == -1) {isValid = false;}
			break
		}				
	}
	if (sText.length > 6) {isValid = false;}
	return isValid;
}
 
function getShipInfo() {
	// this is called to make sure the shipping location is the same as used for the ship quote.
	if (!international) {document.getElementById("zipinput").style.backgroundImage = "none";}
	shipCalc = false;
	shipxmlHttp = GetXmlHttpObject();
	// provide a callback for when the query gets processed
	shipxmlHttp.onreadystatechange = updateShipping;

	var countryCode;
	if (international) {
		countryCode = document.getElementById("countryselect").value 
	} else {
		if (canada) {countryCode="ca"} else {countryCode="us";}
	}
	document.getElementById("quotedisplay").innerHTML = "calculating shipping quote";
	var q = "?z="+lastGoodZip+"&cc="+countryCode+"&g=1"
	if (document.getElementById("mpc")) {q = q+"&mpc="+document.getElementById("mpc").value;}
	if (document.getElementById("vc")) {q = q+"&vc="+document.getElementById("vc").value;}
	if (document.getElementById("itemqty")) {q = q+"&q="+document.getElementById("itemqty").value;}
	shipxmlHttp.open("GET", "/ajaxship.asp"+q, true);	
	shipxmlHttp.send(null)
}
		
	// called when xmlHttp object changes state
function updateShipping() {
	if (shipxmlHttp.readyState==4 || shipxmlHttp.readyState=="complete") {
		var quotedisplay = checkAjax(shipxmlHttp.responseText);
		if (quotedisplay.length > 0) {
			document.getElementById("quotedisplay").innerHTML = quotedisplay;
			if (document.getElementById("shippingcostamt")) {
				if(document.getElementById("shipRate").value == "") {
					document.getElementById("shippingcostamt").innerHTML = "TBD";
					shipAmount = 0;
				} else {
					shipAmount = parseFloat(document.getElementById("shipRate").value);
					document.getElementById("shippingcostamt").innerHTML = formatCurrencyFree(shipAmount+giftboxAmt);
					shipCalc = true;
				}
				if (document.getElementById("taxRate")) {
					taxRate = parseFloat(document.getElementById("taxRate").value);
					if (taxRate == 0) {document.getElementById("taxcost").style.visibility = "hidden";}
				}	
			}
			shipCodeSelected = document.getElementById("shippingQuoteShipCode").value;
			if(document.getElementById("duty")) {duty = parseFloat(document.getElementById("duty").value);}
			if(document.getElementById("ordertotalamt")) {updateTotal('updateShipping');}
			if (document.getElementById("viewcart")) {
				fixSpacer();
				if (document.getElementById("shippingAlert")) {
					if(document.getElementById("shippingAlert").value.toLowerCase() == 'true') {
						alert ('With the discount code(s) you have entered, the total value of the items in your cart no longer meets our minimum requirement for free shipping')
					}	
				}
			}
		}
	}
}	

function selectInternational() {
	document.getElementById("domshipselect").style.display = "none";
	document.getElementById("intshipselect").style.display = "inline";
	document.getElementById("quotedisplay").innerHTML = "";
	international = true;
	if (document.getElementById("viewcart")) {fixSpacer();}
	checkCountry();
}

function selectUscanada() {
	document.getElementById("domshipselect").style.display = "inline";
	document.getElementById("intshipselect").style.display = "none";	
	document.getElementById("quotedisplay").innerHTML = "";
	international = false;
	if (document.getElementById("viewcart")) {fixSpacer();}
	checkZipCode();
}

function checkCountry() {
	if(document.getElementById("countryselect").value.length == 2) {getShipInfo();} else {clearShippingQuote();}
}

/* OutOfStock Notify */
function clickEmail() {
	var email = document.getElementById("oos-emailinput").value;
	if (email=="Enter your email address") {document.getElementById("oos-emailinput").value = "";}
}

function notifyMe() {
	var email = document.getElementById("oos-emailinput").value;
	var re = new RegExp("^[a-zA-Z0-9&\+._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
	if (!email.match(re)) {
		alert("The email address is not of a valid form for our software. Please check to make sure it was entered correctly.");
		return;
	}
	var partno="";
	if (document.getElementById("oos-partno0")) {partno = document.getElementById("oos-partno0").value;}
	if (document.getElementById("oos-partno1")) {
		partno = document.getElementById("oos-partno1").options[document.getElementById("oos-partno1").selectedIndex].value;
		if (partno == "") {
			alert("Please select a color/size for the product you are interested in");
			return;
		}
	}
	xmlHttp = GetXmlHttpObject();

	var q = "?e="+email+"&p="+partno
	if (document.getElementById("comboproductlist")) {
		q = q + "&c="+document.getElementById("comboproductlist").value;
		q = q + "&d="+document.getElementById("cpd").value;
	}
	if (document.getElementById("optin")) {
		if (document.getElementById("optin").value == "true") {q = q + "&optin=1";}
	}
	xmlHttp.onreadystatechange = notifyEmail;
	xmlHttp.open("GET", "/ajax/notifyemail" + q, true);		
	// send the request
	xmlHttp.send(null)
}
function optIn() {
	if (document.getElementById("optin").value.length == 0) {
		document.getElementById("optin").value = "true";
		document.getElementById("cbimg_optin").src = "/images/checkboxchecked.gif";
		document.getElementById("cbstr_optin").style.fontWeight = "bold";
	} else {
		document.getElementById("optin").value = "";
		document.getElementById("cbimg_optin").src = "/images/checkboxunchecked.gif";
		document.getElementById("cbstr_optin").style.fontWeight = "normal";
	}
}
function notifyEmail() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		alert(checkAjax(xmlHttp.responseText));
		window.close();
	}
}

/* Prior Special */
function priorSpecial() {
	if(typeof priSpecWindow == "object") {if (!priSpecWindow.closed) {priSpecWindow.close();} }
	var p = document.getElementById("partno").value
	if(p == "") {p = manprodcode;} 
	var q = "?p="+p.toLowerCase();
	priSpecWindow = window.open("/priorspecial"+q,"psp"+p,"location=0,toolbar=0,menubar=0,scrollbars=0,width=758px,height=433px");
}
function getPriorSpecial() {
	var email = document.getElementById("oos-emailinput").value;
	var re = new RegExp("^[a-zA-Z0-9&\+._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
	if (!email.match(re)) {
		alert("The email address is not of a valid form for our software. Please check to make sure it was entered correctly.");
		return;
	}
	var partno="";
	if (document.getElementById("oos-partno0")) {partno = document.getElementById("oos-partno0").value;}
	if (document.getElementById("oos-partno1")) {
		partno = document.getElementById("oos-partno1").options[document.getElementById("oos-partno1").selectedIndex].value;
		if (partno == "") {
			alert("Please select a color/size for the product you are interested in");
			return;
		}
	}
	xmlHttp = GetXmlHttpObject();

	var q = "?e="+email+"&p="+partno
	xmlHttp.onreadystatechange = notifyEmail;
	xmlHttp.open("GET", "/ajax/priorspecial" + q, true);		
	// send the request
	xmlHttp.send(null)
}

/* Contact Us */

function emailResponse() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		alert(checkAjax(xmlHttp.responseText));
	}
}

/* Visit Store Page */
var map = null;
var geocoder = null;

function loadVisitStore() {
	if (GBrowserIsCompatible()) {
   	    map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GSmallZoomControl());
       	geocoder = new GClientGeocoder();
        geocoder.getLatLng(
      		address,
       		function(point) {
	       		if (!point) {
           			alert(address + " not found");
	       		} else {
	       			map.setCenter(point, 13);
	       			var marker = new GMarker(point);
	       			map.addOverlay(marker);
	       			marker.openInfoWindowHtml(addressinfo);
	       		}
			}
	   	);
		
	} 

	var divHeight = document.getElementById("store_article").offsetHeight;
	if (parseInt(divHeight)< 380) {
		document.getElementById("spacer").style.height = (380-parseInt(divHeight))+"px";
	} else {
		document.getElementById("spacer").style.height = "0px";
	}
	document.getElementById("search1").value = 'Search';
	pageLoaded = true;
	f("check_menu");
}		


function trimLength(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString.length;
}
function taxinfo() {
	alert("Canadian GST/HST/PST taxes, import duties, and brokerage fees are collected at the time you place your order so there are no surprises or hidden charges when your order is delivered to you.");
}

function login() {
	if (document.getElementById("signinemailinput")) {
		if (document.getElementById("signinemailinput").value.length == 0) {
			alert('Please enter your email address');
			return false;
		}
		if (document.getElementById("signinpassinput").value.length == 0) {
			alert('Please enter your password');
			return false;
		}
	} else if (document.getElementById("customeremail")) {
		if (document.getElementById("customeremail").value.length == 0) {
			alert('Please enter your email address');
			return false;
		}
		if (document.getElementById("customerpassword").value.length == 0) {
			alert('Please enter your password');
			return false;
		}
	}
	document.getElementById("loginform").submit();
	return true;
}

function setSelect(sid,sval) {
	for(i=0;i<document.getElementById(sid).options.length;i++) {
		if(document.getElementById(sid).options[i].value == sval) {document.getElementById(sid).selectedIndex = i;}
	}
}

function goToOrder() {
	document.getElementById("redirect").value = "cart";
	document.getElementById("paymentform").submit();
}

/* Utility functions */

function trimLength(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString.length;
}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

function formatCurrency2(strValue)
{
	var a = formatCurrency(strValue);
	a = a.replace('.00','');
	return a;
}

function formatCurrencyFree(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
	if(dblValue == 0) {
		return "Free"
	} else {
		return formatCurrency(strValue)
	}
}	

function roundCurrency(strValue) {
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
//	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
//		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
//		dblValue.substring(dblValue.length-(4*i+3));
	return parseFloat(((blnSign)?'':'-') + dblValue + '.' + strCents);
}

function isURL(argvalue) {
	var regUrl = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	if(regUrl.test(argvalue) == false) {return false;}
	return true;
}

function isCurrency(argvalue) {
	var regUrl = /^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/;
	if(regUrl.test(argvalue) == false) {return false;}
	if(argvalue.length == 0){return false;}
	if(argvalue == "$"){return false;}
	return true;
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}




/* Add Tubes */
function checkTubeSelect() {
	if (document.getElementById("hiddenradio").checked) {
		alert("Please select the tube you would like to add");
		return false;
	}
	document.getElementById("addtubescart").submit();	
	return;
}
function goToCart() {
	document.getElementById("addtubescart").action='/cart/viewcart';
	document.getElementById("addtubescart").submit();	
	return false;
}
var tubeMPC = '';
function tubeImage(partno){
	return;	// the stored procedure that determines the image information needs to be updated
//	if(tubeMPC.length > 0 && tubeMPC != partno.substr(0,5)) {document.getElementById("img"+tubeMPC).src = document.getElementById("src"+tubeMPC).value;}
//	tubeMPC = partno.substr(0,5);
//	document.getElementById("img"+tubeMPC).src = document.getElementById("vimg"+partno).value
}

var states = new Array();

states[0] = new Array('Select State','','Armed Forces (AA)','AA','Armed Forces (AE)','AE','Armed Forces (AP)','AP','Alabama','AL','Alaska','AK','Arkansas','AR','Arizona','AZ','California','CA','Colorado','CO','Connecticut','CT','Delaware','DE','District of Columbia','DC','Florida','FL','Georgia','GA','Hawaii','HI','Idaho','ID','Illinois','IL','Indiana','IN','Iowa','IA','Kansas','KS','Kentucky','KY','Louisiana','LA','Maine','ME','Maryland','MD','Massachusetts','MA','Michigan','MI','Minnesota','MN','Mississippi','MS','Missouri','MO','Montana','MT','Nebraska','NE','Nevada','NV','New Hampshire','NH','New Jersey','NJ','New Mexico','NM','New York','NY','North Carolina','NC','North Dakota','ND','Ohio','OH','Oklahoma','OK','Oregon','OR','Pennsylvania','PA','Rhode Island','RI','South Carolina','SC','South Dakota','SD','Tennessee','TN','Texas','TX','Utah','UT','Vermont','VT','Virginia','VA','Washington','WA','West Virginia','WV','Wisconsin','WI','Wyoming','WY');
states[1] = new Array('Select Province','','Alberta','AB','British Columbia','BC','Manitoba','MB','New Brunswick','NB','Newfoundland/Labrador','NL','Northwest Territories','NT','Nova Scotia','NS','Nunavut','NU','Ontario','ON','Prince Edward Island','PE','Quebec','QC','Saskatchewan','SK','Yukon','YT');
states[2] = new Array('Select State','','Aus. Capital Territory','ACT','New South Wales','NSW','Northern Territory','NT','Queensland','QLD','South Australia','SA','Tasmania','TAS','Victoria','VIC','Western Australia','WA');
states[3] = new Array('Not Applicable','NA');
function accountstateform()
{
	var arraySelect;
	var myForm = document.customerinfoform;
	var billcountrycodeForm = myForm.billcountrycode;
	var billstateForm = myForm.billstate;
	var billcountrycode = billcountrycodeForm.options[billcountrycodeForm.selectedIndex].value;
	if (!billcountrycode) return;
	if (billcountrycode == "us") arraySelect = 0;
	if (billcountrycode == "ca") arraySelect = 1;
	if (billcountrycode == "au") arraySelect = 2;
	if (billcountrycode != "us" && billcountrycode != "ca" && billcountrycode != "au") arraySelect = 3;
	var list = states[arraySelect];
	billstateForm.options.length = 0;
	for(i=0;i<list.length;i+=2)
	{
		billstateForm.options[i/2] = new Option(list[i],list[i+1]);
	}
}			
function billStateSelect()
{
	var arraySelect;
	var billcountrycodeForm = document.getElementById("billingcountrycode");
	var billstateForm = document.getElementById("billingstate");
	var billcountrycode = billcountrycodeForm.options[billcountrycodeForm.selectedIndex].value;
	if (!billcountrycode) return;
	if (billcountrycode == "us") arraySelect = 0;
	if (billcountrycode == "ca") arraySelect = 1;
	if (billcountrycode == "au") arraySelect = 2;
	if (billcountrycode != "us" && billcountrycode != "ca" && billcountrycode != "au") arraySelect = 3;
	var list = states[arraySelect];
	billstateForm.options.length = 0;
	for(i=0;i<list.length;i+=2)
	{
		billstateForm.options[i/2] = new Option(list[i],list[i+1]);
	}
	if (document.getElementById("radiosameaddress").checked) {
		document.getElementById("shippingcountrycode").selectedIndex = document.getElementById("billingcountrycode").selectedIndex;
		shipStateSelect();
	}
}

function shipStateSelect() {
	
	var arraySelect;
	var shipcountrycodeForm = document.getElementById("shippingcountrycode");
	var shipstateForm = document.getElementById("shippingstate");
	var shipcountrycode = shipcountrycodeForm.options[shipcountrycodeForm.selectedIndex].value;
	if (!shipcountrycode) return;
	if (shipcountrycode == "us") arraySelect = 0;
	if (shipcountrycode == "ca") arraySelect = 1;
	if (shipcountrycode == "au") arraySelect = 2;
	if (shipcountrycode != "us" && shipcountrycode != "ca" && shipcountrycode != "au") arraySelect = 3;
	var list = states[arraySelect];
	shipstateForm.options.length = 0;
	for(i=0;i<list.length;i+=2)
	{
		shipstateForm.options[i/2] = new Option(list[i],list[i+1]);
	}
}


function clearExpiredCache() {
	cachexmlHttp = GetXmlHttpObject();
	cachexmlHttp.open("GET", "/ajax/expcache", true);		
	cachexmlHttp.send(null);
}

function makeCloseout() {
	if (confirm("Are you sure you want to move this product to Closeouts?")) {
		document.getElementById("admincloseout").style.borderColor = "#ff0000";
		var mpc = document.getElementById("adminmpc").value;
		var coprice = document.getElementById("closeoutprice").value;
		coxmlHttp = GetXmlHttpObject();
		coxmlHttp.onreadystatechange = updateCloseout;
		coxmlHttp.open("GET", "/ajax/makecloseout?p="+mpc+"&pr="+coprice, true);		
		coxmlHttp.send(null);
	}
	return false;
}

function updateCloseout() {
	if (coxmlHttp.readyState==4 || coxmlHttp.readyState=="complete") {
		var mpc = checkAjax(coxmlHttp.responseText);
		if(mpc.length == 5) {document.getElementById("admincloseout").style.borderColor = "#00ff00";}
	}
}

function makeGoingGone() {
	if (confirm("Are you sure you want to move this product to Going, Going Gone?")) {
		document.getElementById("admingoinggone").style.borderColor = "#ff0000";
		var mpc = document.getElementById("adminmpc").value;
		var coprice = document.getElementById("closeoutprice").value;
		ggxmlHttp = GetXmlHttpObject();
		ggxmlHttp.onreadystatechange = updateGoingGone;
		ggxmlHttp.open("GET", "/ajax/makegoinggone?p="+mpc+"&pr="+coprice, true);		
		ggxmlHttp.send(null);
	}
	return false;
}

function updateGoingGone() {
	if (ggxmlHttp.readyState==4 || ggxmlHttp.readyState=="complete") {
		var mpc = checkAjax(ggxmlHttp.responseText);
		if(mpc.length == 5) {document.getElementById("admingoinggone").style.borderColor = "#00ff00";}
	}
}

function addProductList() {
	document.getElementById("adminaddproductlist").style.borderColor = "#ff0000";
	var mpc = document.getElementById("adminmpc").value;
	plxmlHttp = GetXmlHttpObject();
	plxmlHttp.onreadystatechange = updateProductList;
	plxmlHttp.open("GET", "/ajax/productlist?p="+mpc, true);		
	plxmlHttp.send(null);
	return false;
}

function updateProductList() {
	if (plxmlHttp.readyState==4 || plxmlHttp.readyState=="complete") {
		var mpc = checkAjax(plxmlHttp.responseText);
		if(mpc.length == 5) {document.getElementById("adminaddproductlist").style.borderColor = "#00ff00";}
	}
}

function addPickList() {
	if(document.getElementById("partno").value == "") {
		alert("Please select color and/or size");
		return false;
	} else {
		document.getElementById("adminaddpicklist").style.borderColor = "#ff0000";
		plxmlHttp = GetXmlHttpObject();
		plxmlHttp.onreadystatechange = updatePickList;
		plxmlHttp.open("GET", "/ajax/picklist?p="+document.getElementById("partno").value, true);		
		plxmlHttp.send(null);
		return false;
	}
}

function updatePickList() {
	if (plxmlHttp.readyState==4 || plxmlHttp.readyState=="complete") {
		if(checkAjax(plxmlHttp.responseText).length == 12) {document.getElementById("adminaddpicklist").style.borderColor = "#00ff00";}
	}
}

function requestCount() {
	if(document.getElementById("partno").value == "") {
		alert("Please select color and/or size");
		return false;
	} else {
		document.getElementById("adminrequestcount").style.borderColor = "#ff0000";
		plxmlHttp = GetXmlHttpObject();
		plxmlHttp.onreadystatechange = updateReqCount;
		plxmlHttp.open("GET", "/ajax/requestcount?p="+document.getElementById("partno").value, true);		
		plxmlHttp.send(null);
		return false;
	}
}

function updateReqCount() {
	if (plxmlHttp.readyState==4 || plxmlHttp.readyState=="complete") {
		if(checkAjax(plxmlHttp.responseText).length == 12) {document.getElementById("adminrequestcount").style.borderColor = "#00ff00";}
	}
}

function clearCache() {
	document.getElementById("adminclearcache").style.borderColor = "#ff0000";
	var mpc = document.getElementById("adminmpc").value;
	ccxmlHttp = GetXmlHttpObject();
	ccxmlHttp.onreadystatechange = updateClearCache;
	ccxmlHttp.open("GET", "/ajax/clearcache?p="+mpc, true);		
	ccxmlHttp.send(null);
	return false;
}

function updateClearCache() {
	if (ccxmlHttp.readyState==4 || ccxmlHttp.readyState=="complete") {
		var mpc = checkAjax(ccxmlHttp.responseText);
		if(mpc.length == 5) {document.getElementById("adminclearcache").style.borderColor = "#00ff00";}
	}
}

function clearExpiredCache() {
	cachexmlHttp = GetXmlHttpObject();
	cachexmlHttp.open("GET", "/ajax/expcache", true);		
	cachexmlHttp.send(null);
}

//	Custom Apparel Form
function clearCA() {
	var comments = document.getElementById("cs-bodydata");
	comments.value = comments.value.replace("Enter any questions or comments about your custom apparel requirements.","");

}
function submitCustomApparel() {
	var email=document.getElementById("ca-email");
	var phone=document.getElementById("ca-phone");
	if(email.value.length == 0 && phone.value.length == 0) {
		alert ("Please enter your email or your phone number so that we may contact you.")
		return false;
	}
	if (email.value.length > 0) {
		var re = new RegExp("^[a-zA-Z0-9&\+._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
		if (!email.value.match(re)) {
			email.style.backgroundColor = "#ffff3f";
			alert("The email address is not of a valid form for our software. Please check to make sure it was entered correctly.");
			return false;
		}
	}
	
	var q = "?e="+email.value
		+"&n="+URLEncode(document.getElementById("ca-name").value)
		+"&c="+URLEncode(document.getElementById("ca-company").value)
		+"&p="+URLEncode(document.getElementById("ca-phone").value)
		+"&q="+URLEncode(document.getElementById("ca-qty").value)
		+"&com="+URLEncode(document.getElementById("cs-bodydata").value);
	
	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange = emailResponse;
	xmlHttp.open("GET", "/ajax/customapparel"+q, true);		
	// send the request
	xmlHttp.send(null);
	return false;
}
		
function updateACN(acncookie) {
	setCookie('acn',acncookie,800,"/","",false);
}

function updateECN(ecncookie) {
	setCookie('ecn',ecncookie,800,"/","",false);
}
		
