// *****************************************
//  NUMBER SCROLLER
// *****************************************

function NumberScroller(intervalSeconds, count, callBack)
{
	// define class members
	this.numberScrollerPosition = 1;
	this.numberScrollerCount = count;
	this.numberScrollerIntervalSeconds = intervalSeconds * 1000;
	this.numberScrollerTimer = null;
	this.numberScrollerBusy = null;
	this.numberScrollerInstance = null;
	
	// user defined callback which will get actions of
	// start,resume,pause,next,previous,autoNext,manual
	this.numberScrollerCallBack = callBack;
	
	// define class methods
	this.startNumberScroller = startNumberScroller;
	this.toggleNumberScrollerPause = toggleNumberScrollerPause;
	this.previousNumberScroller = previousNumberScroller;
	this.nextNumberScroller = nextNumberScroller;
	this.setNumberScroller = setNumberScroller;
	this.pauseNumberScroller = pauseNumberScroller;
	this.autoNextNumberScroller = autoNextNumberScroller;
	this.manualNumberScroller = manualNumberScroller;
	this.resumeNumberScroller = resumeNumberScroller;
	this.restartNumberScroller = restartNumberScroller;
}

function startNumberScroller()
{
	var self = this;
	var func = function()
	{
		self.autoNextNumberScroller();
	}
	this.numberScrollerTimer = setInterval(func, this.numberScrollerIntervalSeconds);
	this.numberScrollerCallBack("start", null, null);
}

function resumeNumberScroller(invokeCallBack)
{
	var self = this;
	var func = function()
	{
		self.autoNextNumberScroller();
	}
	this.numberScrollerTimer = setInterval(func, this.numberScrollerIntervalSeconds);
	
	if(invokeCallBack == undefined || invokeCallBack == null || invokeCallBack === true)
	{
		this.numberScrollerCallBack("resume", null, null);
	}
}

function pauseNumberScroller(invokeCallBack)
{
	if(this.numberScrollerTimer)
	{
		clearInterval(this.numberScrollerTimer);
		this.numberScrollerTimer = null;
		
		if(invokeCallBack == undefined || invokeCallBack == null || invokeCallBack === true)
		{
			this.numberScrollerCallBack("pause", null, null);
		}
	}
}

function restartNumberScroller()
{
	if(this.numberScrollerTimer != null)
	{
		this.pauseNumberScroller(false);
		this.resumeNumberScroller(false);
	}
}

function previousNumberScroller()
{
	this.setNumberScroller(this.numberScrollerPosition - 1, "previous");
	this.restartNumberScroller();
}

function nextNumberScroller()
{
	this.setNumberScroller(this.numberScrollerPosition + 1, "next");
	this.restartNumberScroller();
}

function autoNextNumberScroller()
{
	this.setNumberScroller(this.numberScrollerPosition + 1, "autoNext");
}

function toggleNumberScrollerPause()
{
	if(this.numberScrollerTimer)
	{
		this.pauseNumberScroller();
	}
	else
	{
		this.resumeNumberScroller();
	}
}

function manualNumberScroller(newPosition)
{
	this.setNumberScroller(newPosition, "manual");
	this.restartNumberScroller();
}

function setNumberScroller(newPosition, action)
{
	if(this.numberScrollerBusy || newPosition == this.numberScrollerPosition)
	{
		return;
	}
	this.numberScrollerBusy = true;
	
	if(newPosition > this.numberScrollerCount)
	{
		newPosition = 1;
	} 
	else if(newPosition < 1)
	{
		newPosition = this.numberScrollerCount;
	}
	
	var previousPosition = this.numberScrollerPosition;
	this.numberScrollerPosition = newPosition;
	this.numberScrollerCallBack(action, previousPosition, newPosition);
	this.numberScrollerBusy = false;
}

function preloadImages()
{
	var i;
	for(i=0; i<imageScrollCount; i++)
	{
		var preloadedImage = new Image();
		preloadedImage.src = imageScrollPaths[i];
	}
}

// *****************************************
//  DROPDOWN MENUS
// *****************************************

var currentDropDownMenu = null;
var hideDropDownMenuTimer = null;
var menuEffect = null;
function showDropDownMenu(elem)
{
	if(currentDropDownMenu == elem)
	{
		// this menu is already opened
		if(hideDropDownMenuTimer)
		{
			clearTimeout(hideDropDownMenuTimer);
			hideDropDownMenuTimer = null;
		}
		
		return;
	}
	else if(currentDropDownMenu != null)
	{
		if(menuEffect)
		{
			menuEffect.cancel();
		}
		
		// hide the old menu
		hideMenu(currentDropDownMenu);
	}
	
	currentDropDownMenu = elem;

	menuEffect = new Effect.Appear(currentDropDownMenu, 
			{ 
				duration: 0.15,
				delay: 0.0,
				transition: Effect.Transitions.sinoidal
			});
	//document.getElementById(currentDropDownMenu).style.display = "";
}

function delayHideMenu(elem)
{
	if(hideDropDownMenuTimer)
	{
		return;
	}
	
	var func = "hideMenu('" + elem + "')";
	hideDropDownMenuTimer = setTimeout(func, 100);
}

function hideMenu(elem)
{
	if(hideDropDownMenuTimer)
	{
		clearTimeout(hideDropDownMenuTimer);
	}
	
	var elemToClose = document.getElementById(elem);
	if(elemToClose)
	{
		elemToClose.style.display = "none";
		currentDropDownMenu = null;
	}
	
	
	hideDropDownMenuTimer = null;
}

function createProductList()
{
  $('createProductListForm').request(
  {
    onSuccess: function(transport)
    { 				   
      var html = transport.responseText;

      if(html.indexOf('pcs-popup-messages') < 0)
      {
        hideBBox();
        document.getElementById('productListsSection').innerHTML = html;
      }
      else
      {
        $('popupMessages').innerHTML = html;
        $('popupMessagesSection').show();
      }
    }
  });
  return false;
}

function editProductList()
{
  $('editProductListForm').request(
  {
    onSuccess: function(transport)
    { 				   
      var html = transport.responseText;

      if(html.indexOf('pcs-popup-messages') < 0)
      {
        hideBBox();
        document.getElementById('productListsSection').innerHTML = html;
      }
      else
      {
        $('popupMessages').innerHTML = html;
        $('popupMessagesSection').show();
      }
    }
  });
  return false;
}

function deleteProductLists()
{
	var elems = document.getElementsByName("listKey");
	for(var i=0; i<elems.length; i++)
	{
		if(elems[i].checked)
		{
			// at least one was selected
			showBBoxStatic('Confirmation', 'deleteShoppingListConfirmation');
			return false;
		}
	}
	
	// nothing was selected so display a message
	showBBoxMessage('Delete Selected Lists', 'Please select at least one list', {'width':325});
	return false;
}

function doDeleteProductLists()
{
	document.getElementById('productListForm').action = "/account/deleteProductLists";

	$('productListForm').request(
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			document.getElementById('productListsSection').innerHTML = html;
		}
	});

	hideBBox();
}

function combineProductLists()
{
	var elems = document.getElementsByName("listKey");
	var numSelected = 0;
	for(var i=0; i<elems.length; i++)
	{
		if(elems[i].checked)
		{
			numSelected++;
			if (numSelected >=2)
			{
				// at least two are selected
				document.getElementById('productListForm').action = "/account/combineShoppingLists";
				$('productListForm').request(
				{
					onSuccess: function(transport)
					{
						var html = transport.responseText;
						showBBoxText('Combine Lists', html);
					}
				});
			}
		}
	}

	// nothing was selected so display a message
	showBBoxMessage('Combine Selected Lists', 'Please select at least two lists', {'width':325});
}

function doCombineProductLists()
{
  $('combineProductListsForm').request(
  {
    onSuccess: function(transport)
    { 				   
      var html = transport.responseText;

      if(html.indexOf('pcs-popup-messages') < 0)
      {
        hideBBox();
        document.getElementById('productListsSection').innerHTML = html;
      }
      else
      {
        $('popupMessages').innerHTML = html;
        $('popupMessagesSection').show();
      }
    }
  });
  return false;
}

function addToProductListPopup(itemKey)
{
  new Ajax.Updater('', '/account/addToList?itemKey=' + itemKey,
  {
    onSuccess: function(transport)
    {
      var html = transport.responseText;
      if(html && (html.indexOf('pcs-login-page') < 0))
      {
        showBBoxText('Add To Shopping List', html);
      }
      else
      {
        var form = document.createElement("form");
        document.body.appendChild(form);
        form.method = "post";
        form.action = '/account/promptLogin';
        var redirectField = document.createElement("input");
        redirectField.setAttribute("type", "hidden");
        redirectField.setAttribute("name", "redirectUrl");
        redirectField.setAttribute("value", location.href);
        form.appendChild(redirectField);
        form.submit();
      }
    }
  });
}

function addProductToList(newList)
{
  var formId;

  if (newList != 'true') {
	  formId = 'addToProductListForm';
  } else {
	  formId = 'addToNewProductListForm';
  }

  $(formId).request(
  {
    onSuccess: function(transport)
    { 				   
      var html = transport.responseText;
      if(html.indexOf('pcs-popup-messages') < 0)
      {
    	  $('bboxContents').innerHTML = html;
      }
      else
      {
        $('popupMessages').innerHTML = html;
        $('popupMessagesSection').show();
      }
    }
  });
	 
  return false;
}

function addToNewProductList()
{
  $('addToNewProductListForm').request(
  {
    onSuccess: function(transport)
    { 				   
      var html = transport.responseText;

      if(html.indexOf('pcs-popup-messages') < 0)
      {
        hideBBox();
        eval("var jsonResult = " + html);
        window.location.href = '/account/viewList/listKey/' + jsonResult.listKey;
      }
      else
      {
        $('popupMessages').innerHTML = html;
        $('popupMessagesSection').show();
      }
    }
  });
  return false;
}

function catalogLogin()
{
  var form = document.createElement("form");
  document.body.appendChild(form);
  form.method = "post";
  form.action = '/account/promptLogin';
  var redirectField = document.createElement("input");
  redirectField.setAttribute("type", "hidden");
  redirectField.setAttribute("name", "redirectUrl");
  redirectField.setAttribute("value", "/account/catalogRequest");
  form.appendChild(redirectField);
  form.submit();
}

//This method will automatically move the cursor to the next
//input field in the phone number
//the srcElem is the name of the field the cursor is currently on
//the destElem is the name of the element the cursor will be move to
//when the value in srcElem has a length of numberDigits, the cursor
//will be moved to destElem.
function phoneMover(srcElem, destElem, numberDigits)
{
	if(document.getElementById(srcElem).value.length >= numberDigits)
	{
		document.getElementById(destElem).focus();
	}
}

//address forms will be different depending on the country selected
function onAddressCountryChange(countryKey, prefix, skipZipAutoFill)
{
	setAddressLabels(countryKey, prefix);
	
	if(countryKey <= 1)
	{
		// show zip+4
		document.getElementById(prefix + "zip_suffix_div").style.display = "";
		document.getElementById(prefix + "zip").style.width = null;
		document.getElementById(prefix + "zip").size = 15;
	}
	else
	{
		// hide zip+4
		document.getElementById(prefix + "zip_suffix_div").style.display = "none";
		document.getElementById(prefix + "zip").style.width = document.getElementById(prefix + "street1").style.width;
	}
	
	if(countryKey <= 3)
	{
		// switching from a foreign to domestic address form
		document.getElementById(prefix + "foreignCityRow").style.display = "none";
		document.getElementById(prefix + "foreignStateRow").style.display = "none";
		document.getElementById(prefix + "domesticCityRow").style.display = "";
		document.getElementById(prefix + "domesticStateRow").style.display = "";
		
		var zipRow = document.getElementById(prefix + "zipRow");
		if(zipRow)
		{
			zipRow.style.backgroundColor = "#EEEEEE";
		}
		
		document.getElementById(prefix + "zipOld").value = "";
		
		if(!skipZipAutoFill || skipZipAutoFill !== true)
		{
			onAddressZipChange(document.getElementById(prefix + "zip").value, prefix);
		}
	}
	else
	{
		// switching from a domestic to foreign address form
		hideZipErrorIcon(prefix);

		var zipRow = document.getElementById(prefix + "zipRow");
		if(zipRow)
		{
			zipRow.style.backgroundColor = "#FFFFFF";
		}
		
		document.getElementById(prefix + "domesticCityRow").style.display = "none";
		document.getElementById(prefix + "domesticStateRow").style.display = "none";
		document.getElementById(prefix + "foreignCityRow").style.display = "";
		document.getElementById(prefix + "foreignStateRow").style.display = "";
	}
}

//changes the zip and state labels for domestic addresses
//the zip label text must be wrapped in a block with id <prefix>zipLabel
//the state label text must be wrapped in a block with id <prefix>stateLabel
function setAddressLabels(countryKey, prefix)
{
	switch(parseInt(countryKey))
	{
		case 1:
		  document.getElementById(prefix + "zipLabel").innerHTML = "Zip";
		  document.getElementById(prefix + "stateLabel").innerHTML = "State";
		  break;    
		case 2:
		  document.getElementById(prefix + "zipLabel").innerHTML = "Postal Code";
		  document.getElementById(prefix + "stateLabel").innerHTML = "Province\\Territory";
		  break;
		case 3:
		  document.getElementById(prefix + "zipLabel").innerHTML = "Postal Code";
		  document.getElementById(prefix + "stateLabel").innerHTML = "Province";
		  break;
		default:
		  document.getElementById(prefix + "zipLabel").innerHTML = "Postal Code";
		  break;
	}
}

//clears the fields involved in autofilling based on zip
function clearAddressAutoFill(prefix)
{
	// set the state name
	document.getElementById(prefix + "domesticState").value = "";

	var citySelect = document.getElementById(prefix + "domesticCity");
	for(var count = citySelect.options.length - 1; count >= 0; count--)
 {
     citySelect.options[count] = null;
 }
}

//autofills the state and city based on the country and zip
//if the zip is invalid, then an error icon will display
function onAddressZipChange(zip, prefix)
{
	var countryKey = document.getElementById(prefix + "country").value;
	if(countryKey > 3)
	{
		clearAddressAutoFill(prefix);
		copyBillingAddressToShippingAddress();
		return;
	}
	
	var zipOld = document.getElementById(prefix + "zipOld");
	if(zip == zipOld.value)
	{
		// there was no change in the zip
		return;
	}
	zipOld.value = zip;

	if(zip.strip() == "")
	{
		hideZipErrorIcon(prefix);
		clearAddressAutoFill(prefix);
		copyBillingAddressToShippingAddress();
		return;
	}
	
	new Ajax.Updater('', '/addressAutoFill',
	{
		parameters:
		{
			'postal':zip,
			'countryKey':countryKey
		},
		onSuccess: function(transport)
		{
			processAutoFillResponse(transport.responseText, prefix);
			
			// this is for the checkout with billing\shipping forms
			copyBillingAddressToShippingAddress();
		}
	});
}

//processes the response from onAddressZipChange
//this will either show an error icon or fill in the address values
function processAutoFillResponse(html, prefix)
{
	if(html.indexOf('pcs-error-messages') < 0)
	{
		// there were no errors
		eval("var jsonResult = " + html);

		hideZipErrorIcon(prefix);

		// set the state name
		document.getElementById(prefix + "domesticState").value = jsonResult.state;

		// remove the options already in the city select box
		var citySelect = document.getElementById(prefix + "domesticCity");
		for(var count = citySelect.options.length - 1; count >= 0; count--)
	    {
	        citySelect.options[count] = null;
	    }
		
	    // add the cities to the city select box with keys as postal keys and values as the city name
		var cities = jsonResult.cities;
		var postalKeys = jsonResult.postalKeys;
		for(var i=0; i<cities.length; i++)
		{
			// create the option in the city options
			var newOption = new Option(cities[i],postalKeys[i]);
			citySelect.options[i] = newOption;
		}

		// select the default city which is the first one in the list
		citySelect.selectedIndex = 0;
	}
	else 
	{
		showZipErrorIcon(prefix);
		clearAddressAutoFill(prefix);
	}
}

//when entering an address and the zip code is invalid for
//domestic addresses, an error icon will appear and the
//input box will have a red border
function showZipErrorIcon(prefix)
{
	var zipErrorIcon = document.getElementById(prefix + "zipErrorIcon");
	var zipElem = document.getElementById(prefix + "zip");
	if(zipErrorIcon && zipElem)
	{
		Effect.Appear(zipErrorIcon, { duration: 0.3 });
		zipElem.style.borderColor = "#FF0000";
		zipElem.style.borderWidth = "2px";
		zipElem.style.borderStyle = "solid";
	}
}

//this method removes the effect that occurs when the zip
//is wrong for domestic address forms. See showZipErrorIcon() above.
function hideZipErrorIcon(prefix)
{
	var zipErrorIcon = document.getElementById(prefix + "zipErrorIcon");
	var zipElem = document.getElementById(prefix + "zip");
	if(zipErrorIcon && zipElem)
	{
		Effect.Fade(zipErrorIcon, { duration: 0.3 });
		zipElem.style.borderColor = "";
		zipElem.style.borderWidth = "";
		zipElem.style.borderStyle = "";
	}
}

function copyFieldValue(src, dest)
{
	var srcElem = document.getElementById(src);
	var destElem = document.getElementById(dest);
	
	if(srcElem && destElem)
	{
		destElem.value = srcElem.value;
	}
}

function copyRadioFieldValue(srcName, destId)
{
	var srcElems = document.getElementsByName(srcName);
	if(!srcElems)
		return;
		
	var destElem = document.getElementById(destId);
	if(!destElem)
		return;
	
	for(var i=0; i<srcElems.length; i++)
	{
		if(srcElems[i].checked)
		{
			destElem.value = srcElems[i].value;
			return;
		}
	}
}

//the timer used to delay the hiding
var floatingCartTimer = null;

// displays the floating cart
// the id of the div should be floatingCart
function showFloatingCart()
{
	if(floatingCartTimer != null)
	{
		clearTimeout(floatingCartTimer);
		floatingCartTimer = null;
	}
	
	var floatingCart = document.getElementById("floatingCart");
	if(floatingCart.style.display != "none")
	{
		// the cart is already being shown
		return;
	}

	// the cart is not being shown so display it
	Effect.Appear('floatingCart', { duration: 0.25 });
}

// keeps the cart open
function keepFloatingCart()
{
	if(floatingCartTimer != null)
	{
		clearTimeout(floatingCartTimer);
		floatingCartTimer = null;
	}
}

// creates a timer to close the floating cart
// after a configurable amount of time elapses
function delayHideFloatingCart()
{
	if(floatingCartTimer == null)
	{
		floatingCartTimer = setTimeout(hideFloatingCart, 100);
	}
}

// hides the floating cart without delay
function hideFloatingCart()
{
	
	if(floatingCartTimer)
	{
		clearTimeout(floatingCartTimer);
		floatingCartTimer = null;
	}
	
	Effect.Fade('floatingCart', { duration: 0.15 });
}

function hideFloatingCartQuick()
{
	if(floatingCartTimer)
	{
		clearTimeout(floatingCartTimer);
		floatingCartTimer = null;
	}
	
	var floatingElem = document.getElementById("floatingCart");
	if(floatingElem)
	{
		floatingElem.style.display = "none";
	}
}

function updateFloatingCart()
{
	document.getElementById("floatingCartForm").action = "/updateFloatingCart";
	
	$('floatingCartForm').request(
	{
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
	   			
				document.getElementById('floatingCartHeader').innerHTML = jsonResult.floatingCartHeader;
	   			document.getElementById('floatingCart').innerHTML = jsonResult.floatingCartBody;
	   			
	   			// see if we are on the shopping cart page
	   			// if we are, we need to replace
	   			var pageContentsElem = document.getElementById("tilesContent");
	   			var shoppingCartPageElem = document.getElementById("shoppingCartPage");
	   			if(pageContentsElem && shoppingCartPageElem)
	   			{
	   				// we are on the shopping cart page
	   				pageContentsElem.innerHTML = jsonResult.shoppingCart;
	   			}
	   		}
		}
	});
}

// the floating cart might have a checkout button which will go
// to the view cart page.  If this button is selected, the
// quantities should be updated with what is in the floating cart.
// This method will make sure the action is correct since it is
// changed by updateFloatingCart.
function checkoutFloatingCart()
{
	document.getElementById("floatingCartForm").action = "/checkoutFloatingCart";
}

function removeFromFloatingCart(id)
{
	new Ajax.Updater('', '/removeFromFloatingCart', 
	{
		parameters: 
		{ 
			'i': id
		},
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
	   			
				document.getElementById('floatingCartHeader').innerHTML = jsonResult.floatingCartHeader;
	   			document.getElementById('floatingCart').innerHTML = jsonResult.floatingCartBody;
	   			
	   			// see if we are on the shopping cart page
	   			// if we are, we need to replace
	   			var pageContentsElem = document.getElementById("tilesContent");
	   			var shoppingCartPageElem = document.getElementById("shoppingCartPage");
	   			if(pageContentsElem && shoppingCartPageElem)
	   			{
	   				// we are on the shopping cart page
	   				pageContentsElem.innerHTML = jsonResult.shoppingCart;
	   			}
	   		}
		}
	});
}

var bboxMinWidth = 400;
var viewportWidth;
var viewportHeight;

// this is a global variable that points to a function that will be called
// when the user clicks the close button on the upper right of the popup.
// If this function returns false, the popup will remain opened
var onPopupCloseHandler = null;

// displays the contents in the popup box without doing any AJAX requests
function showBBoxText(title, contents, params)
{
	displayBBox(title, contents, params);
}

function showBBoxMessage(title, message, params)
{
	var contents = "<table border=\"0\" width=\"100%\" align=\"center\" cellpadding=\"6\" cellspacing=\"0\" style=\"background-color:#FFFFFF\"><tr><td align=\"center\" style=\"padding:15px 20px 0px;\"><div style=\"text-align:left;\">" + message + "</div></td></tr><tr><td align=\"center\" style=\"padding:10px;\"><a href=\"javascript:hideBBox();\"><img src=\"/site/img/btn_ok.gif\" alt=\"Cancel\" border=\"0\"/></a></td></tr></table>";
    displayBBox(title, contents, params);
}	

// displays the innerHTML of contentsDiv in the popup box without doing any AJAX requests
function showBBoxStatic(title, contentsDiv, params)
{
      var contents = document.getElementById(contentsDiv).innerHTML;
      displayBBox(title, contents, params);
}

// Calls the URL and displays the resulting HTML into the popup box
function showBBox(title, url, params)
{
      new Ajax.Updater('', url,
      {
            onSuccess: function(transport)
            {
                  var html = transport.responseText;
                  displayBBox(title, html, params);
            }
      });
}

function displayBBox(title, contents, params)
{
	  hideFloatingCartQuick();
	  ieHideSelect(true);
      showBackgroundFade();
      Event.observe(window, 'resize', onWindowResize);
      //Event.observe(window, 'scroll', onWindowResize);
      var bbox = document.getElementById('bbox');
      
      var bboxHeader = document.getElementById('bbox_header');
      if(params && params['hideHeader'])
      {
    	  bboxHeader.style.display = "none";
      }
      else
      {
    	 bboxHeader.style.display = "";
      }
      
      resetWidths();
      
      document.getElementById('bboxTitle').innerHTML = title;
      document.getElementById('bboxContents').innerHTML = contents;  

      bbox.style.left = "-5000px";
      bbox.style.display = "";

      var width = parseInt($('bbox').getStyle('width'));
      var height = parseInt($('bbox').getStyle('height'));

      var minWidth = (params)?params['minWidth']:null;
      if(!minWidth || minWidth <= 0)
      {
    	  minWidth = bboxMinWidth;
      }
      
      // set minimum width
      var boxWidth = (params)?params['width']:null;
      if((boxWidth != null) && (boxWidth != undefined) && (boxWidth != ''))
      {
            width = boxWidth;
            bbox.style.width = boxWidth + "px";
            document.getElementById('bboxTable').style.width = boxWidth + "px";
      }
      else if(width < minWidth)
      {
            width = minWidth;
            bbox.style.width = minWidth + "px";
            document.getElementById('bboxTable').style.width = minWidth + "px";
      }

      var y = parseInt(getOffset("y"));

      setViewportSize();
      var top = parseInt((viewportHeight / 2) - (height / 2));
      var left = parseInt((viewportWidth / 2) - (width / 2));

	  if(top < 0) {
      	top = 0;
	  }
      	
      bbox.style.top = (top + y) + "px";
      bbox.style.left = left + "px"; 

      new Draggable('bbox', 
      {
      	scroll:window,
      	handle: 'bbox_header',
      	revert: false,
      	starteffect: null,
      	endeffect: null
      	
      });

      contents.evalScripts();
}

// invoked when the user clicks the close button in the upper right of the popup
// the onPopupCloseHandler will be invoked before the popup is closed
// NOTE: this should not be called from any other code
function hideBBoxClose()
{
	if(onPopupCloseHandler)
	{
		var closePopup = onPopupCloseHandler();
		if(!closePopup)
		{
			// the handler chose not to close the popup
			return;
		}
	}
	
	hideBBox();
}

function resetWidths()
{
	document.getElementById('bbox').style.width = null;
    document.getElementById('bboxTable').style.width = null;
    document.getElementById('bboxContents').style.width = null;
}

// closes the popup box
function hideBBox()
{
	  Event.stopObserving(window, 'resize', onWindowResize);
	  //Event.stopObserving(window, 'scroll', onWindowResize);
	  onPopupCloseHandler = null;
      
	  document.getElementById('bbox').style.display = "none";
      document.getElementById('fadeBg').style.display = "none";
      document.getElementById('bboxTitle').innerHTML = "";
      document.getElementById('bboxContents').innerHTML = "";
      resetWidths();
      ieHideSelect(false); 
}

function centerBBox(popupElement)
{
	if(!popupElement)
	{
		popupElement = "bbox";
	}
	
	  var bbox = document.getElementById(popupElement);
	  var width = parseInt($(popupElement).getStyle('width'));
	  var height = parseInt($(popupElement).getStyle('height'));
	  var y = parseInt(getOffset("y"));
	
	  setViewportSize();
	  var top = parseInt((viewportHeight / 2) - (height / 2));
	  var left = parseInt((viewportWidth / 2) - (width / 2));
	
	  if(top < 0)
	  	top = 0;
	  	
	  bbox.style.top = (top + y) + "px";
	  bbox.style.left = left + "px"; 
}

function onWindowResize()
{
	var elem = document.getElementById("fadeBg");
	if(!elem || elem.style.display == "none")
		return;
	showBackgroundFade();
	centerBBox();
}

function showBackgroundFade()
{
	var height = document.documentElement.scrollHeight + 'px';
	var width = document.documentElement.scrollWidth + 'px';
	$('fadeBg').setStyle({opacity: 0.6, 'width': width, 'height': height});
	$('fadeBg').show();
}

function setViewportSize()
{
      if (typeof window.innerWidth != 'undefined')
      {
            // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    		viewportWidth = window.innerWidth;
    		viewportHeight = window.innerHeight;
      }
      else if (typeof document.documentElement != 'undefined' &&
                   typeof document.documentElement.clientWidth != 'undefined' &&
                   document.documentElement.clientWidth != 0)
      {
            // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    		viewportWidth = document.documentElement.clientWidth;
    		viewportHeight = document.documentElement.clientHeight;
      }
      else
      {
            // older versions of IE
    		viewportWidth = document.getElementsByTagName('body')[0].clientWidth;
    		viewportHeight = document.getElementsByTagName('body')[0].clientHeight;
      }
}

function ieHideSelect(state){
	if(isInternetExplorer6() == true) {
		var selectTags = document.getElementsByTagName("SELECT");
		for(var i=0; i<selectTags.length; i++){
			if(state){
				selectTags[i].style.display = "none";
			}else{
				selectTags[i].style.display = "block";
			}
		}
	}
}

function isInternetExplorer6() {
	var appVer = navigator.appVersion;
	var version = parseFloat(appVer.split("MSIE")[1]);
	appVer = appVer.split(';');
	if ((String(appVer[1]).indexOf('MSIE') > -1) && (version <= 6)) {
		return true;
	}
	
	return false;
}

function getOffset(which) {
	//********************************************************//
	//*********** FIND TOP POSITION OF SCROLLED AREA *********//
	//********************************************************//
	var x,y;
	// all except Explorer
	if (self.pageYOffset){ 
		x = self.pageXOffset;
		y = self.pageYOffset;
	}
	// Explorer 6 Strict
	else if (document.documentElement && document.documentElement.scrollTop){
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body){ 
	// all other Explorers
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	if(which == "y"){
		return y;
	}else{
		return x
	}
}

//multi-dimensional array that stores:
//[0] - id of group
//[1] - currently selected tab in group (false if first tab should be selected)
//[2] - list of tabs in group
//[3] - true if hover changes tab, false if click changes tab
//[4] - true if hover highlights tab, false otherwise
var tabGroups = [];

function addTabGroup(tabsId, selectedTab){
addTabGroup(tabsId, selectedTab, false, false);
}

function addTabGroup(tabsId, selectedTab, hover){
addTabGroup(tabsId, selectedTab, hover, false);
}

function addTabGroup(tabsId, selectedTab, hover, highlight){
var tabGroup = [tabsId, selectedTab, [], hover, highlight];
tabGroups.push(tabGroup);
}

function getTabGroup(tabId){
for (group=0;group<tabGroups.length;group++){
 for (tab=0;tab<tabGroups[group][2].length;tab++){
   if (tabGroups[group][2][tab] == tabId) {
     return tabGroups[group];
   }
 }
}
}

function productInfoData(type,id){
if(id && id != 'ExpandAll_Data'){
 tab_Data_Obj = document.getElementById(id);
 if(tab_Data_Obj != null){
   if(type == "hide"){
     tab_Data_Obj.style.display = 'none';
   }
   if(type == "show"){
     tab_Data_Obj.style.display = 'block';
   }
 }
}
}

function showAllDataTabs(tabsId){
var productTabs = document.getElementById(tabsId);
if(productTabs){
 var tabs = productTabs.getElementsByTagName("TR");
 if(tabs){
   for(i=0;i<tabs.length;i++){
     if(tabs[i].id && tabs[i].id != 'ExpandAll'){
       var id = tabs[i].id;
       productInfoData('show',id+"_Data");
     }
   }
 }
}
}

function changeTab(tabGroup, type , id){
if(id){
 var innerTab = document.getElementById(id);
 var img = innerTab.getElementsByTagName("IMG");
 var td = innerTab.getElementsByTagName("TD");
 if(type == "reset" ){
   productInfoData("hide",id+"_Data");
 }
 if(type == "click" ){
   productInfoData("show",id+"_Data");
 }
 if(img){
   for(x=0;x<img.length;x++){
     if(type == "in" || type == "click" ){
       var imgSrc = img[x].src;
       var newImgSrc = imgSrc.replace("_inactive_","_active_");
       img[x].src = newImgSrc;
     }
     if(type == "out"){
       if(tabGroup[1] != id){
         var imgSrc = img[x].src;
         var newImgSrc = imgSrc.replace("_active_","_inactive_");
         img[x].src = newImgSrc;
       }
     }
     if(type == "reset"){
       var imgSrc = img[x].src;
       var newImgSrc = imgSrc.replace("_active_","_inactive_");
       img[x].src = newImgSrc;
       productInfoData("hide",id+"_Data");
     }
   }
 }
 if(td){
   for(k=0;k<td.length;k++){
     if(td[k].id){
       if(type == "in" || type == "click" ){
         var inId = td[k].id;
          td[k].id = inId.replace("_inactive","_active");

       }
       if(type == "out"){
          td[k].id = inId.replace("_active","_inactive");
       }
       if(type == "reset"){
         var inId = td[k].id;
          td[k].id = inId.replace("_active","_inactive");
       }
     }       
   }
 }
}
}

function resetTabs(tabGroup){
var tabsDiv = document.getElementById(tabGroup[0]);
if(tabsDiv){
 var tabs = tabsDiv.getElementsByTagName("TR");
 if(tabs){
   for(i=0;i<tabs.length;i++){
     if(tabs[i].id){
       var id = tabs[i].id;
       if(!tabGroup[1]){
         tabGroup[1] = getIdFirstTab(tabs);
       }
       if(id != tabGroup[1]){
         changeTab(tabGroup, "reset" , id);
       } else {
         changeTab(tabGroup, "click" , id);
       }
     }
   }
 }
}
}

function getIdFirstTab(tabs){
for(i=0;i<tabs.length;i++){
 var id = tabs[i].id;
 if ((id != null) && (id != '')) {
   return id;
 }
}
}

function selectTab(tabId, hash){
var tabGroup = getTabGroup(tabId);
tabGroup[1] = tabId;
changeTab(tabGroup, 'click' , tabId);
resetTabs(tabGroup);
if (hash) {
 window.location.hash = hash;
} else {
 window.location.hash = "tabs";
}
}

function initalizeTabs(){
for (group=0;group<tabGroups.length;group++){
 var tabGroup = tabGroups[group];
 var tabsId = tabGroup[0];

 resetTabs(tabGroup);
 var tabsDiv = document.getElementById(tabsId);
 if(tabsDiv){
   var tabs = tabsDiv.getElementsByTagName("TR");

   if(tabs.length > 3){
     productInfoData("show","ExpandAllDiv");
   }

   if(tabs){
     for(i=0;i<tabs.length;i++){
       if(tabs[i].id){
         tabGroup[2].push(tabs[i].id);
         tabs[i].style.cursor ="pointer";
         //******* ONCLICK EVENT ********//
         tabs[i].onclick=function(){
           var id = this.id;
           var currentGroup = getTabGroup(id);
           currentGroup[1] = id;
           changeTab(currentGroup, "click" , currentGroup[1]);
           resetTabs(currentGroup);
           if(tabGroup[1] == 'ExpandAll'){
             showAllDataTabs(currentGroup[0]);
           }   
         }
         //******* MOUSEOVER EVENT ********//
         if (tabGroup[3]) {
           tabs[i].onmouseover = tabs[i].onclick;
         } else if (tabGroup[4]) {
           tabs[i].onmouseover=function(){
             var id = this.id;
             var currentGroup = getTabGroup(id);
             changeTab(currentGroup, "in" , id);
           }
         }
         //******* MOUSEOUT EVENT ********//
         if (tabGroup[4]) {
           tabs[i].onmouseout=function(){
             var id = this.id;
             var currentGroup = getTabGroup(id);
             changeTab(currentGroup, "out" , id);
           }
         }
       }
     }
   }
 }
}
}

function emailCart()
{
	$('emailCartFormId').request(
	{
		onSuccess: function(transport)
		   { 
		   		var html = transport.responseText;
		   		if(html.indexOf('pcs-error-messages') < 0)
		   		{
		   			// the email was sent
		   			showBBoxText("Email Shopping Cart", html, {'width':500});
		   		}
		   		else
		   		{
		   			// errors occurred while sending the email
		   			$('emailCartErrors').innerHTML = html;
		   			$('emailCartErrorsSection').show();
		   		}
		   }
	});
	
	return false;
}

function saveCart()
{
	$('saveCartFormId').request(
	{
		onSuccess: function(transport)
		   { 
		   
		   		var html = transport.responseText;
		   		if(html.indexOf('pcs-error-messages') < 0)
		   		{
		   			// the save was successful so redirect to the view cart page
		   			window.location = "/viewCart";
		   		}
		   		else
		   		{
		   			// error occurred during the save
		   			$('saveCartErrors').innerHTML = html;
		   			$('saveCartErrorsSection').show();
				}
		   }
	});
	
	return false;
}

function calculateShippingFromCart()
{
	$('shipCalcCartForm').request(
	{
		onSuccess: function(transport)
		   { 
		   		var html = transport.responseText;
		   		if(html.indexOf('pcs-error-messages') < 0)
		   		{
		   			// calculation was successful
		   			eval("var jsonResult = " + html);
		   			
		   			//$('calcShippingErrorsSection').hide();
			   		//$('shippingCalcResultText').innerHTML = jsonResult.shippingText;
			   		//document.getElementById("shippingCalcResult").style.display = "";
			   		
		   			var shippingCostZipSection = document.getElementById("shippingCostZipSection");
		   			var shippingCostZip = document.getElementById("shippingCostZip");
		   			var zipToDisplay = jsonResult.zip;
		   			if(shippingCostZipSection && shippingCostZip && zipToDisplay != "")
		   			{
		   				shippingCostZip.innerHTML = jsonResult.zip;
		   				shippingCostZipSection.style.display = "";
		   			}
		   			
			   		var shippingOnCartPage = document.getElementById("shippingOnCartPage");
			   		if(shippingOnCartPage)
			   		{
			   			shippingOnCartPage.innerHTML = jsonResult.shippingText;
			   		}
			   		
			   		var totalOnCartPage = document.getElementById("totalOnCartPage");
			   		if(totalOnCartPage)
			   		{
			   			totalOnCartPage.innerHTML = jsonResult.cartTotal;
			   		}
			   		
			   		if(jsonResult.showQuoteAlert)
			   		{
			   			showBBoxStatic('Call For A Quote', 'shippingQuoteNotification');
			   		}
			   		else
			   		{
			   			hideBBox();
			   		}
		   		}
		   		else
		   		{
		   			// error
		   			$('shippingCalcResult').hide();
		   			$('calcShippingErrors').innerHTML = html;
		   			$('calcShippingErrorsSection').show();
		   		}
		   }
	});
	
	return false;
}

var applyingCartPromotion = false;
function applyCartDiscount()
{
	if(applyingCartPromotion)
	{
		return false;
	}
	applyingCartPromotion = true;
	
	var discountCode = document.getElementById("discountCode").value;
	if(!discountCode || discountCode == null || discountCode == undefined || discountCode == '' || discountCode == 'key code')
	{
		applyingCartPromotion = false;
		return false;
	}
			
	$('applyCartDiscountForm').request(	
	{
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			
   			// success
   			eval("var jsonResult = " + html);
			
			if(jsonResult.promoResult)
			{
				// the discount was applied
				document.getElementById("tilesContent").innerHTML = jsonResult.cart;
				document.getElementById("cartApplyDiscountMsgDiv").innerHTML = jsonResult.promoResultText;
				document.getElementById("cartApplyDiscountMsgDiv").style.color = "#409529";
				document.getElementById("cartApplyDiscountMsgDiv").style.display = "";
				Effect.Fade("cartApplyDiscountMsgDiv", { duration: 0.25, delay: 2.0 });
			}
			else
			{
				// the discount was not applied
				document.getElementById("cartApplyDiscountMsgDiv").innerHTML = jsonResult.promoResultText;
				document.getElementById("cartApplyDiscountMsgDiv").style.color = "#FF0000";
				document.getElementById("cartApplyDiscountMsgDiv").style.display = "";
				Effect.Fade("cartApplyDiscountMsgDiv", { duration: 0.25, delay: 2.0 });
			}
		},
		onComplete: function()
		{
			applyingCartPromotion = false;
			document.getElementById("discountCode").value = "key code";
		}
	});
	
	return false;
}

function warrantyNoThanks(action)
{
	if(action == "cart")
	{
		hideBBox();
	}
	else if(action == "paypal")
	{
		document.getElementById('cartUpdateForm').action='/updateCart';
		document.getElementById('scNextAction').value = 'checkoutPayPal';
		document.getElementById('cartUpdateForm').submit();
	}
	else if(action == "checkout")
	{
		document.getElementById('cartUpdateForm').action='/updateCart';
		document.getElementById('scNextAction').value = 'checkout';
		document.getElementById('cartUpdateForm').submit();
	}
	else if(action == "checkoutMember")
	{
		document.getElementById('cartUpdateForm').action='/updateCart';
		document.getElementById('scNextAction').value = 'checkoutMember';
		document.getElementById('cartUpdateForm').submit();
	}
}

function warrantyAddPlans(action)
{
	$('warrantyButtonsEnabled').hide();
	$('warrantyButtonsDisabled').show();
	
	$('warrantyForm').request(
	{
	   onSuccess: function(transport)
	   { 
	   		var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			// adding the warranties were successfull
	   			warrantyAddPlansAfterSubmit(action);
	   		}
	   		else
	   		{
	   			// error occurred so just continue with the checkout
	   			warrantyNoThanks(action)
	   		}
	   }
	});
	
	
	return false;
}

function warrantyAddPlansAfterSubmit(action)
{
	document.getElementById('cartUpdateForm').action='/updateCart';
	
	if(action == "cart")
	{
		document.getElementById('scNextAction').value = '';
	}
	else if(action == "paypal")
	{
		document.getElementById('scNextAction').value = 'checkoutPayPal';
	}
	else if(action == "checkout")
	{
		document.getElementById('scNextAction').value = 'checkout';
	}
	else if(action == "checkoutMember")
	{
		document.getElementById('scNextAction').value = 'checkoutMember';
	}
	
	document.getElementById('cartUpdateForm').submit();
}

function showWarrantyDescriptionOfCoverage()
{
	document.getElementById("fadeBg").style.zIndex = 200;
	document.getElementById("bbox").style.display = "none";
	var warrantyPopup = document.getElementById('warrantyCoveragePopup');
	warrantyPopup.style.display = "";
	centerBBox('warrantyCoveragePopup');
}

function hideWarrantyDescriptionOfCoverage()
{
	$('warrantyCoveragePopup').hide();
	document.getElementById("bbox").style.display = "";
	document.getElementById("fadeBg").style.zIndex = 10;	
}

function toggleShippingMethodList(countryKey)
{
	if(countryKey == 2)
	{
		document.getElementById("shippingMethods").style.display = "none";
		document.getElementById("shippingMethodsCanada").style.display = "";
	}
	else
	{
		document.getElementById("shippingMethodsCanada").style.display = "none";
		document.getElementById("shippingMethods").style.display = "";
	}
}

function removeCheckoutItem(orderLineNumber)
{
	var showMultiShipping = false;
	if(document.getElementById('checkoutShippingId'))
	{
		showMultiShipping = true;
	}

	new Ajax.Updater('', '/checkout/removeItem', 
	{
		parameters: 
		{ 
			'orderLineNumber': orderLineNumber,
			'showMultiShipping': showMultiShipping
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				document.getElementById('checkoutCartId').innerHTML = jsonResult.cart;
				document.getElementById('checkoutShippingPrices').innerHTML = jsonResult.method;
	   			document.getElementById('checkoutPricesId').innerHTML = jsonResult.prices;
	   			
	   			var payPalWarningElem = document.getElementById('checkoutPaypalWarning');
	   			var payPalMethodElem = document.getElementById('checkoutPaypalMethod');
	   			if(payPalWarningElem && payPalMethodElem && !jsonResult.hasReorders && !jsonResult.isMultiShipping)
	   			{
	   				payPalMethodElem.style.display = "";
	   				payPalWarningElem.style.display = "none";
	   			}
	   			
	   			var shippingPrices = document.getElementById('checkoutShippingPrices');
	   			if(shippingPrices)
				{
					updateShippingPrices();
				}
	   		}
		}
	});
}

function syncFields(fieldNameSrc, fieldNameDest)
{
	var isSame = document.getElementById('shippingSameAsBilling').checked;
	if(isSame)
	{
		var fieldSrc = document.getElementById(fieldNameSrc);
		var fieldDest = document.getElementById(fieldNameDest);
	
		if(fieldSrc && fieldDest)
		{
			fieldDest.value = fieldSrc.value;
		}
	}
}

function copyBillingAddressToShippingAddress()
{
	var copyElem = document.getElementById("shippingSameAsBilling");
	if(copyElem && copyElem.checked)
	{
		// update the country and then display the correct fields if local or foreign address
		copyFieldValue('billing_country', 'shipping_country');
		onAddressCountryChange(document.getElementById('shipping_country').value, "shipping_", true);
		
		// copy the rest of the fields from billing address to shipping address
		copyFieldValue('billing_firstName', 'shipping_firstName');
		copyFieldValue('billing_lastName', 'shipping_lastName');
		copyFieldValue('billing_company', 'shipping_company');
		copyFieldValue('billing_street1', 'shipping_street1');
		copyFieldValue('billing_street2', 'shipping_street2');
		copyFieldValue('billing_domesticState', 'shipping_domesticState');
		copyFieldValue('billing_foreignState', 'shipping_foreignState');
		copyFieldValue('billing_foreignCity', 'shipping_foreignCity');
		copyFieldValue('billing_zip', 'shipping_zip');
		copyFieldValue('billing_zip_suffix', 'shipping_zip_suffix');
		copyFieldValue('billing_zipOld', 'shipping_zipOld');
		copyFieldValue('billing_phone', 'shipping_phone');
		copyFieldValue('billing_phoneExt', 'shipping_phoneExt');	
	
		
		// we need to remove all shipping options and copy over the billing options
		var billingCities = document.getElementById('billing_domesticCity');
		var shippingCities = document.getElementById('shipping_domesticCity');
	
		// empty the shipping fields
		for(var count = shippingCities.options.length - 1; count >= 0; count--)
	    {
	        shippingCities.options[count] = null;
	    }

		// add the cities to the city select box with keys as postal keys and values as the city name
		for(var i=0; i<billingCities.options.length; i++)
		{
			// create the option in the city options
			var newOption = new Option(billingCities.options[i].text, billingCities.options[i].value);
			shippingCities.options[i] = newOption;
		}

		shippingCities.selectedIndex = billingCities.selectedIndex;
	}
}

function disableShippingAddressFields()
{
	// disable all shipping address fields
	document.getElementById('shipping_firstName').disabled = true;
	document.getElementById('shipping_lastName').disabled = true;
	document.getElementById('shipping_company').disabled = true;
	document.getElementById('shipping_street1').disabled = true;
	document.getElementById('shipping_street2').disabled = true;
	document.getElementById('shipping_country').disabled = true;
	document.getElementById('shipping_zip').disabled = true;
	document.getElementById('shipping_zip_suffix').disabled = true;
	document.getElementById('shipping_domesticCity').disabled = true;
	document.getElementById('shipping_domesticState').disabled = true;
	document.getElementById('shipping_foreignCity').disabled = true;
	document.getElementById('shipping_foreignState').disabled = true;
	document.getElementById('shipping_phone').disabled = true;
	document.getElementById('shipping_phoneExt').disabled = true;
	
	var savedAddresses = document.getElementById('shipping_savedAddresses');
	if(savedAddresses)
	{
		savedAddresses.selectedIndex = 0;
		savedAddresses.disabled = true;
	}
	
	var disabledColor = "#878787";
	document.getElementById('shipping_firstName_text').style.color = disabledColor;
	document.getElementById('shipping_lastName_text').style.color = disabledColor;
	document.getElementById('shipping_company_text').style.color = disabledColor;
	document.getElementById('shipping_street1_text').style.color = disabledColor;
	document.getElementById('shipping_street2_text').style.color = disabledColor;
	document.getElementById('shipping_country_text').style.color = disabledColor;
	document.getElementById('shipping_zipLabel').style.color = disabledColor;
	document.getElementById('shipping_domesticCity_text').style.color = disabledColor;
	document.getElementById('shipping_stateLabel').style.color = disabledColor;
	document.getElementById('shipping_foreignCity_text').style.color = disabledColor;
	document.getElementById('shipping_foreignState_text').style.color = disabledColor;
	document.getElementById('shipping_phone_text').style.color = disabledColor;
	document.getElementById('shipping_phoneExt_text').style.color = disabledColor;
	
	savedAddresses = document.getElementById('shipping_savedAddresses_text');
	if(savedAddresses)
	{
		savedAddresses.style.color = disabledColor;
	}
}

function enableShippingAddressFields()
{
	var savedAddresses = document.getElementById('shipping_savedAddresses');
	if(savedAddresses)
	{
		savedAddresses.selectedIndex = 0;
		savedAddresses.disabled = false;
	}
	
	// enable all shipping address fields
	document.getElementById('shipping_firstName').disabled = false;
	document.getElementById('shipping_lastName').disabled = false;
	document.getElementById('shipping_company').disabled = false;
	document.getElementById('shipping_street1').disabled = false;
	document.getElementById('shipping_street2').disabled = false;
	document.getElementById('shipping_country').disabled = false;
	document.getElementById('shipping_zip').disabled = false;
	document.getElementById('shipping_zip_suffix').disabled = false;
	document.getElementById('shipping_domesticCity').disabled = false;
	document.getElementById('shipping_domesticState').disabled = false;
	document.getElementById('shipping_foreignCity').disabled = false;
	document.getElementById('shipping_foreignState').disabled = false;
	document.getElementById('shipping_phone').disabled = false;
	document.getElementById('shipping_phoneExt').disabled = false;
	
	var enabledColor = "#000000";
	document.getElementById('shipping_firstName_text').style.color = enabledColor;
	document.getElementById('shipping_lastName_text').style.color = enabledColor;
	document.getElementById('shipping_company_text').style.color = enabledColor;
	document.getElementById('shipping_street1_text').style.color = enabledColor;
	document.getElementById('shipping_street2_text').style.color = enabledColor;
	document.getElementById('shipping_country_text').style.color = enabledColor;
	document.getElementById('shipping_zipLabel').style.color = enabledColor;
	document.getElementById('shipping_domesticCity_text').style.color = enabledColor;
	document.getElementById('shipping_stateLabel').style.color = enabledColor;
	document.getElementById('shipping_foreignCity_text').style.color = enabledColor;
	document.getElementById('shipping_foreignState_text').style.color = enabledColor;
	document.getElementById('shipping_phone_text').style.color = enabledColor;
	document.getElementById('shipping_phoneExt_text').style.color = enabledColor;
	
	savedAddresses = document.getElementById('shipping_savedAddresses_text');
	if(savedAddresses)
	{
		savedAddresses.style.color = enabledColor;
	}
}

function resetShippingAddressFields(prefix)
{
	var countryElem = document.getElementById(prefix + "country");
	countryElem.selectedIndex = 0;
	onAddressCountryChange(countryElem.value, prefix, true);
	
	// reset all shipping address fields
	document.getElementById(prefix + 'firstName').value = "";
	document.getElementById(prefix + 'lastName').value = "";
	document.getElementById(prefix + 'company').value = "";
	document.getElementById(prefix + 'street1').value = "";
	document.getElementById(prefix + 'street2').value = "";
	document.getElementById(prefix + 'zipOld').value = "";
	document.getElementById(prefix + 'zip').value = "";
	document.getElementById(prefix + 'zip_suffix').value = "";
	document.getElementById(prefix + 'domesticState').value = "";
	document.getElementById(prefix + 'foreignState').value = "";
	document.getElementById(prefix + 'foreignCity').value = "";
	document.getElementById(prefix + 'phone').value = "";
	document.getElementById(prefix + 'phoneExt').value = "";

	// remove all cities
	var shippingCities = document.getElementById(prefix + 'domesticCity');
	for(var count = shippingCities.options.length - 1; count >= 0; count--)
    {
        shippingCities.options[count] = null;
    }
}

function clearShippingAddressFields(prefix)
{
	var countryElem = document.getElementById(prefix + "country");
	countryElem.selectedIndex = 0;
	
	// reset all shipping address fields
	document.getElementById(prefix + 'firstName').value = "";
	document.getElementById(prefix + 'lastName').value = "";
	document.getElementById(prefix + 'company').value = "";
	document.getElementById(prefix + 'street1').value = "";
	document.getElementById(prefix + 'street2').value = "";
	document.getElementById(prefix + 'zipOld').value = "";
	document.getElementById(prefix + 'zip').value = "";
	document.getElementById(prefix + 'zip_suffix').value = "";
	document.getElementById(prefix + 'domesticState').value = "";
	document.getElementById(prefix + 'foreignState').value = "";
	document.getElementById(prefix + 'foreignCity').value = "";
	document.getElementById(prefix + 'phone').value = "";
	document.getElementById(prefix + 'phoneExt').value = "";

	// remove all cities
	var shippingCities = document.getElementById(prefix + 'domesticCity');
	for(var count = shippingCities.options.length - 1; count >= 0; count--)
    {
        shippingCities.options[count] = null;
    }
	
	hideZipErrorIcon(prefix);
}

function clearBillingAddressFields(prefix)
{
	var countryElem = document.getElementById(prefix + "country");
	countryElem.selectedIndex = 0;
	
	// reset all shipping address fields
	document.getElementById(prefix + 'firstName').value = "";
	document.getElementById(prefix + 'lastName').value = "";
	document.getElementById(prefix + 'company').value = "";
	document.getElementById(prefix + 'street1').value = "";
	document.getElementById(prefix + 'street2').value = "";
	document.getElementById(prefix + 'zipOld').value = "";
	document.getElementById(prefix + 'zip').value = "";
	document.getElementById(prefix + 'zip_suffix').value = "";
	document.getElementById(prefix + 'domesticState').value = "";
	document.getElementById(prefix + 'foreignState').value = "";
	document.getElementById(prefix + 'foreignCity').value = "";
	document.getElementById(prefix + 'phone').value = "";
	document.getElementById(prefix + 'phoneExt').value = "";
	document.getElementById(prefix + 'email').value = "";
	document.getElementById(prefix + 'email_confirm').value = "";

	// remove all cities
	var shippingCities = document.getElementById(prefix + 'domesticCity');
	for(var count = shippingCities.options.length - 1; count >= 0; count--)
    {
        shippingCities.options[count] = null;
    }
	
	hideZipErrorIcon(prefix);
}

function toggleShippingSameAsBilling(isChecked)
{
	if(isChecked)
	{
		copyBillingAddressToShippingAddress();
		disableShippingAddressFields();	
	}
	else
	{
		resetShippingAddressFields("shipping_");
		enableShippingAddressFields();
	}
}

function onAccountTypeChange(accountType)
{
	if(accountType == 1)
	{
		// business account
		document.getElementById("billing_company_required").innerHTML = "*";
		document.getElementById("shipping_company_required").innerHTML = "*";
	}
	else
	{
		// consumer ccount
		document.getElementById("billing_company_required").innerHTML = "&nbsp;";
		document.getElementById("shipping_company_required").innerHTML = "&nbsp;";
	}
}

function checkoutEditBillingAddress()
{
	handleEmailConfirmation("","emailConfirmation");
	
	$('checkoutEditAddressForm').request(
	{
		onSuccess: function(transport)
		{ 				   
			var html = transport.responseText;

		      if(html.indexOf('pcs-error-messages') < 0)
		      {
		    	  hideBBoxClose();
		    	  document.getElementById('checkoutReviewBillingAddress').innerHTML = html;
		    	  doAddressEditEffect('checkoutReviewBillingAddress');
		      }
		      else
		      {
		        $('errorText').innerHTML = html;
		        $('errorSection').show();
		        resetEmailConfirmation("");
		      }
		 }
	});
	
	return false;
}

function checkoutEditShippingAddress()
{
	$('checkoutEditAddressForm').request(
	{
		onSuccess: function(transport)
		{ 				   
			var html = transport.responseText;

		      if(html.indexOf('pcs-error-messages') < 0)
		      {
		    	  eval("var jsonResult = " + html);
		    	  
		    	  hideBBoxClose();
		    	  document.getElementById('checkoutReviewShippingAddress').innerHTML = jsonResult.address;
		    	  document.getElementById('checkoutShippingPrices').innerHTML = jsonResult.method;
		    	  document.getElementById('checkoutPricesId').innerHTML = jsonResult.prices;
		    	  doAddressEditEffect('checkoutReviewShippingAddress');
		    	  updateShippingPrices();
		      }
		      else
		      {
		        $('errorText').innerHTML = html;
		        $('errorSection').show();
		      }
		 }
	});
	
	return false;
}

// highlights the address section that has changed
// only used for the primary billing and shipping, not multi shipping
function doAddressEditEffect(name)
{
  document.getElementById(name).style.backgroundColor = "#B2CDE4";
  new Effect.Highlight(name, 
	  {
  		startcolor:'#B2CDE4',
  		endcolor:'#F8F8F8',
  		restorecolor:'#F8F8F8',
  		duration:0.4,
  		delay:.7,
  		afterFinish: function()
  		{
  			document.getElementById(name).style.backgroundColor = "";
  		}
  	  });
}

// loads a saved shipping address in the checkout member page
function loadSavedShippingAddress(addressKey)
{
	if(addressKey <= 0)
	{
		return;
	}
	
	new Ajax.Updater('', '/checkout/loadShippingAddress', 
	{
		parameters: 
		{ 
			'addressKey': addressKey
		},
		method: 'post',
		onSuccess: function(transport)
		{				
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				checkoutAddressEntryShippingCountryObserver.stop();
				checkoutAddressEntryShippingZipObserver.stop();
				document.getElementById("shippingAddressDiv").innerHTML = html;
				html.evalScripts();
	   		}
			else
			{
				document.getElementById('shipping_savedAddresses').selectedIndex = 0;
			}
		}
	});
}

//loads a saved shipping address in the bbox that edits a shipping
// address during checkout
function loadSavedShippingAddressPopup(addressKey)
{
	if(addressKey <= 0)
	{
		return;
	}
	
	new Ajax.Updater('', '/checkout/loadShippingAddressPopup', 
	{
		parameters: 
		{ 
			'addressKey': addressKey
		},
		method: 'post',
		onSuccess: function(transport)
		{
			// this closes the form observers for country and zip on the popup
			onPopupCloseHandler();
			
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				document.getElementById("bboxContents").innerHTML = html;
				html.evalScripts();
	   		}
			else
			{
				document.getElementById('savedAddresses').selectedIndex = 0;
			}
		}
	});
}

function updateShippingPrices()
{
	document.getElementById("loadingShippingPricesImage").style.display = "";
	
	new Ajax.Updater('', '/checkout/getShippingPrices', 
	{
		onSuccess: function(transport)
		{
			var jsonStr = transport.responseText;
			if(jsonStr.indexOf('pcs-error-messages') >= 0)
			{
				// there was an error getting the shipping prices 
				document.getElementById("loadingShippingPricesImage").style.display = "none";
				return;
			}
			else
			{
				processShippingPrices(jsonStr);
			}
			
		}
	});
}

function processShippingPrices(jsonStr)
{
	eval("var jsonResult = " + jsonStr);
					
	for(var i=0; i<jsonResult.shippingPrices.length; i++)
	{
		var shippingPrice = jsonResult.shippingPrices[i];
		var carrierKey = shippingPrice.carrierKey;
		var serviceKey = shippingPrice.serviceKey;
		var price = shippingPrice.price;
		
		var priceStr = "";
		if(price != "-1")
		{
			priceStr = price;
		}
		
		var priceId = "shippingMethodPrice_" + carrierKey + "_" + serviceKey;
		var priceElem = document.getElementById(priceId);
		if(priceElem)
		{
			priceElem.innerHTML = priceStr;
		}
	}
	
	document.getElementById("loadingShippingPricesImage").style.display = "none";
}

var keepNotification = false;
function updateShippingMethod(carrierServiceId)
{
	keepNotification = false;
	agreeShippingTermsReminderRemove();
	new Ajax.Updater('', '/checkout/updateShippingMethod', 
	{
		parameters: 
		{ 
			'carrierServiceId': carrierServiceId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			document.getElementById('checkoutPricesId').innerHTML = html;
	   			document.getElementById('oldCarrierServiceId').value = carrierServiceId;
	   		}
	   		else
	   		{
	   			showBBoxText("Error",html,300);
	   			var oldCarrierServiceId = document.getElementById('oldCarrierServiceId').value;
	   			document.getElementById(oldCarrierServiceId).checked = true;
	   		}
		}
	});
}

function togglePaymentMethod(paymentTypeId)
{
	document.getElementById("paymentMethodKeyDiv_creditcard").style.display = "none";
	document.getElementById("paymentMethodKeyDiv_paypal").style.display = "none";
	
	// open account might not be displayed if the account is not business
	var openCreditElem = document.getElementById("paymentMethodKeyDiv_opencredit");
	if(openCreditElem)
	{
		openCreditElem.style.display = "none";
	}
	
	document.getElementById(paymentTypeId).style.display = "";
}

function loadPaymentMethod(accountPaymentKey)
{
	alert(accountPaymentKey);
}

// called when use clicks the multiple shipping button on the review page
// we will make sure at least one line is selected for multiple shipping
// we will also copy the selected multishipping lines to the form that
// has the shipping and payment information so that is saved also
function submitMultiShipping()
{
	if(checkMultiShipSelects())
	{
		document.getElementById("checkoutActionType").value = "multiShip";
		copyMultiShippingInformation();
		document.getElementById("checkoutViewForm").submit();
	}
}

// make sure at least one line is selected for multiple shipping
function checkMultiShipSelects()
{
	var elems = document.getElementsByName("multiOrderLineNumbers");
	for(var i=0; i<elems.length; i++)
	{
		if(elems[i].checked)
		{
			// at least one was selected
			return true;
		}
	}
	
	// nothing was selected so display a message
	showBBoxStatic('Multiple Shipping','multiShipWarning',300);
	return false;
}

// copy the multiple shipping ids to the form containing the shipping
// and payment information
function copyMultiShippingInformation()
{
	var elems = document.getElementsByName("multiOrderLineNumbers");
	var orderLineNumbers = "";
	for(var i=0; i<elems.length; i++)
	{
		if(elems[i].checked)
		{
			orderLineNumbers += elems[i].value + ",";
		}
	}

	document.getElementById("multiShippingLines").value = orderLineNumbers;
}

function loadPaymentMethod(accountPaymentKey)
{
	new Ajax.Updater('', '/checkout/loadAccountPayment', 
	{
		parameters: 
		{ 
			'accountPaymentKey': accountPaymentKey
		},
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
				eval("var jsonResult = " + html);
				
				$('creditCardName').writeAttribute({'value':jsonResult.holderName});
				$('creditCardType').writeAttribute({'value':jsonResult.paymentType});
				$('creditCardNumber').writeAttribute({'value':jsonResult.ccNumber});
				$('creditCardExpMonth').writeAttribute({'value':(parseInt(jsonResult.expMnth)-1)});
				$('creditCardExpYear').writeAttribute({'value':jsonResult.expYr});
				$('creditCardSecurityId').writeAttribute({'value':''});
	   		}
		}
	});
}

function addDestination(groupId)
{
	var multiSectionDiv = "multiLineSection_" + groupId;
	new Ajax.Updater('', '/checkout/multiShipAddDestination', 
	{
		parameters: 
		{ 
			'groupId': groupId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	   			document.getElementById(multiSectionDiv).innerHTML = jsonResult.line;
	   			document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
	   		}
		}
	});
}

function removeDestination(groupId, orderLineNumber)
{
	var multiSectionDiv = "multiLineSection_" + groupId;
	new Ajax.Updater('', '/checkout/multiShipRemoveDestination', 
	{
		parameters: 
		{ 
			'groupId': groupId,
			'orderLineNumber': orderLineNumber
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	   			
	   			document.getElementById(multiSectionDiv).innerHTML = jsonResult.line;
	   			document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
	   		}
		}
	});
}

function updateMultiShippingQty(groupId, orderLineNumber)
{
	var oldValueElem = document.getElementById('multiQuantityOld_' + orderLineNumber);
	var newValueElem = document.getElementById('multiQuantity_' + orderLineNumber);

	var oldValue = oldValueElem.value;
	var newValue = newValueElem.value;

	// only update if the old and new values are different
	if(parseInt(oldValue) != parseInt(newValue))
	{
		new Ajax.Updater('', '/checkout/multiShipUpdateQty', {
			parameters: 
			{ 
				'groupId': groupId,
			    'orderLineNumber': orderLineNumber,
			    'quantity': newValue
			},
			method: 'post',
			onSuccess: function(transport)
			{
				var html = transport.responseText;
				if(html == "error" || html.indexOf('pcs-error-messages') >= 0)
				{
					// there was an error updating the quantities 
					// so just revert the changed quantity back to its old value
					document.getElementById('multiQuantity_' + orderLineNumber).value = oldValue;
				}
				else
				{
					eval("var jsonResult = " + html);
					
					var quantities = jsonResult.quantities;
					for(var i=0; i<quantities.qtyChanges.length; i++)
					{
						var qtyChange = quantities.qtyChanges[i];
						var qtyElem = document.getElementById("multiQuantity_" + qtyChange.oln);
						
						if(qtyElem.type == undefined)
						{
							$('multiQuantity_' + qtyChange.oln).innerHTML = qtyChange.qty;
						}
						else
						{
							// change the old value first
							
							$('multiQuantityOld_' + qtyChange.oln).writeAttribute({'value':qtyChange.qty});
							$('multiQuantity_' + qtyChange.oln).writeAttribute({'value':qtyChange.qty});
						}
					}
					
					document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
				}
			}
		});
	}
}

function updateMultiShippingAddress(groupId, orderLineNumber, shipAddressKey)
{
	// [{"carrierKey":3,"serviceKey":4,"description":"GROUND","selected":true},{}]
	
	new Ajax.Updater('', '/checkout/multiShipUpdateAddress', {
		parameters: 
		{ 
			'groupId': groupId,
		    'orderLineNumber': orderLineNumber,
		    'shipAddressKey': shipAddressKey
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
			{
				eval("var jsonResult = " + html);
				document.getElementById('checkoutPrices').innerHTML = jsonResult.prices;
				
				var methods = jsonResult.methods;
				var size = methods.length;
				var methodsSelect = document.getElementById("multiLineShipping_" + orderLineNumber);

				if(size > 0 && methodsSelect)
				{
					// remove the options
					for(var count = methodsSelect.options.length - 1; count >= 0; count--)
				    {
						methodsSelect.options[count] = null;
				    }
					
					// add the new options
					var selectedIndex = 0;
					for(var i=0; i<methods.length; i++)
					{
						// create the option
						var newOption = new Option(methods[i].description, methods[i].carrierKey + "_" + methods[i].serviceKey);
						methodsSelect.options[i] = newOption;
						if(methods[i].selected)
						{
							selectedIndex = i;
						}
					}
					
					methodsSelect.selectedIndex = selectedIndex;
				}
			}
		}
	});
}

function updateMultiShippingMethod(groupId, orderLineNumber, carrierServiceId)
{
	new Ajax.Updater('', '/checkout/multiShipUpdateMethod', {
		parameters: 
		{ 
			'groupId': groupId,
		    'orderLineNumber': orderLineNumber,
		    'carrierServiceId': carrierServiceId
		},
		method: 'post',
		onSuccess: function(transport)
		{
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
			{
				document.getElementById('checkoutPrices').innerHTML = html;
			}
		}
	});
}

function createMultiShippingRecipient()
{
	$('multiShippingNewRecipientForm').request(
	{
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
	   		if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			eval("var jsonResult = " + html);
	
				var recipient = jsonResult.recipient;
		
				// get the information from the json response
				var addressKey = recipient.address.id;
				var addressOption = recipient.address.value;
				var orderLineNumber = recipient.address.orderLineNumber;

				// add the option to each field
				var addressSelects = document.getElementsByName("updatedShippingAddresses");
				for(var i=0; i<addressSelects.length; i++)
				{
					// create the option to add to all shipping address select fields
					var newAddressOption = new Option(addressOption,addressKey);
					var addressSelect = addressSelects[i];
					var len = addressSelect.length;
					addressSelect.options[len] = newAddressOption;
				}
		
				// set the new address to be the address for the order line we clicked new recipient for
				var currentSelect = document.getElementById("multiLineAddress_" + orderLineNumber);
				currentSelect.selectedIndex = currentSelect.options.length - 1;

				// replace prices
				document.getElementById("checkoutPrices").innerHTML = jsonResult.prices;
	
				hideBBox();
	   		}
	   		else
	   		{
	   			$('newRecipientErrors').innerHTML = html;
	   			$('newRecipientErrorsSection').show();
			}
		}
	});
	
	return false;
}

var selectedItems;

function unselectItem(index) {
  document.getElementById('checkboxList_' + selectedItems[index]).checked = false; 
  resetCompareImages();
}

function resetCompareImages() {
  selectedItems = new Array();
  var numSelected = 0;	
  var checkboxes = document.getElementsByClassName('sub_checkbox', $('itemListing'));
  if(checkboxes) {
    for(i=0;i<checkboxes.length;i++) {
      var item = checkboxes[i];
      if (item.checked) {
        var itemkey = item.id.substring(13);
        numSelected++;
        selectedItems[numSelected] = itemkey;
        document.getElementById('compareImage' + numSelected).src = document.getElementById('itemImage_' + itemkey).src;
        document.getElementById('compareTd' + numSelected).style.cursor = 'pointer';
      }
    }
  }
	
  if (numSelected < 4) {
    for (i=numSelected+1; i <= 4; i++) {
      document.getElementById('compareImage' + i).src = '/site/img/pixel.gif';
      document.getElementById('compareTd' + i).style.cursor = '';
    }
  }
}

function addItemsToCart() {
  var cartForm = document.getElementById('addCartForm');
  var checkboxes = document.getElementsByClassName('sub_checkbox', $('itemListing'));
  var numChecked = 0;
  
  if(checkboxes)
  {
    for(i=0;i<checkboxes.length;i++)
    {
      var item = checkboxes[i];
      if (item.checked) {
        numChecked++;
	  	var itemKey = item.id.sub('checkboxList_', '');
	  	var qty =document.getElementById('quantityList_' + itemKey).value;
	  	
	    if ((qty == null) || qty == '')
	    {
	      qty = '1';
	    }
	    
	    var itemKeyField = document.createElement("input");
	    itemKeyField.setAttribute("type", "hidden");
	  	itemKeyField.setAttribute("name", "item");
	  	itemKeyField.setAttribute("value", itemKey);
	  	cartForm.appendChild(itemKeyField);
	  	
	  	var qtyField = document.createElement("input");
	  	qtyField.setAttribute("type", "hidden");
	  	qtyField.setAttribute("name", "qty");
	  	qtyField.setAttribute("value", qty);
	  	cartForm.appendChild(qtyField);
	  }
	}
  }

  if (numChecked == 0) {
    showBBoxMessage('Add Items To Cart', 'Please select at least one item', {'width':325});
  } else {
    cartForm.submit();
  }
}

function addSuggestedItemsToCart() {
	  var cartForm = document.getElementById('addCartForm');
	  var checkboxes = document.getElementsByClassName('sub_checkbox', $('itemListing'));
	  var numChecked = 0;
	  
	  if(checkboxes)
	  {
	    for(i=0;i<checkboxes.length;i++)
	    {
	      var item = checkboxes[i];
	      if (item.checked) {
	        numChecked++;
		  	var itemKey = item.id.sub('checkboxList_', '');
		  	var qty =document.getElementById('quantityList_' + itemKey).value;
		  	
		    if ((qty == null) || qty == '')
		    {
		      qty = '1';
		    }
		    
		    var itemKeyField = document.createElement("input");
		    itemKeyField.setAttribute("type", "hidden");
		  	itemKeyField.setAttribute("name", "item");
		  	itemKeyField.setAttribute("value", itemKey);
		  	cartForm.appendChild(itemKeyField);
		  	
		  	var qtyField = document.createElement("input");
		  	qtyField.setAttribute("type", "hidden");
		  	qtyField.setAttribute("name", "qty");
		  	qtyField.setAttribute("value", qty);
		  	cartForm.appendChild(qtyField);
		  }
		}
	  }

	  if (numChecked == 0) {
		  $('suggestedItemsErrorsSection').show();
	  } else {
	    cartForm.submit();
	  }
	}

function addItemToCart(itemKey) {
  var cartForm = document.getElementById('addCartForm');
  var qty = document.getElementById('quantityList_' + itemKey).value;
  
  if ((qty == null) || qty == '')
  {
    qty = '1';
  }

  var itemKeyField = document.createElement("input");
  itemKeyField.setAttribute("type", "hidden");
  itemKeyField.setAttribute("name", "item");
  itemKeyField.setAttribute("value", itemKey);
  cartForm.appendChild(itemKeyField);

  var qtyField = document.createElement("input");
  qtyField.setAttribute("type", "hidden");
  qtyField.setAttribute("name", "qty");
  qtyField.setAttribute("value", qty);
  cartForm.appendChild(qtyField);

  cartForm.submit();
}

function compareItems() {
  var itemString = "";
  var checkboxes = document.getElementsByClassName('sub_checkbox', $('itemListing'));
  var numChecked = 0;

  if(checkboxes)
  {
    for(i=0;i<checkboxes.length;i++)
    {
      var item = checkboxes[i];

      if (item.checked) {
        var itemkey = item.id.sub('checkboxList_', '');
        itemString += itemkey + ';';
        numChecked++;
      }
    }
  }

  if (numChecked < 2) {
    showBBoxMessage('Compare Items', 'Please select at least two items', {'width':325});
  } else if (numChecked > 4) {
    showBBoxMessage('Compare Items', 'Please select at most four items', {'width':325});
  } else {
    showBBox('Compare Items', '/productCompare?keys=' + itemString, '');
  }
}

function removeCompareItem(itemKey) {
	var items = $('comparedItems').value.split(";");
	var itemString = "";

	for (i=0;i<items.length;i++)
	{
		if (items[i] != itemKey)
		{
			itemString += items[i] + ';';
		}
	}

	showBBox('Compare Items', '/productCompare?keys=' + itemString, '');
}

function highlightDifferences(highlight) {
	if (highlight) {
		showBBox('Compare Items', '/productCompare?highlight=true&keys=' + $('comparedItems').value, '');
	} else {
		showBBox('Compare Items', '/productCompare?keys=' + $('comparedItems').value, '');
	}
}

function addToCart(itemKey) {
	  var cartForm = document.getElementById('addCartForm');
	  var qty = document.getElementById('itemQty').value;

	  if (isNaN(qty) || (qty == '')) {
	    showBBoxMessage('Add To Cart', 'Please enter a valid quantity', {'width':325});
	    return;
	  }

	  var itemKeyField = document.createElement("input");
	  itemKeyField.setAttribute("type", "hidden");
	  itemKeyField.setAttribute("name", "item");
	  itemKeyField.setAttribute("value", itemKey);
	  cartForm.appendChild(itemKeyField);

	  var qtyField = document.createElement("input");
	  qtyField.setAttribute("type", "hidden");
	  qtyField.setAttribute("name", "qty");
	  qtyField.setAttribute("value", qty);
	  cartForm.appendChild(qtyField);
	  
	  var warranty = document.getElementById('warrantySelection');
	  if ((warranty != null) && (warranty.value != '')) {
	    var warrantyItemKeyField = document.createElement("input");
	    warrantyItemKeyField.setAttribute("type", "hidden");
	    warrantyItemKeyField.setAttribute("name", "warrantyItem");
	    warrantyItemKeyField.setAttribute("value", warranty.value);
	    cartForm.appendChild(warrantyItemKeyField);
	  }

	  cartForm.submit();
	}

	function reviewProduct(itemKey){
	  var url = '/reviewProduct?itemKey=' + itemKey;
	  showBBox('Product Review', url);
	}

	function reviewProductFromAccount(itemKey){
	  var url = '/account/reviewProduct?itemKey=' + itemKey;
	  showBBox('Product Review', url);
	}

	function saveAccountReview() {
	  $('saveReviewForm').request(
	  {
	    onSuccess: function(transport)
	    { 
	      var html = transport.responseText;
	      if(html.indexOf('pcs-popup-messages') < 0)
	      {
	        $('productReviewBody').innerHTML = transport.responseText;
	      }
	      else
	      {
	        $('popupMessages').innerHTML = html;
	        $('popupMessagesSection').show();
	      }
	    }
	  });

	  return false;
	}

	function saveFeedback() {
	  $('feedbackSubmitForm').request(
	  {
	    onSuccess: function(transport)
	    { 
	      var html = transport.responseText;
	      if(html.indexOf('pcs-popup-messages') < 0)
	      {
	        showBBoxText('Page Feedback', html);
	        $('feedbackSubmitForm').reset();
	        $('feedbackFormMessagesSection').hide();
	      }
	      else
	      {
	        $('feedbackFormMessages').innerHTML = html;
	        $('feedbackFormMessagesSection').show();
	      }
	    }
	  });

	  return false;
	}

	function saveReview() {
	  $('saveReviewForm').request(
	  {
	    onSuccess: function(transport)
	    { 
	      var html = transport.responseText;
	      if(html.indexOf('pcs-popup-messages') < 0)
	      {
	        $('productReviewBody').innerHTML = transport.responseText;
	        centerBBox();
	      }
	      else
	      {
	        $('popupMessages').innerHTML = html;
	        $('popupMessagesSection').show();
	      }
	    }
	  });

	  return false;
	}

	function saveAccountReview() {
	  $('saveReviewForm').request(
	  {
	    onSuccess: function(transport)
	    { 
	      var html = transport.responseText;
	      if(html.indexOf('pcs-popup-messages') < 0)
	      {
	    	  window.location = "/account/productReviewsPage";
	      }
	      else
	      {
	        $('popupMessages').innerHTML = html;
	        $('popupMessagesSection').show();
	      }
	    }
	  });

	  return false;
	}

	function emailProduct(itemKey){
	  var url = '/emailProduct?itemKey=' + itemKey;
	  showBBox('Email to Friend', url);
	}

	function emailProductSend() {
		  $('emailProductForm').request(
		  {
		    onSuccess: function(transport)
		    { 
		      var html = transport.responseText;
		      if(html.indexOf('pcs-popup-messages') < 0)
		      {
		        $('emailProductBody').innerHTML = transport.responseText;
		      }
		      else
		      {
		        $('popupMessages').innerHTML = html;
		        $('popupMessagesSection').show();
		      }
		    }
		  });

		  return false;
		}

	function swapImage(itemKey, filename, imageUrl, altText) {
	  var prodImage = document.getElementById('prodImage');
	  prodImage.src = imageUrl;
	  prodImage.alt = altText;

	  var prodImageUrl = document.getElementById('prodImageUrl');
	  var enlargeViewUrl = document.getElementById('enlargeViewUrl');
	  prodImageUrl.href = 'javascript:enlargeImage(\'' + itemKey + '\',\'' + filename + '\')';
	  enlargeViewUrl.href = prodImageUrl.href;
	}

	function enlargeImage(itemKey, filename) {
	  var url = '/enlargeImage?itemKey=' + itemKey + '&imageUrl=' + filename;
	  showBBox('Enlarged View', url);
	}

	function enlargeImageSwap(itemKey, filename) {
	  var url = '/enlargeImage?swap=true&itemKey=' + itemKey + '&imageUrl=' + filename;

	  new Ajax.Updater('', url,
	  {
	    onSuccess: function(transport)
	    {
	      var html = transport.responseText;
	      eval("var jsonResult = " + html);
	      document.getElementById('enlargedImage').src = jsonResult.imageUrl;
	      
	      var zoomWindow = document.getElementById('zoomWindow');
	      zoomWindow.style.visibility = 'hidden';

	      var zoomButton = document.getElementById('zoomButtonTable');
	      if ((jsonResult.zoom != null) && (jsonResult.zoom != '')) {
	        zoomButton.style.visibility = 'visible';
	      } else {
	        zoomButton.style.visibility = 'hidden';
	      }

	      if (zoomButton.style.visibility == 'visible') {
	        document.getElementById('zoomImageSrc').src = jsonResult.zoom;
	      }
	    }
	  });
	}

	function enlargeImageScrollUp(){
	  clearTimeout(enlargeImageScrollUpTimer);
	  document.getElementById('thumbnailScroll').scrollTop -= 1;
	  enlargeImageScrollUpTimer = setTimeout("enlargeImageScrollUp()",5);
	}

	function enlargeImageScrollDown(){
	  clearTimeout(enlargeImageScrollDownTimer);
	  document.getElementById('thumbnailScroll').scrollTop += 1;
	  enlargeImageScrollDownTimer = setTimeout("enlargeImageScrollDown()",5);
	}

	function enlargeImageScrollStop(){
	  clearTimeout(enlargeImageScrollUpTimer);
	  clearTimeout(enlargeImageScrollDownTimer);
	}

	var enlargeImageScrollUpTimer = "";
	var enlargeImageScrollDownTimer = "";

	var zoomDraggable;
	var zoomWindow;
	var zoomImage;
	var enlargeImageHeight;
	var enlargeImageWidth;
	var zoomXRatio;
	var zoomYRatio;

	function zoomDrag() {
	  var windowX = parseInt($(zoomWindow).getStyle('left')) + 60 - 10;
	  var windowY = parseInt($(zoomWindow).getStyle('top')) + 60 - 46;
	  positionZoomImage(windowX, windowY);
	}

	function zoomSnap(x, y) {
	  var retX = x;
	  var retY = y;

	  if (x < -30) {
	    retX = -30;
	  } else if ((x + 120) > (enlargeImageWidth + 50)) {
	    retX = (enlargeImageWidth + 50 - 120);
	  }

	  if (y < 6) {
	    retY = 6;
	  } else if ((y + 120) > (enlargeImageHeight + 86)) {
	    retY = (enlargeImageHeight + 86 - 120);
	  }

	  return [retX, retY];
	}

	function positionZoomImage(windowX, windowY) {
	  zoomImage.style.left = (0 - (windowX * zoomXRatio) + 60) + 'px';
	  zoomImage.style.top = (0 - (windowY * zoomYRatio) + 60) + 'px';
	}

	function imageZoom() {
	  zoomWindow = document.getElementById('zoomWindow');
	  if (zoomWindow.style.visibility == 'visible') {
	    // hide
	    zoomWindow.style.visibility = 'hidden';
	    zoomDraggable.destroy();
	  } else {
	    // show
	    zoomDraggable = new Draggable('zoomWindow', {change: zoomDrag, snap: zoomSnap, starteffect: null, endeffect: null});
	    zoomImage = document.getElementById('zoomImage');
	    var zoomImageHeight = parseInt($('zoomImageSrc').height);
	    var zoomImageWidth = parseInt($('zoomImageSrc').width);
	    enlargeImageHeight = parseInt($('enlargedImage').height);
	    enlargeImageWidth = parseInt($('enlargedImage').width);
	    zoomXRatio = zoomImageWidth / enlargeImageWidth;
	    zoomYRatio = zoomImageHeight / enlargeImageHeight;

	    var windowX = enlargeImageWidth / 2;
	    var windowY = enlargeImageHeight / 2;
	    zoomWindow.style.left = (windowX + 10 - 60) + 'px';
	    zoomWindow.style.top = (windowY + 46 - 60) + 'px';
	    positionZoomImage(windowX, windowY);
	    zoomWindow.style.visibility = 'visible';
	  }
	}

	function showSavedLists() {
	  var savedLists = document.getElementById("div_savedList");
	  var newList = document.getElementById("div_newList");
	  savedLists.style.display = 'block';
	  newList.style.display = 'none';
	}

	function showNewList() {
	  var savedLists = document.getElementById("div_savedList");
	  var newList = document.getElementById("div_newList");
	  savedLists.style.display = 'none';
	  newList.style.display = 'block';
	}

	function picGroupSorting(picGroupKey, sortColumn, sortDirection) {
	  var url = '/picGroupGridSort?picGroupKey=' + picGroupKey + '&sortColumn=' + sortColumn + '&sortDirection=' + sortDirection;

	  new Ajax.Updater('', url,
	  {
	    onSuccess: function(transport)
	    {
	      var html = transport.responseText;
	      if (html.length > 0)
	      {
	        document.getElementById('picGroupGrid').innerHTML = html;
	      }
	    }
	  });
	}

	function addItemsToCartFromPicGroup() {
	var cartForm = document.getElementById('addCartForm');
	var qtyFields = document.getElementsByClassName('pic_group_qty', $('picGroupGrid'));
	var numItems = 0;

		  if(qtyFields)
		  {
		    for(i=0;i<qtyFields.length;i++)
		    {
		      var qtyField = qtyFields[i];
		      if (qtyField.value != '')
		      {
		        if (!isNaN(qtyField.value))
		        {
		    	  	var itemKey = qtyField.id.sub('quantityList_', '');
		    	    var itemKeyFormField = document.createElement("input");
		    	    itemKeyFormField.setAttribute("type", "hidden");
		    	    itemKeyFormField.setAttribute("name", "item");
		    	    itemKeyFormField.setAttribute("value", itemKey);
		    	  	cartForm.appendChild(itemKeyFormField);
		    	  	
		    	  	var qtyFormField = document.createElement("input");
		    	  	qtyFormField.setAttribute("type", "hidden");
		    	  	qtyFormField.setAttribute("name", "qty");
		    	  	qtyFormField.setAttribute("value", qtyField.value);
		    	  	cartForm.appendChild(qtyFormField);

		    	  	
		    	  	numItems++;
		        }
		        else
		        {
		        	showBBoxMessage('Add Items To Cart', 'Please enter a valid quantity', {'width':325});
		            return;
		        }
		      }
		    }
		  }

		  if (numItems == 0) {
			    showBBoxMessage('Add Items To Cart', 'Please enter at least one quantity', {'width':325});
			  } else {
			    cartForm.submit();
			  }
	}

	function shoppingListInfo() {
	  var url = '/contentPopup?pageName=shoppingListInfo';
	  showBBox('Information About Shopping Lists', url);
	}
	
		function populateAddonFinder(action, path, submitPath) {
		  // reset path on submit form
		  if ((submitPath != null) && (submitPath != '')) {
		    document.getElementById(submitPath).value='';
		  }

		  new Ajax.Updater('', '/' + action, 
		  {
		    parameters:
		    {
		      'searchModel.path':path
		    },
		    onSuccess: function(transport)
		    {
		      var html = transport.responseText;

		      if(html.indexOf('pcs-error-messages') < 0)
		      {
		        eval("var jsonResult = " + html);

		        var dropdownList = jsonResult.dropdownList;
		        for(var i=0; i<dropdownList.length; i++)
		        {
		          // get dropdown element
		          var dropdownElement = document.getElementById(dropdownList[i].id);
		          // remove existing options
		          for(var count = dropdownElement.options.length - 1; count >= 0; count--)
		          {
		            dropdownElement.options[count] = null;
		          }

		          var options = dropdownList[i].option;
		          for(var j=0; j<options.length; j++)
		          {
		            // create the option
		            var newOption = new Option(options[j].displayText,options[j].value);
		            dropdownElement.options[j] = newOption;
		          }

		          // select the first one in the list
		          dropdownElement.selectedIndex = 0;

		          // if more than one item in list, set to default color, otherwise grey
		          if (dropdownElement.options.length > 1)
		          {
		            dropdownElement.style.color="";
		          }
		          else
		          {
		            dropdownElement.style.color="#b4b4b4";
		          }
		        }
		      }
		    }
		  });
		}

		function populateProductFinder(elem, facetInfo) {
		  if (elem == null)
		  {
		    // initialization
		    var firstFacet = document.getElementById(facetInfo[1][0]);
		    var path = firstFacet.value;
		    var facetSystemNames = facetInfo[0];
		    var facetFormIds = facetInfo[1];
		    var facetDefaultValues = facetInfo[2];
		  } else {
		    var facetIndex = facetInfo[1].indexOf(elem.id) + 1;
		    var path = elem.value;
		    if (path == '')
		    {
		      var remainingFacetIds = facetInfo[1].slice(facetIndex);
		      for (var index = 0; index < remainingFacetIds.length; index++)
		      {
		        var facet = document.getElementById(remainingFacetIds[index]);
		        facet.selectedIndex = 0;
		        facet.disabled = true;
		      }

		      return;
		    } else {
		      var facetSystemNames = facetInfo[0].slice(facetIndex);
		      var facetFormIds = facetInfo[1].slice(facetIndex);
		      var facetDefaultValues = facetInfo[2].slice(facetIndex);
		    }
		  }

		  new Ajax.Updater('', '/productFinder', 
		  {
		    parameters:
		    {
		      'searchModel.path':path,
		      'facetSystemNames':facetSystemNames,
		      'facetFormIds':facetFormIds,
		      'facetDefaultValues':facetDefaultValues
		    },
		    onSuccess: function(transport)
		    {
		      var html = transport.responseText;

		      if(html.indexOf('pcs-error-messages') < 0)
		      {
		        eval("var jsonResult = " + html);

		        var dropdownList = jsonResult.dropdownList;
		        for(var i=0; i<dropdownList.length; i++)
		        {
		          // get dropdown element
		          var dropdownElement = document.getElementById(dropdownList[i].id);

		          // remove existing options
		          for(var count = dropdownElement.options.length - 1; count >= 0; count--)
		          {
		            dropdownElement.options[count] = null;
		          }

		          var options = dropdownList[i].option;
		          for(var j=0; j<options.length; j++)
		          {
		            // create the option
		            var newOption = new Option(options[j].displayText,options[j].value);
		            dropdownElement.options[j] = newOption;
		          }

		          // select the first one in the list
		          dropdownElement.selectedIndex = 0;

		          // if more than one item in list, set to default color, otherwise grey
		          if (dropdownElement.options.length > 1)
		          {
		            dropdownElement.disabled = false;
		          }
		          else
		          {
		            dropdownElement.disabled = true;
		          }
		        }
		      }
		    }
		  });
		}

		function executeProductFinderSearch(elem, pageTitle) {
		  var path = elem.value;
		  if (path == '') {
		  	showBBoxMessage(pageTitle, 'Please make all selections first', {'width':325});
		  	return;
		  }

		  if (path.indexOf('||') == -1) {
		  	showBBoxMessage(pageTitle, 'Please select another attribute', {'width':325});
		  	return;
		  }

		  var form = document.createElement("form");
		  document.body.appendChild(form);
		  form.method = "post";
		  form.action = '/productFinder';

		  var pathField = document.createElement("input");
		  pathField.setAttribute("type", "hidden");
		  pathField.setAttribute("name", "searchModel.path");
		  pathField.setAttribute("value", path);
		  form.appendChild(pathField);

		  var pageTitleField = document.createElement("input");
		  pageTitleField.setAttribute("type", "hidden");
		  pageTitleField.setAttribute("name", "pageTitle");
		  pageTitleField.setAttribute("value", pageTitle);
		  form.appendChild(pageTitleField);

		  form.submit();
		}

		function switchFastTab(webPrimaryKey, tabSelection) {
		  if (document.getElementById('FastTab' + tabSelection).className == 'home_tab_inactive')
		  {
		    var url = '/switchFastTab?webPrimaryKey=' + webPrimaryKey + '&tabSelection=' + tabSelection;

		    new Ajax.Updater('', url,
		    {
		      onSuccess: function(transport)
		      {
		        var html = transport.responseText;
		        $('fastTabsBody').innerHTML = transport.responseText;

		        for (var tab=1; tab <= 4; tab++) {
		          var tabElement = document.getElementById('FastTab' + tab);
		          if (tab == tabSelection) {
		            tabElement.className = 'home_tab_active';
		          } else {
		            tabElement.className = 'home_tab_inactive';
		          }
		        }
		      }
		    });
		  }
		}
		
		function quickOrderMultiple() {
			  $('quickOrderMultiple').show();
			}

			function changeCategoryListing(letter) {
			  var url = '/homepageCategoryListing?letter=' + letter;

			  new Ajax.Updater('', url,
			  {
			    onSuccess: function(transport)
			    {
			      var html = transport.responseText;
			      document.getElementById('homepageCategoryListing').innerHTML = html;
			    }
			  });
			}
			
			function addAddress()
			{
				handleEmailConfirmation("","emailConfirmation");
				
				$('addAddressForm').request(
				{
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
							document.getElementById("globalContent").innerHTML = html;
							hideBBoxClose();
						}
						else {	
							$('errorText').innerHTML = html;
				   			$('errorSection').show();
				   			resetEmailConfirmation("");
						}
					}
				});
				
				return false;
			}

			function editAddress()
			{
				handleEmailConfirmation("","emailConfirmation");
				
				$('editAddressForm').request(
				{
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
							document.getElementById("globalContent").innerHTML = html;
							hideBBoxClose();
						}
						else {	
							$('errorText').innerHTML = html;
				   			$('errorSection').show();
				   			resetEmailConfirmation("");
						}
					}
				});
				
				return false;
			}

			function setDefaultAddress(addressKey)
			{
				new Ajax.Updater('', '/account/setDefaultShippingAddress', {
					parameters: 
					{ 
						'addressKey': addressKey
					},
					method: 'post',
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("globalContent").innerHTML = html;
						}
						else {
							// an error occurred
						}
					}
				});
			}

			function deleteAddress()
			{
				new Ajax.Updater('', '/account/deleteShippingAddress', {
					parameters: 
					{ 
						'addressKey': document.getElementById('deleteAddressId').value
					},
					method: 'post',
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("globalContent").innerHTML = html;
						}
						else {
							// an error occurred
						}
					}
				});
				
				hideBBox();
			}

			function deleteAddressConfirm(addressKey)
			{
				document.getElementById('deleteAddressId').value = addressKey;
				showBBoxStatic('Confirmation', 'deleteAddressConfirmation');
			}

			//to support google autofill the email confirm has the same name as the email
			//according to ECML field names. When the page submits, we need to rename the field
			function handleEmailConfirmation(prefix, realName)
			{
				var emailConfirmElem = document.getElementById(prefix + "email_confirm");
				if(!emailConfirmElem)
				{
					return;
				}

				emailConfirmElem.name = realName;
				return true;
			}

			//puts the email confirmation text field but to the ECML name for online email
			function resetEmailConfirmation(prefix)
			{
				var emailConfirmElem = document.getElementById(prefix + "email_confirm");
				if(!emailConfirmElem)
				{
					return;
				}

				emailConfirmElem.name = "Ecom_BillTo_Online_Email";
				return true;
			}

			function editCatalogAddress()
			{
				handleEmailConfirmation("","emailConfirmation");
				
				$('editAddressForm').request(
				{
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
							document.getElementById("tilesContent").innerHTML = html;
							hideBBoxClose();
						}
						else {	
							$('errorText').innerHTML = html;
				   			$('errorSection').show();
				   			resetEmailConfirmation("");
						}
					}
				});
				
				return false;
			}

			function addCatalogAddress()
			{
				handleEmailConfirmation("","emailConfirmation");
				
				$('addAddressForm').request(
				{
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
							document.getElementById("tilesContent").innerHTML = html;
							hideBBoxClose();
						}
						else {	
							$('errorText').innerHTML = html;
				   			$('errorSection').show();
				   			resetEmailConfirmation("");
						}
					}
				});
				
				return false;
			}
			
			// on the order history search page, if the user searches
			// by status, we will show a drop down of the various statuses
			// if the user doesn't search by status, we will show a free form text field
			function toggleOrderHistorySearchTerm(searchType)
			{
				if(!searchType)
				{
					return;
				}
				
				var termElem = document.getElementById("orderHistorySearchValue");
				var statusElem = document.getElementById("orderHistorySearchStatusValue");
				
				if(searchType == "status")
				{
					termElem.style.display = "none";
					statusElem.style.display = "";
				}
				else if(searchType == "myOrders" || searchType == "companyOrders")
				{
					termElem.disabled = true;
					statusElem.style.display = "none";
					termElem.style.display = "";
				}
				else
				{
					termElem.disabled = false;
					statusElem.style.display = "none";
					termElem.style.display = "";
				}
			}

			function toggleProductReviewComments(index)
			{
				var readMoreElem = document.getElementById("readMoreButton_" + index);
				if(!readMoreElem)
				{
					return;
				}
				
				var reviewSummaryElem = document.getElementById("reviewSummary_" + index);
				var reviewFullElem = document.getElementById("reviewFull_" + index);
				if(!reviewSummaryElem || !reviewFullElem)
				{
					return;
				}
				
				if(reviewFullElem.style.display == "none")
				{
					// we are currently showing the summary review instead of the full
					readMoreElem.src = "/site/img/btn_read_more_collapse.gif";
					reviewSummaryElem.style.display = "none";
					reviewFullElem.style.display = "";
				}
				else
				{
					// we are currently showing the full review
					readMoreElem.src = "/site/img/btn_read_more.gif";
					reviewFullElem.style.display = "none";
					reviewSummaryElem.style.display = "";
				}
			}

			function viewQuote(quoteKey){
				var url = '/account/quoteDetails?quoteKey=' + quoteKey;
				showBBox('Quote Information', url);
			}

			function toggleBusinessAccountFields(accountType)
			{
				if(accountType == '1')
				{
					document.getElementById("businessAccountFields").style.display = "";
				}
				else
				{
					document.getElementById("businessAccountFields").style.display = "none";
				}
			}

			function updateProductReviews(url)
			{
				new Ajax.Updater('', url,
				{
					onSuccess: function(transport)
					{
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("productReviewsDiv").innerHTML = html;
						}
						else 
						{
							// do nothing
						}
					}
				});
			}

			function updateProductMissingReviews(url)
			{
				new Ajax.Updater('', url,
				{
					onSuccess: function(transport)
					{
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("productMissingReviewsDiv").innerHTML = html;
						}
						else 
						{
							// do nothing
						}
					}
				});
			}

			function selectAllProducts()
			{
			  var checkboxes = document.getElementsByClassName('sub_checkbox', $('itemListing'));
			  if(checkboxes) {
			    for(i=0;i<checkboxes.length;i++) {
			      var item = checkboxes[i];
			      item.checked = true;
			    }
			  }
			}

			function addItemsToCartFromHistory() {
			  var cartForm = document.getElementById('addCartForm');
			  var checkboxes = document.getElementsByClassName('sub_checkbox', $('itemListing'));
			  var numChecked = 0;

			  if(checkboxes)
			  {
			    for(i=0;i<checkboxes.length;i++)
			    {
			      var item = checkboxes[i];
				 
				  if (item.checked) {
			        numChecked++;
				  	var itemKey = item.id.sub('checkboxList_', '');

				    var itemKeyField = document.createElement("input");
				  	itemKeyField.setAttribute("type", "hidden");
				  	itemKeyField.setAttribute("name", "item");
				  	itemKeyField.setAttribute("value", itemKey);
				  	cartForm.appendChild(itemKeyField);
					  	
				  	var qtyField = document.createElement("input");
				  	qtyField.setAttribute("type", "hidden");
				  	qtyField.setAttribute("name", "qty");
				  	qtyField.setAttribute("value", "1");
				  	cartForm.appendChild(qtyField);
				  }
				}
			  }

			  if (numChecked == 0) {
			    showBBoxMessage('Add Items To Cart', 'Please select at least one item', {'width':325});
			  } else {
			    cartForm.submit();
			  }
			}

			function toggleCreateExtranetUserFields(role)
			{
				if(role == 1 || role == 2)
				{
					// disable
					document.getElementById("extranetUserSupervisor").disabled = true;
					document.getElementById("extranetUserSpendingLimit").disabled = true;
					
					document.getElementById("extranetUserSupervisorText").style.color = "#999999";
					document.getElementById("extranetUserSpendingLimitText").style.color = "#999999";
					
					document.getElementById("extranetUserSpendingLimitRequired").style.display = "none";
				}
				else
				{
					// enable
					document.getElementById("extranetUserSupervisor").disabled = false;
					document.getElementById("extranetUserSpendingLimit").disabled = false;
					
					document.getElementById("extranetUserSupervisorText").style.color = "#000000";
					document.getElementById("extranetUserSpendingLimitText").style.color = "#000000";
					
					document.getElementById("extranetUserSpendingLimitRequired").style.display = "";
				}
			}
			
			function addPaymentMethod()
			{
				$('addPaymentMethodForm').request(
				{
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
							document.getElementById("globalContent").innerHTML = html;
							hideBBox();
						}
						else {	
							$('errorText').innerHTML = html;
				   			$('errorSection').show();
						}
					}
				});
				
				return false;
			}

			function editPaymentMethod()
			{
				$('editPaymentMethodForm').request(
				{
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
							document.getElementById("globalContent").innerHTML = html;
							hideBBox();
						}
						else {	
							$('errorText').innerHTML = html;
				   			$('errorSection').show();
						}
					}
				});
				
				return false;
			}

			function setDefaultPaymentMethod(paymentMethodKey)
			{
				new Ajax.Updater('', '/account/setDefaultPaymentMethod', {
					parameters: 
					{ 
						'paymentMethodKey': paymentMethodKey
					},
					method: 'post',
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("globalContent").innerHTML = html;
						}
						else {
							// an error occurred
						}
					}
				});
			}

			function deletePaymentMethod()
			{
				new Ajax.Updater('', '/account/deletePaymentMethod', {
					parameters: 
					{ 
						'paymentMethodKey': document.getElementById('deletePaymentId').value
					},
					method: 'post',
					onSuccess: function(transport)
					{ 
						var html = transport.responseText;
				   		if(html.indexOf('pcs-error-messages') < 0)
				   		{
				   			document.getElementById("globalContent").innerHTML = html;
						}
						else {
							// an error occurred
						}
					}
				});

				hideBBox();
			}

			function deletePaymentMethodConfirm(paymentMethodKey)
			{
				document.getElementById('deletePaymentId').value = paymentMethodKey;
				showBBoxStatic('Confirmation', 'deletePaymentConfirmation');
			}


function emptyCartConfirm()
{
	showBBoxStatic('Confirmation', 'emptyCartConfirmation');
}

function subscribeNewsletter(formId) {
  $(formId).request(
  {
    onSuccess: function(transport)
    { 
      var html = transport.responseText;
      showBBoxText('Newsletter Subscription', html);
    }
  });

  return false;
}

function deleteCartConfirm(cartKey)
{
	document.getElementById('deleteCartId').value = cartKey;
	showBBoxStatic('Confirmation', 'deleteCartConfirmation');
}

function deleteCart()
{
	window.location.href = '/deleteSavedCart/cartId/' + document.getElementById('deleteCartId').value;
}

function agreeShippingTermsReminder()
{
	var prepayElem = document.getElementById("shippingTypePrepay");
	var collectElem = document.getElementById("shippingTypeFreightCollect");
	var truckShipmentTerms = document.getElementById("truckShipmentTerms");
	var freightCollectTerms = document.getElementById("freightCollectTerms");
	
	if(prepayElem && prepayElem.checked && truckShipmentTerms && !truckShipmentTerms.checked)
	{
		document.getElementById("truckShipmentTermsAlert").style.border = "3px solid #ff0000";
		document.getElementById("truckShipmentTermsAlert").style.backgroundColor = "#FFFAFA";
		return;
	}
	else if(collectElem && collectElem.checked && freightCollectTerms && !freightCollectTerms.checked)
	{
		document.getElementById("freightCollectTermsAlert").style.border = "3px solid #ff0000";
		document.getElementById("freightCollectTermsAlert").style.backgroundColor = "#FFFAFA";
		return;
	}
}

function agreeShippingTermsReminderRemove()
{
	if(keepNotification === true)
	{
		return;
	}
	
	var prepayElem = document.getElementById("shippingTypePrepay");
	var collectElem = document.getElementById("shippingTypeFreightCollect");
	var truckShipmentTerms = document.getElementById("truckShipmentTerms");
	var freightCollectTerms = document.getElementById("freightCollectTerms");
	
	if(prepayElem && prepayElem.checked && truckShipmentTerms && !truckShipmentTerms.checked)
	{
		document.getElementById("truckShipmentTermsAlert").style.border = "3px solid #ffffff";
		document.getElementById("truckShipmentTermsAlert").style.backgroundColor = "#FFFFFF";
		return;
	}
	else if(collectElem && collectElem.checked && freightCollectTerms && !freightCollectTerms.checked)
	{
		document.getElementById("freightCollectTermsAlert").style.border = "3px solid #ffffff";
		document.getElementById("freightCollectTermsAlert").style.backgroundColor = "#FFFFFF";
		return;
	}
}

function completeOrderSubmit()
{
	var shippingCostElem = document.getElementById("shippingCostReviewDiv");
	if(shippingCostElem && shippingCostElem.innerHTML == "--")
	{
		showBBoxMessage('Error Completing Order', 'We are sorry but the shipping method is unavailable for the current destination.<br/>Please either select another shipping method or call our Sales Department at 1-800-645-1232.');
		return;
	}
	
	var prepayElem = document.getElementById("shippingTypePrepay");
	var collectElem = document.getElementById("shippingTypeFreightCollect");
	var truckShipmentTerms = document.getElementById("truckShipmentTerms");
	var freightCollectTerms = document.getElementById("freightCollectTerms");
	
	if(prepayElem && prepayElem.checked && truckShipmentTerms && !truckShipmentTerms.checked)
	{
		document.getElementById("truckShipmentTermsAlert").style.border = "3px solid #ff0000";
		document.getElementById("truckShipmentTermsAlert").style.backgroundColor = "#FFFAFA";
		showBBoxMessage('Truck Shipment Terms', 'Please agree to the "Truck Shipment Terms"');
		return;
	}
	else if(collectElem && collectElem.checked && freightCollectTerms && !freightCollectTerms.checked)
	{
		document.getElementById("freightCollectTermsAlert").style.border = "3px solid #ff0000";
		document.getElementById("freightCollectTermsAlert").style.backgroundColor = "#FFFAFA";
		showBBoxMessage('Freight Collect Terms', 'Please agree to the "Freight Collect Terms"');
		return;
	}
	
	document.getElementById("completeOrderEnabled").style.display = "none";
	document.getElementById("completeOrderDisabled").style.display = "";
	document.getElementById('checkoutViewForm').submit();
}

function changeAccessoryCharge(shipAddressKey, freightAccessoryKey, isChecked)
{
	var action = "/checkout/addAccessoryCharge";
	if(!isChecked)
	{
		action = "/checkout/removeAccessoryCharge";
	}
	
	new Ajax.Updater('', action, {
		parameters: 
		{ 
			'shipAddressKey': shipAddressKey,
			'freightAccessoryKey': freightAccessoryKey
		},
		method: 'post',
		onSuccess: function(transport)
		{ 
			var html = transport.responseText;
			if(html.indexOf('pcs-error-messages') < 0)
	   		{
	   			document.getElementById('checkoutPricesId').innerHTML = html;
			}
			else {
				// an error occurred
			}
		}
	});
}

function validateSearchKeywords() {
	if (document.getElementById('searchInput').value == 'Enter Stock # or Keyword') {
		return false;
	} else {
		return true;
	}
}

function openGecProductInfoWindow(itemKey)
{
	window.open("/gec/productWindow?itemKey=" + itemKey, "ProductInfo", "status=no,toolbar=no,width=650,height=700,resizable=yes,scrollbars=yes,location=no,directories=no,menubar=no,copyhistory=no");
}

function openGecPicGroupInfoWindow(picGroupKey)
{
	window.open("/gec/picGroupWindow?picGroupKey=" + picGroupKey, "PicGroupInfo", "status=no,toolbar=no,width=650,height=700,resizable=yes,scrollbars=yes,location=no,directories=no,menubar=no,copyhistory=no");
}
