var cflPreloadedImgs = new Array(), speedIncrease = 0, spinTimer;

if(document.all && !document.getElementById){
	document.getElementById = function(id){
		return document.all[id];
	}
}

// preload function and images
function pixPath(depth){
	preload('bn_arrow', depth + 'images/retail/bn_arrow.gif');
	preload('bn_arrow_roll', depth + 'images/retail/bn_arrow_roll.gif');

	preload('bn_hd_go', depth + 'images/retail/bn_hd_go.gif');
	preload('bn_hd_go_roll', depth + 'images/retail/bn_hd_go_roll.gif');
}

function preload(imgObj, imgSrc){
	cflPreloadedImgs[imgObj] = new Image();
	cflPreloadedImgs[imgObj].src = imgSrc;
}

function toggleDisplay(control){
	var target = MochiKit.DOM.getElement(control), sourceControlString = control + "Toggle", source = MochiKit.DOM.getElement(sourceControlString);
	
	if(target.style.visibility == "hidden"){
		target.style.visibility = "visible";
		target.style.display = "";
		source.innerHTML = "-";
		
		setCookie(control + "Toggle", 1);
	}else{
		target.style.visibility = "hidden";
		target.style.display = "none";
		source.innerHTML = "+";
		
		setCookie(control + "Toggle", 0);
	}
}
function changeDisplay(control, show) {
	var target = MochiKit.DOM.getElement(control);

	if (show == true) {
		target.style.visibility = "visible";
		target.style.display = "";
	} else {
		target.style.visibility = "hidden";
		target.style.display = "none";
	}
}

function changeImageMochikit(imgID, imgObj) {
	MochiKit.DOM.getElement(imgID).src = cflPreloadedImgs[imgObj].src;
}

//source: http://weblogs.asp.net/rajbk/archive/2003/12/11/setting-the-default-button-for-a-textbox-in-asp-net.aspx
//set onkeypress attribute for textbox
//i.e. onkeypress="return clickButton(event,'Button1')"
function clickButton(e, buttonid){
      var evt = e ? e : window.event, bt = MochiKit.DOM.getElement(buttonid);
      if (bt)
      {
          if (evt.keyCode == 13)
          {
                bt.click();
                return false;
          }
      }
}

function doSearch() {
	window.location.href = "/search/results.aspx?txtSearch=" + encodeURIComponent(MochiKit.DOM.getElement('topSearchForm').txtSearch.value);
	return false;
}

function backHistory(){
	window.history.go(-1)
	return false;
}

function mailToFriend(itemid){
	if (!popEmail || popEmail.closed)
	{
		var strUrl = "/products/popupProductMailToFriend.aspx?pid=" + itemid, popEmail = window.open(strUrl, "SendEmail", "width=390,height=550,left=200,top=100,resizable=1");
	}
	popEmail.focus();
	
	return false;
}

function instockNotify(itemid){
	if (!popInstockNotify || popInstockNotify.closed)
	{
		var strUrl = "/products/popupProductInStockNotifyRequest.aspx?pid=" + itemid, popInstockNotify = window.open(strUrl, "InstockRequest", "width=390,height=420,left=200,top=100,resizable=1");
	}
	popInstockNotify.focus();
	
	return false;
}

function popImage(imgSrc){
	if (!popImage || popImage.closed)
	{
		var strUrl = "/products/popImage.asp?img_src=" + imgSrc, popImage = window.open(strUrl, "imageWindow", "width=660,height=545,left=200,top=100,resizable=1");
	}
	popImage.focus();
	
	return false;
}
function popLargeImage(itemID, picid, idtype){
	if (!popLargeImageWin || popLargeImageWin.closed)
	{
		var strUrl = "/products/popupProductLargeImage.aspx?id=" + encodeURIComponent(itemID) + "&picid=" + encodeURIComponent(picid) + "&idt=" + encodeURIComponent(idtype), popLargeImageWin = window.open(strUrl, "imageWindow", "width=660,height=545,left=200,top=100,resizable=1");
	}
	popLargeImageWin.focus();
	
	return false;
}
function openPopup(relativeUrl, windowWidth, windowHeight, windowName){
	if(relativeUrl.charAt(0) == '/' && !isNaN(windowWidth) && !isNaN(windowHeight)){
		var popupWindow = window.open(relativeUrl, windowName, "width=" + windowWidth + ",height=" + windowHeight + ",left=200,top=100,resizable=1");
		popupWindow.focus();
	}
	
	return false;
}

/* Add to Cart functions */
function prepareAddPopupImages(){
	preload('spin_up','/images/retail/spin_up.gif');
	preload('spin_up_roll','/images/retail/spin_up_roll.gif');

	preload('spin_down','/images/retail/spin_down.gif');
	preload('spin_down_roll','/images/retail/spin_down_roll.gif');

	preload('bn_close2','/images/retail/bn_close2.gif');
	preload('bn_close2_roll','/images/retail/bn_close2_roll.gif');

	preload('bn_cancel','/images/retail/bn_cancel.gif');
	preload('bn_cancel_roll','/images/retail/bn_cancel_roll.gif');

	preload('bn_add','/images/retail/bn_add.gif');
	preload('bn_add_roll','/images/retail/bn_add_roll.gif');

	preload('save_changes','/images/retail/bn_save_changes.gif');
	preload('save_changes_roll','/images/retail/bn_save_changes_roll.gif');
}

function initialQuantity(){
	return parseInt(aspNetFrm.initialQuantity.value);
}
function currentQuantity(){
	return parseInt(aspNetFrm.currentQuantity.value);
}
function quantityMultiple(){
	return parseInt(aspNetFrm.quantityMultiple.value);
}
function maxOrder(){
	return parseInt(aspNetFrm.maxOrder.value);
}

function openAddPopup(obj, ItemID, ItemShortDesc, salesMin, salesUM, pieceCount, pieceUM, inv, quantityInCart){
	var layer = MochiKit.DOM.getElement("addPopup"),
	imgPopHeadAdd = MochiKit.DOM.getElement("imgPopHeadAdd"),
	imgPopHeadEdit = MochiKit.DOM.getElement("imgPopHeadEdit"),
	aPopUpdateAdd = MochiKit.DOM.getElement("apop-add"),
	aPopUpdateSave = MochiKit.DOM.getElement("apop-save"),
	productDescriptionCtrl = MochiKit.DOM.getElement("productDescription"),
	pieceCountCtrl = MochiKit.DOM.getElement("pieceCount"),
	salesMinCtrl = MochiKit.DOM.getElement("salesMin"),
	style2,
	errorDiv,
	innerHeight,
	vpDim,
	layerBase,
	anchorPos,
	layerPos,
	popDim,
	halfPopHeight,
	scrollTopPosition,
	newPosition;

	if(layer){
		style2 = layer.style;
		errorDiv = MochiKit.DOM.getElement('popErrors');
		innerHeight = 0;
		vpDim = MochiKit.Style.getViewportDimensions();
		layerBase = layer.parentNode;
		anchorPos = MochiKit.Style.getElementPosition(obj);
		layerPos = MochiKit.Style.getElementPosition(layerBase);
		popDim = MochiKit.Style.getElementDimensions(layer);
		halfPopHeight = popDim.h / 2;
		scrollTopPosition = MochiKit.Style.getViewportPosition();
		newPosition = (anchorPos.y - halfPopHeight) - layerPos.y;
		
		//clear error message
		if(errorDiv){
			errorDiv.innerHTML = "";
			errorDiv.style.display = "none";
		}
		
		//set product description
		productDescriptionCtrl.innerHTML = "<b>" + ItemShortDesc + "</b> is available in <b>Purchase Multiples</b> of <b>" + salesMin + "</b>&#160;" + salesUM + "(s).";
		if(!((salesUM == 'foot' || salesUM == 'pound' || salesUM == 'yard') && salesUM == pieceUM && pieceCount == 1)){
			pieceCountCtrl.innerHTML = "Each&#160;<b>" + salesUM + "</b>&#160;contains <b>" + pieceCount + "</b>&#160;" + pieceUM + ".";
		}else{
			pieceCountCtrl.innerHTML = "";
		}
		salesMinCtrl.innerHTML = "<b>Available in Purchase Multiples</b> of <b>" + salesMin + "</b>.";
		
		//set variable values
		if(isNaN(quantityInCart)){
			aspNetFrm.initialQuantity.value = 0;
		}else{
			aspNetFrm.initialQuantity.value = quantityInCart;
		}
		aspNetFrm.quantityMultiple.value = salesMin;
		aspNetFrm.maxOrder.value = inv;
		aspNetFrm.ItemID.value = ItemID;
		
		setMultiple();
		
		//get header image/save image
		if(isNaN(quantityInCart)){
			imgPopHeadAdd.style.display = "";
			imgPopHeadEdit.style.display = "none";
			
			aPopUpdateAdd.style.display = "";
			aPopUpdateSave.style.display = "none";
		}else{
			imgPopHeadAdd.style.display = "none";
			imgPopHeadEdit.style.display = "";
			
			aPopUpdateAdd.style.display = "none";
			aPopUpdateSave.style.display = "";
		}
		
		//calculate position
		if(document.body.clientHeight){
			innerHeight = document.body.clientHeight;
		}else{
			innerHeight = window.innerHeight;
		}
		
		//check to make sure popup isn't off screen to the bottom
		if(anchorPos.y + halfPopHeight > scrollTopPosition.y + vpDim.h){
			newPosition = scrollTopPosition.y + vpDim.h - popDim.h - layerPos.y;
		} else if (anchorPos.y - halfPopHeight < scrollTopPosition.y) {
			//check to make sure popup isn't off screen to the top
			newPosition = anchorPos.y - layerPos.y;
		} else if (anchorPos.y - halfPopHeight < 190) {
			//check to make sure popup isn't inside dept. nav area. IE has a layer problem where some header nav stays on top of the popup.
			newPosition = 190 - layerPos.y;
		}

		//display add cart layer.
		style2.top = newPosition + "px";
		style2.visibility = "visible";
		
		aspNetFrm.PositionTop.value = newPosition;
	}

	return false;
}
function closeAddPopup(){
	var layer = MochiKit.DOM.getElement("addPopup"), style2 = layer.style, errorDiv = MochiKit.DOM.getElement('popErrors');
	style2.visibility = "hidden";
	
	if(errorDiv){
		errorDiv.innerHTML = "";
		errorDiv.style.display = "none";
	}
	
	return false;
}
function updateQuantity(si, tpd){
	if (typeof si == "undefined")
	{
		si = "";
	}
	if (typeof tpd == "undefined")
	{
		tpd = false;
	}
	var addCartReq, requested, availableNow, errorDiv;
	
	if( currentQuantity().toString() != "NaN" ){
		if (currentQuantity() <= maxOrder()){
			aspNetFrm.pf.value="uc";
			
			addCartReq = null;
			if(tpd){
				//addCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/orders/cartQuantityService.asp",{"ItemID": aspNetFrm.ItemID.value, "Quantity": aspNetFrm.currentQuantity.value, "tpd": "1"});
				addCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/cart/quantityService.aspx",{"ItemID": aspNetFrm.ItemID.value, "Quantity": aspNetFrm.currentQuantity.value, "tpd": "1"});
			}else{
				//addCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/orders/cartQuantityService.asp",{"ItemID": aspNetFrm.ItemID.value, "Quantity": aspNetFrm.currentQuantity.value});
				addCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/cart/quantityService.aspx",{"ItemID": aspNetFrm.ItemID.value, "Quantity": aspNetFrm.currentQuantity.value});
			}
			addCartReq.addCallbacks(addCartSucceed, addCartFail);
		}
		else
		{
			requested = currentQuantity();
			multiple = quantityMultiple();
			maxOrderVar = maxOrder();
			errorDiv = MochiKit.DOM.getElement('popErrors');
			
			if(maxOrderVar>=multiple && maxOrderVar>0){
				availableNow = (Math.floor(maxOrderVar/multiple))*multiple;
				aspNetFrm.currentQuantity.value = availableNow;
				aspNetFrm.txtNumber.value = aspNetFrm.currentQuantity.value;
			}else{
				availableNow = 0;
			}
			
			if(errorDiv){
				errorDiv.innerHTML = "Thanks for requesting "+requested+", however we have "+availableNow+" in stock.  Please adjust your order.";
				errorDiv.style.display = "";
			}
		}
	}
	else
	{	
		errorDiv = MochiKit.DOM.getElement('popErrors');
		if(errorDiv){
			errorDiv.innerHTML = "Sorry, product not available.";
			errorDiv.style.display = "";
		}
	}
	
	return false;
}
function addCartSucceed(result){
	closeAddPopup();
	if(MochiKit.Format.strip(result.responseText) == "True"){
		window.location.href = window.location.href;
	}else{
		aspNetFrm.submit();
	}
}
function addCartFail(result){
	closeAddPopup();
	aspNetFrm.submit();
}



function setMultiple(){
	if (aspNetFrm.initialQuantity.value != "" && initialQuantity()!=0)
	{
		aspNetFrm.currentQuantity.value = initialQuantity();
		aspNetFrm.txtNumber.value = initialQuantity();
	}

	else
	{
		aspNetFrm.currentQuantity.value = quantityMultiple();
		aspNetFrm.txtNumber.value = quantityMultiple();
	}
}
function resetValue(textBox){
	aspNetFrm.txtNumber.value = textBox.value;
}
function increment(textBox){
	textBox.value = parseInt(textBox.value) + quantityMultiple();
	aspNetFrm.txtNumber.value = textBox.value;
}
function decrement(textBox){
	if( parseInt(textBox.value) - quantityMultiple() <= 0 ){
		return false;
	} else {
		textBox.value = parseInt(textBox.value) - quantityMultiple();
		aspNetFrm.txtNumber.value = textBox.value;
		return true;
	}
}
function spinIncrement(textBox){
	increment(textBox);

	//speed up the timer each repitition
	if (speedIncrease < 180)
	{
		speedIncrease = speedIncrease + 20;
	}
	//Set timer for additional increments
	newTextBox = textBox;
	spinTimer = setTimeout('spinIncrement(newTextBox)', 220-speedIncrease);

	return false;
}
function spinDecrement(textBox){
	//decrement
	if (decrement(textBox)==true) //Stops the spinDecrement loop when can't decrement more
	{
		//speed up the timer each repitition
		if (speedIncrease < 180 )
		{
			speedIncrease = speedIncrease + 20;
		}
		//set timer for additional decrement
		newTextBox = textBox;
		spinTimer = setTimeout('spinDecrement(newTextBox)', 220-speedIncrease);
	}
	
	return false;
}
function stopSpin(){
	if(spinTimer){
		clearTimeout(spinTimer);
		speedIncrease = 0;
	}
	
	return false;
}
/* End Add to Cart functions */

/* Manage Cart Item functions */
function manageCartItem(op, itemID){
	aspNetFrm.pf.value=op;
	aspNetFrm.ItemID.value=itemID;
	var manageCartReq = null;
	manageCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/cart/cartService.aspx",{"pf": op, "ItemID": itemID});
	manageCartReq.addCallback(manageCartItemSucceed);
	manageCartReq.addErrback(manageCartItemFail);

	return false;
}
function manageCartItemInstance(op, itemInstance){
	aspNetFrm.pf.value=op;
	aspNetFrm.ItemInstance.value=itemInstance;
	var manageCartReq = null;
	manageCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/cart/cartService.aspx",{"pf": op, "ItemInstance": itemInstance});
	manageCartReq.addCallback(manageCartItemSucceed);
	manageCartReq.addErrback(manageCartItemFail);
	
	return false;
}
function manageCartItemSucceed(result){
	if(strip(result.responseText) == "True"){
		window.location.href = window.location.href;
	}
	else
	{
		aspNetFrm.submit();
	}
}
function manageCartItemFail(result){
	aspNetFrm.submit();
}
/* End Manage Cart Item functions */

/* Manage Cart functions */
function manageCart(op){
	aspNetFrm.pf.value=op;
	var manageCartReq = null;
	manageCartReq = MochiKit.Async.doSimpleXMLHttpRequest("/cart/cartService.aspx",{"pf": op});
	manageCartReq.addCallback(manageCartSucceed);
	manageCartReq.addErrback(manageCartFail);
	
	return false;
}
function removeCartAll(){
	if(confirm("Are you sure you want to empty your cart?")){
		manageCart("ucrall");
	}
	
	return false;
}
function manageCartSucceed(result){
	if(strip(result.responseText) == "True"){
		window.location.href = window.location.href;
	}
	else
	{
		aspNetFrm.submit();
	}
}
function manageCartFail(result){
	aspNetFrm.submit();
}
/* End Manage Cart functions */