// This prevents the file from bombing if SITE_ROOT is not defined in the HTML file.
if (SITE_ROOT == null) { var SITE_ROOT = "/"; }
if (CONTENT_ROOT == null) { var CONTENT_ROOT = "/"; }

function loadScript (e) {
  jQuery(".accordion-header").click(function() {
    jQuery(this).toggleClass("active").next().slideToggle('fast', function() {
      jQuery("input[type='text']:enabled:first", this).focus();
    });
  });
  
  // until css2.1 is common enough
  jQuery("#content a[href$=\"doc\"]").addClass("doc");
  jQuery("#content a[href$=\"wmv\"]").addClass("wmv");
  jQuery("#content a[href$=\"pdf\"]").addClass("pdf");
  jQuery("#content a[href$=\"zip\"]").addClass("zip");
  jQuery("#content a[href$=\"ppt\"]").addClass("ppt");
  jQuery("#content a[href$=\"xls\"]").addClass("xls");
  jQuery("#content a[href$=\"mdi\"]").addClass("mdi");
  jQuery("#content a[href$=\"vcf\"]").addClass("vcf");
  jQuery("#content a[href$=\"xml\"]").addClass("xml");
  jQuery("#content a[href$=\"mdb\"]").addClass("mdb");
  jQuery("#content a[href$=\"pub\"]").addClass("pub");
  jQuery("#content a[href$=\"mpp\"]").addClass("mpp");
  
  Menu.init("primaryTabs");
  Menu.init("controls");
  
  Forms.required("searchterm", "Keyword, Part Number or X-Ref");
  Autocomplete.Initialize("searchterm", "Search.ex", "doCategoryManufacturerSearch");
  
  //request information form
  jQuery("#fNewsletter").click(function() {
      jQuery(".newsletter").toggle();
      //jQuery("#titleRow").toggle();
      jQuery("#businessQuestionRow").toggle();
  });
  
  jQuery("#fNewsletter:checked").val(function() {
    jQuery(".newsletter").toggle();
    //jQuery("#titleRow").toggle();
    jQuery("#businessQuestionRow").toggle();
  });
  
  if (jQuery(".error:first").offset()) {
    jQuery(document).scrollTop(jQuery(".error:first").offset().top - 15);
  }
  
  FSToggle.init();
  Tables.init(e);
  StoreLocator.init(e);
  Help.init(e);
  AccountInformation.init(e);
  Custs.init(e);
  EditAddress.init(e); // TODO -FIX EVENT for EditAddress
  EditUserAccount.init(e);
  Locations.init(e);
  Users.init(e);
  EditAddress.init(e);
  Details.init(e);
  Tabination.init(e);
  OrderPad.init(e);
  mtr.init(e);
  Rotate.init(e);
  Registration.Initialize(e);
  //Session.init(e);
  // Intentionally left Performance.init out
  StoreLocator.init();
  
} Events.addEvent(window, "load", loadScript);

//-----( @Endeca )---------------------------------------------
var Endeca = {
  init: function() {
    // necessary for web studio to work correctly
    if ((location.host).indexOf("fastenal.com") != -1) {
      document.domain = "fastenal.com";
    }
  }
};
//Events.addEvent(window,"load",function () { Endeca.init(); });
//-----( END )-------------------------------------------------

// Cart.js
//-----( @ShoppingCart )---------------------------------------

// go to a location.. TODO - Convert this to FAST.gotoUrl
function gotoUrl(url) {
	window.location.href = url;
}

function saveInventoryOption(value) {
  Cookies.setCookie("INV_ON_ACCOUNT", value, "365", "/");
  window.location = window.location;
}

// Ajax Details page onSubmit
function updateCart( aForm) {
  var sProductDetailId = aForm.productDetailId.value;
  var sQty = aForm.qty.value;
  var sQtyPerPkg = aForm.qtyPerPkg.value;
  var sIsAvailableOnline = aForm.isAvailableOnline.value;
 
  var cartErrors = document.getElementById("addCartErrors");
    
  if (cartErrors != null && sQty != null) {
    if (isNaN(parseInt(sQty))) {
      cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be numeric</li><ul>";
      cartErrors.style.display = "block";	  
      return false;
    } else if ((sQty % 1) != 0) {
      cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be an integer</li><ul>";
      cartErrors.style.display = "block";	  
      return false;
    }else if (sQty <= 0) {
      cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be greater than zero</li><ul>";
      cartErrors.style.display = "block";	  
      return false;
    }
  }   
    
  var btnSubmit = aForm.elements["submit"];
  btnSubmit.disabled = "disabled";
  var sExec = "products.ex";
  var sParam = "dispatch=addToCart";
  var path = setPath( sExec, sParam );
  var params = "productDetailId=" + sProductDetailId +
               "&qty" + sProductDetailId + "=" + sQty;

  jQuery.get(path, params, function(response) {
    updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display');     //update the cart popup as well
    FAST.popupObject("newPopupWindow");
    return response;
  });
} //end updateCart

function addToCartSubmit(formName){
    var inputQty = document.getElementById('addCartQty').value;
    var aQty = document.getElementById('availableInvQty').value;
    var sku = document.getElementById('sku').value;
    var productId = document.getElementById('productId').value;
    var productType = document.getElementById('productType').value;
    
    if(isNaN(inputQty) || inputQty < 0 || parseInt(inputQty)!=inputQty){
        submitToCart(document.forms[formName]);
        return;
    }
    
    if(productType == 'C'){
        // sold out
        if(aQty < 1){
            alert("Product "+sku+" is out of stock.");
            return;
        }
        
        var cartQty = OrderPad.getCartItemQty(productId);
        // not enough
        if(aQty - cartQty - inputQty < 0){
            var leftQty = (aQty - cartQty)<0?0:(aQty - cartQty);
            if(leftQty == 0){
                //alert("Product "+sku+" is only "+aQty+" remaining and all of them are in your shopping cart.")
                alert("There is no additional inventory available for SKU "+sku+". This SKU will not be added to your shopping cart.");
                return;
            }
            if(confirm("Product "+sku+" is no longer available in the quantity you requested ("+inputQty+"). Would you like to change your order quantity to "+leftQty+"?")){
                document.getElementById('addCartQty').value = leftQty;
                submitToCart(document.forms[formName]);
            }else
                return;
        }else
            submitToCart(document.forms[formName]);
    }else
        submitToCart(document.forms[formName]);
}

function submitToCart(form){
    if(updateCart(form) == false){
        return;
    } 
    preventCartState = false;
}

// Tradeshow
function showDiv( p_sDivName ) {
  var aDiv = document.getElementById(p_sDivName);
  aDiv.style.display = "block";
}

function hideDiv( p_sDivName ) {
  var aDiv = document.getElementById(p_sDivName);
  aDiv.style.display = "none";
}
// End Tradeshow
  

//-----( Global functions )------------------------------------
var hideBgHandle;

function changeProtocol(obj, secure) {
  
  if (obj != null) {
    var linkHref = (secure ? "https://" : "http://");
    var protocolIndex = obj.href.indexOf(":");
  
    if (protocolIndex != -1) {
      linkHref += obj.href.substring(protocolIndex + 3);
      obj.href = linkHref;
    }
  }
}

function ajaxExceptionHandler(transport, e){
  try {
    if ( Ajax.getTransport()== false ) {
      //let the global handler deal with this.
      //todo need a better way to interact with global handler?
      return;
    }
  } catch(e) {
  }
  
  try {
    var hdr = 'Ajax Handler\n' 
            + 'An exception occurred. Provide this information to support.\n\n'
    var transportPart = 'State: ' + transport.readyState + "\n"
                      + 'Status: ' + transport.status + "\n\n";
    var exception = 'Exception Info\n     ' + e + '\n\n';
    try {
      var parts = 
          'Description:         ' + e.description + '\n' 
        + 'FileName:            ' + e.fileName + '\n' 
        + 'LineNumber:          ' + e.lineNumber + '\n' 
        + 'Message:             ' + e.message + '\n'
        + 'Name:                ' + e.name + '\n'
        + 'Number:              ' + e.number + '\n'
        + 'Prototype:           ' + e.prototype + '\n'
        + 'Stack:               ' + e.stack + '\n';
        
      var responseText = transport.responseText;      
    }  catch(e) {
    }
  
    var message = hdr + transportPart + exception + parts + '\n\n\n' + responseText;
    alert(message);
  } catch (e) {
  }
}

// open a popup window with params
function popupUrl(url, name, features) {
	var newWindow = window.open(url, name, features);
	newWindow.focus();
}

// toggle the visibility property -- combine with toggle function
function toggleVisibility(id) {
	var el = document.getElementById(id);
	if (el.style.visibility == "visible" 
	|| el.style.visibility == "") {
		el.style.visibility = "hidden";
	} else {
		el.style.visibility = "visible";
	}
	
}

// toggle the display property -- combine with toggle function
function toggleDisplay(id) {
	var el = document.getElementById(id);
	if (el.style.display == "block" 
	|| el.style.display == "") {
		el.style.display = "none";
	} else {
		el.style.display = "block";
	}
}

// encode urls
function urlEncode(str){
	str = escape(str);
	str = str.replace(new RegExp('\\+','g'),'%2B');
	return str.replace(new RegExp('%20','g'),'+');
} // urlEncode

// decode urls
function urlDecode(str){
	str = str.replace(new RegExp('\\+','g'),' ');
	return unescape(str);
} // urlDecode

// get the left n characters from a string
function left(str, n){
  if (n <= 0) {
	  return "";
	} else if (n > String(str).length) {
    return str;
	} else {
	  return String(str).substring(0, n);
  }
} // left

// get the right n characters from a string
function right(str, n){
  if (n <= 0) { 
    return "";
  } else if (n > String(str).length) {
    return str;
  } else {
    var iLen = String(str).length;
    return String(str).substring(iLen, iLen - n);
  }
} // right

// trim the leading and trailing spaces from a string
function trim(str) {
	str = str.replace(/^\s*|\s*$/g,"");
	return str;
} // trim

// looks in array for a specified value
function inArray(array, value) {
	for (var i=0; i<array.length; i++) {
		if (array[i] == value) {
			return true;
		}
	}
	return false;
}

// remove an element
function removeElement(el) {       
	if (el.parentNode) {
		el.parentNode.removeChild(el);
	}
} // removeElement

// insert content after an existing element
function insertAfter(newElement, existingElement) {
	var parentElement = existingElement.parentNode;
	if (parentElement.lastChild == existingElement) {
		return parentElement.appendChild(newElement);
	} else {
		return parentElement.insertBefore(newElement, existingElement.nextSibling);
	}
} // insertAfter

// this function is needed to work around 
// a bug in IE related to element attributes
function hasClass(obj) {
	var result = false;
	var classAttr = obj.getAttribute("class");
	if (classAttr != null) {
		result = classAttr.value;
	}
	return result;
}



// determine if the string is alpha numeric only
function isAlphaNumeric(string) {
  var matcher = string.match(/^\w+$/);
  if (matcher != null) { return true; } else { return false; }
} // isAlphaNumeric

// determines if the year is a leap year
function isLeapYear(year) {
  if (year%4 == 0 && year%100 != 0 || year%400 == 0) { return true; } else { return false; }
} // isLeapYear

// enable/disable elements
function enable(el) { document.getElementById(el.id).disabled = false; }
function disable(el) { document.getElementById(el.id).disabled = true; }
function enableThis(el) { el.disabled = false; }
function disableThis(el) { el.disabled = true; }

//-----( END )-------------------------------------------------


//-----( @Prototypes )-----------------------------------------
// Summary: prototype implementations of existing javascript functions

// prototype implementation of the trim function
String.prototype.trim = function() {
  var x = this;
  return trim(x);
}

// prototype implementation of the left function
String.prototype.left = function(n) {
	var x = this;
	return left(x, n);
};

// prototype implementation of the right function
String.prototype.right = function(n) {
	var x = this;
	return right(x, n);
};

Array.prototype.inArray = function(n) {
	var x = this;
	return inArray(x, n);
};

Array.prototype.shuffle = function() {
  var len = this.length;
  var rand, temp, i;
  for (i = 0; i < len; i++){
    rand = Math.floor(Math.random() * len);
    temp = this[i];
    this[i] = this[rand];
    this[rand] = temp;
  }
};

Array.prototype.copy = function() {
  return this.slice();
};

Array.prototype.indexOf = function(value) {
  var i = 0;
  while(i < this.length){
    if(this[i] == value) return i;
    i++;
  }
  return -1;
}

Array.prototype.lastIndexOf = function(value) {
  var i = this.length;
  while (--i){
    if (this[i] == value) {
			return i;
		}
  }
  return -1;
}
//-----( END )-------------------------------------------------


// determines if the link has a # in it, then highlights the area
function doHighlight(href) {
  if (href.indexOf('#') != -1) {
    var pos = href.indexOf('#');
    pos = href.length - pos;
    href = right(href, pos -1);
    new Effect.Highlight(href);
  }
}


// sets the value of a select list
function setSelected(el, value) {
  var listObj = document.getElementById(el);
  var length = listObj.length;
  for (var i=0; i<length; i++) {
    if (listObj.options[i].text == value
    || listObj.options[i].value == value) {
      listObj.options[i].selected = true;
    }
  }
} // setSelected


// show MSDS popup window
function viewMsds(url) {
	var name = "fcom_msds_popup";
	var features = "width=785,height=589,";
	features += "directories=no,location=yes,menubar=yes,";
  features += "resizable=yes,scrollbars=yes,status=yes,toolbar=yes";
	popupUrl(url, name, features);
} // viewMsds


// IE6 only, all other browsers will ignore.
// This is used to imitate the css :hover 
// use: applyHover(document.getElementById("NAMEOFCONTAINER"), 'TYPEOFTAG');
// css mod: #NAMEOFCONTAINER TYPEOFTAG:hover {} -> #NAMEOFCONTAINER TYPEOFTAG:hover, #NAMEOFCONTAINER TYPEOFTAG.hover {} 
function applyHover(container, tagType){
  if (document.all&&container.getElementsByTagName&&!window.XMLHttpRequest) {
    var elementsToHover = container.getElementsByTagName(tagType);
    for (i=0; i<elementsToHover.length; i++) {
      node = elementsToHover[i];
      node.onmouseover=function() {
        this.className+=" hover";
      }
      node.onmouseout=function() {
        this.className=this.className.replace(" hover", "");
      }
    }
  }
}// applyHover


function checkTimeOut(errorHTML, redirect) {
	errorHTML = errorHTML.stripTags();
	errorHTML = errorHTML.strip();
	var timeout = false;
	errorHTML.scan(/\w+/, function(match){ if(match[0] == 'timeout') timeout = true; });
	if (timeout == true){
		var sURL = redirect; //'../accounts.ex';
		window.location.href = sURL;
		return false;
	}
	return true;
} //end checkTimeOut

function checkResponseForErrors(transport) {
	var status = true;
	
	try{
    var urlLocation = transport.getResponseHeader("Content-Location");
    //alert(urlLocation);
    if (urlLocation.indexOf('login') > 0){
      //window.location.href = '/web/products.ex';
      var pageFrom = "?pageFrom=" + document.getElementById('pageFrom').value;
      var sURL = SITE_ROOT + 'login/signin.ex';
      window.location.href = sURL + pageFrom;
      status = false;
    }
  }catch (e){
    
  }finally{
    return status;
  }
  
  
	
} //end checkResponseForErrors


function handleErrorForwarding(urlLocation){
	
	  if (urlLocation.indexOf('products') > 0){
		window.location.href = SITE_ROOT + 'products.ex';
	  }
	
	
	  if (urlLocation.indexOf('pohistory') > 0){
		window.location.href = SITE_ROOT + 'history.ex';
	  }
		
		
	  if (urlLocation.indexOf('login') > 0){
		var pageFrom = "?pageFrom=" + document.getElementById('pageFrom').value;
		var sURL = SITE_ROOT + 'login/signin.ex';
		window.location.href = sURL + pageFrom;
	  }
	
}

  function showPopInBackground(){
    try{
        if(hideBgHandle){
          //clear setInterval for hiding bg see hidePopInBackground()
          clearInterval(hideBgHandle);
          hideBGHanle=null;
        }//end if
    }catch(e){
    }

  document.getElementById("shadeOutBackground").style.visibility = 'visible';
  document.getElementById("loadingBar").style.display = 'block';
  //when the background is made visible, IE6 needs this to make it fill up the whole page
  if (!window.XMLHttpRequest) {//IE6 and other older browsers only
    //var wrapHeight = document.getElementById("wrap").getHeight() + 'px';
    var wrapHeight = 1000;//window.screen.availHeight;
    document.getElementById("shadeOutBackground").style.height = wrapHeight;
    document.getElementById("shadeOutBackground").style.position = "absolute";
    document.getElementById("loadingBar").style.height = wrapHeight;
    document.getElementById("loadingBar").style.position = "absolute";
  }
} //end showPopInBackground


function hidePopInBackground() {
  //alert('hidePopInBackground begin');
  //document.getElementById("shadeOutBackground").style.visibility = 'hidden';
  //document.getElementById("loadingBar").style.display = 'none';
  //alert('hidePopInBackground end');
  
  //ensure background is hidden by looping until it is.
  hideBgHandle = setInterval (hidePopInBackgroundInterval,500);
}
//run repeatedly until the background is hidden
//once hidden exectute clearInterval
function hidePopInBackgroundInterval(){
  document.getElementById("shadeOutBackground").style.visibility = 'hidden';
  document.getElementById("loadingBar").style.display = 'none';
  if(isBackgroundHidden() ){
    clearInterval(hideBgHandle);
    hideBgHandle=null;
  };
}
//returns true if pop in bg is hidden
function isBackgroundHidden(){
  if (document.getElementById("shadeOutBackground").style.visibility == 'hidden'
      && document.getElementById("loadingBar").style.display == 'none'){
      return true;
  }else{
    return false;
  }
}

function openPopIn(section, clickedElement) {
  showPopInBackground();    
  document.getElementById(section + "PopIn").centerOn(clickedElement);
  Effect.Appear(section + "PopIn", {duration:.5});
  Effect.Fade("loadingBar", {duration:.5});
  document.getElementById("display" + section + "Errors").innerHTML = "";
  if (document.getElementById(section + "Errors") != null) {
    document.getElementById(section + "Errors").innerHTML = ""; 
  }
}


function popupEdit(section) {
  openPopIn(section, document.getElementById(section));
}


function sendSavePopIn(section, url, formSubmitted) {
  disable(document.getElementById('submit' + section));
  if ( formSubmitted == null ) {
    formSubmitted = document.getElementById("form" + section);
  }
  
  if ( document.getElementById(section + "PopIn") != null ) {
    Effect.Fade(section + "PopIn", {duration:.2});
  }
  
  Effect.Appear("loadingBar", {duration:.2});
  document.getElementById('temp' + section).innerHTML = '';
  new Ajax.Updater( {success:'temp' + section}
                  , url
                  , { 
                      asynchronous:true
                    , parameters:Form.serialize(formSubmitted)
                    , onComplete:function(transport){savePopIn(transport, section);}
                    , onException:function(transport,e ){failedSendSavePopIn(transport, section,e);} 
                    
                    } );
} //end sendSavePopIn


function savePopIn(transport, section) {
  //alert('save popIn: ' + section);
	var response = transport.responseText;
	//alert("response: " + response);
  //alert('savePopin: ' + transport.status);
  
  if (transport.status>1000){
    //alert('savePopin abort, crazy status code: ' + transport.status);
    failedPopIn(transport, section, 'Status code: ' + transport.status);
    return;
  }
  
  try{
  if (document.getElementById('temp' + section).innerHTML != null && document.getElementById('temp' + section).innerHTML != '') {
		var errorHTML = 'none';
		if (document.getElementById(section + "Errors") != null) { 
			errorHTML = document.getElementById(section + "Errors").innerHTML; 
		}
		errorHTML = errorHTML.stripTags();
		errorHTML = errorHTML.strip();
    //alert('check transport for errors');
		if (checkResponseForErrors(transport)) {
			if (errorHTML == "none") {
				document.getElementById(section).innerHTML = document.getElementById('temp' + section).innerHTML;
				Effect.Fade(section + "PopIn", {duration:.5});
				Effect.Fade("loadingBar", {duration:.5});
				setTimeout("popInCleanup('" + section + "', true)", 500);
			} else {
				Effect.Appear(section + "PopIn", {duration:.5});
				Effect.Fade("loadingBar", {duration:.5});
				document.getElementById("display" + section + "Errors").innerHTML = document.getElementById(section + "Errors").innerHTML;
				document.getElementById("display" + section + "Errors").style.display = "block";
			}
			document.getElementById(section + "Errors").innerHTML = "";
			document.getElementById('temp' + section).innerHTML = "";
		}
		enable(document.getElementById('submit' + section));
	} else { //something failed in the ajax call, clean up the code
		//alert("failedPopIn was called from savePopIn."+ "\n response: " + response); //Error tracking
    failedPopIn(transport, section);
	}
  }catch(e){
    //throw e;
  }finally{
    //alert('finally');
  }
} //end savePopIn

function failedSendSavePopIn(transport, section,e) {
  failedPopIn(transport, section,e);
  if(e){
    //setTimeout("popInCleanup('" + section + "', true)", 500);
    hidePopInBackground();
  }
}


function failedPopIn(transport, section,e) {
  //alert('failed popin');
  enable(document.getElementById('submit' + section));
	ajaxExceptionHandler(transport, e);
  popInCleanup( 'failed', false );
  
  
  
  
  //throw e;
  //todo, reset form?
}


function cancelPopIn(section) {
  Effect.Fade(section + "PopIn", {duration:.5});
  document.getElementById("shadeOutBackground").style.visibility = 'hidden';

  document.getElementById("form" + section).reset();

  setTimeout("popInCleanup('" + section + "', false)", 500);
}


function resetDefaultValues(form) {
  var iMaxElements = form.elements.length;
  for (var i = 0; i < iMaxElements; i++) {
    myType = form.elements[i].type;
    if (myType == 'checkbox' || myType == 'radio') {
      form.elements[i].defaultChecked = form.elements[i].checked;
    }
    
    if (myType == 'hidden' || myType == 'password' || myType == 'text' || myType == 'textarea') {
      form.elements[i].defaultValue = form.elements[i].value;
    }
    
    if (myType == 'select-one' || myType == 'select-multiple') {
      var iMaxElementsOptions = form.elements[i].options.length;
      for (var j = 0; j < iMaxElementsOptions; j++) {
        form.elements[i].options[j].defaultSelected = form.elements[i].options[j].selected;
      }
    }
  }
} //end resetDefaultValues


function copyAllValues(className, newValue) {
  if(confirm('Are you sure you want to update all values to: ' + newValue + '?')){
		var classInputs = getElementsByClassName(className, "input");
//		classInputs.each(function(classInput) {
//      classInput.value = newValue;
//		});
                for(i=0;i<classInputs.length;i++)
                    classInputs[i].value = newValue;
  }
}


//Error tracking
function exceptionInSendSavePopIn() {
  alert("There was an exception in sendSavePopIn.")
}

function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function findPos(obj) {
  var curleft = 0;
  var curtop = 0;
  
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent); /* this line is correct, this will return false when obj.offsetParent == 'HTML' */
    
    return [curleft, curtop];
  }
}

//create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
	//target is what you want it to go after. Look for this elements parent.
	var parent = targetElement.parentNode;
	
	//if the parents lastchild is the targetElement...
	if(parent.lastchild == targetElement) {
		//add the newElement after the target element.
		parent.appendChild(newElement);
		} else {
		// else the target has siblings, insert the new element between the target and it's next sibling.
		parent.insertBefore(newElement, targetElement.nextSibling);
		}
}

function rmWhiteSpace(str) {
    spaceFree = str.replace(/\s+/g,'');
 
    return spaceFree;   
}

// Creates the isContainedIn function
if ( !window.Element ) {
	Element = function() {};
  
  var element = new Element;
  _isContainedIn = element.isContainedIn;
}

function showPopup(ref) {
  var location = ref.getAttribute("href");
  
  if (location != null || location != "") {
    var name = "fcom_help_popup";
    var features = "width=500,height=400,";
    features += "directories=no,location=no,menubar=no,";
    features += "resizable=no,scrollbars=yes,status=yes,toolbar=no";
    popupUrl(location, name, features);
    
  }
    
  return false;
}

function SetAllCheckboxes(FormName, FieldName, CheckValue) {
    // Required: FormName = The name of the form that will have Checkboxes modified.
    // Required: FieldName = The name of the checkboxes that will be modified.
    // Required: CheckValue = true(selected) or false(deselected)
    if (!document.forms[FormName]) return;
    var objCheckBoxes = document.forms[FormName].elements[FieldName];
    if (!objCheckBoxes) return;
    var countCheckBoxes = objCheckBoxes.length;
    if (!countCheckBoxes) objCheckBoxes.checked = CheckValue;
    else {
        for(var count=0;count<countCheckBoxes;count++) {
        objCheckBoxes[count].checked = CheckValue;
        }
    }
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function setPath( sExec , sParam ) {
  var fullPath = window.location.toString();
  var endLocation = fullPath.indexOf(SITE_ROOT, SITE_ROOT.length);
  var newPath = SITE_ROOT + sExec + "?" + sParam;
      
  return newPath;
}

function getStyle(elem, name) {
    // J/S Pro Techniques p136
  if (elem) {
    if (elem.style[name]) {
        return elem.style[name];
    } else if (elem.currentStyle) {
        return elem.currentStyle[name];
    }
    else if (document.defaultView && document.defaultView.getComputedStyle) {
        name = name.replace(/([A-Z])/g, "-$1");
        name = name.toLowerCase();
        s = document.defaultView.getComputedStyle(elem, "");
        return s && s.getPropertyValue(name);
    } else {
        return null;
    }
  }
}

function preloadImage(path) {
  pic1= new Image(100,100); 
  pic1.src= path; 
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function isVisible(e) {
  //returns true is should be visible to user.
  if (typeof e == "string") {
    e = document.getElementById(e);
  }
  while (e.nodeName.toLowerCase() != 'body' && e.style.display.toLowerCase() != 'none' && e.style.visibility.toLowerCase() != 'hidden') {
    e = e.parentNode;
  }
  if (e.nodeName.toLowerCase() == 'body') {
    return true;
  } else{
    return false;
  }
}

function getParameter(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function popWindow(D,C,E,B) {
  var A=(screen.width-E)/2;
  var H=(screen.height-B)/2;
  var F="height="+B+",width="+E+",screenX="+A+",left="+A+",screenY="+H+",top="+H+",location=no,scrollbars=yes,menubar=no,resizable=no,status=no,toolbar=no";
  var G=window.open(D,C,F);
  G.focus();
}

// Container object for global variables
var FASTENAL = {};

//Cart summary	
FASTENAL.globalCurrent;	// global references to current element
FASTENAL.globalRelated;
FASTENAL.current;	// setTimeout() call for cart summary delay
FASTENAL.related;
FASTENAL.time;

var preventCartState = false;

var fastenal = {
    byId: function(obj) {
        return document.getElementById(obj);
    },
    
    byClass: function(obj) {
        return getElementsByClassName(obj);
    },
    
    gotoUrl: function(url) {
        window.location = url;
    },
    
    toggle: function(obj, link) {
        obj = document.getElementById(obj);

        if (obj) {
          if (getStyle(obj,"display") == "block")
              obj.style.display = "none";
          else obj.style.display = "block";

          i = 0;
          
          // toggles max/min child nodes if present
          if (link) {
            for (i=0;i<link.childNodes.length;i++) {
                if (link.childNodes[i].className == "maximize") {
                    link.childNodes[i].className = "minimize";
                } else if (link.childNodes[i].className == "minimize") {
                    link.childNodes[i].className = "maximize";
                }
            }
          }
        }        
    },
    
    setAllCheckboxes: function(FormName, FieldName, CheckValue) {
        SetAllCheckboxes(FormName, FieldName, CheckValue);
    },
    
    enableOn: function(str, obj, target) {
        if (obj.value == str) {
            target.disabled = false;
            target.focus();
        } else {
            target.value = "";
            target.disabled = true;
        }
    }
};

// Proof of Concept Stuff
function framework_popin(url, height, width, title) {
  try {
    jQuery.get(url, function(response) {
      FAST.popupObject("newPopupWindow", "framework_popup", response, height, width, title);
      //Help.init();
      loadScript();
    });
  } catch(e) {
    console.error(e);
    return true;
  }
  return false;
}

function ShowColdHeadingVideo() {
    var response = "<div id=\"video-preview\" class=\"center\"></div>",
        title = "";

    FAST.popupObject("newPopupWindow", "framework_popup", response, 325, 375, title);
    
    var s1 = new SWFObject('http://ecorptv.com/mediaplayer.swf','player','320','260','9');
    
    s1.addParam('wmode','transparent');
    s1.addParam('allowfullscreen','true');
    s1.addParam('allowscriptaccess','always');
    
    var meta = 'id=90900&thumbnailurl=http://ecorptv.com/thumb/1_90900.jpg';
    s1.addParam('flashvars','image=http://ecorptv.com/thumb/1_90900.jpg&file=http://server1.ecorptv.com/flvideo/90900.flv&id=' + escape(meta));
    s1.write('video-preview');
}

function framework_popout(element) {
  FAST.popupObject("newPopupWindow");

  return false;
} // END Proof of Concept

// Store Availability Search on details.ex
function doSearch(formInfo, output) {
  formInfo = document.getElementById(formInfo) || formInfo;
  output = document.getElementById(output) || output;
  
  if (typeof formInfo == 'object' && typeof output == 'object') {
    Forms.fixSubmit(formInfo);
    var sExec = formInfo.getAttribute("action");
    var sParam = "";
    
    for (var i=0;i<formInfo.length;i++) {
      if (formInfo.elements[i].name == "fAction") {
        formInfo.elements[i].name = "action"; // fixes a bug in ie7 where formInfo.action = object insead of action path
      }
      if ((formInfo.elements[i].value != "") && (formInfo.elements[i].type != "submit")) {
        sParam += formInfo.elements[i].name.trim() + "=" + formInfo.elements[i].value.trim() + "&";
      }
      else if (formInfo.elements[i].type == "checkbox") {
        if (formInfo.elements[i].checked) {
          sParam += formInfo.elements[i].name.trim() + "=true&";
        }
        else {
          sParam += formInfo.elements[i].name.trim() + "=false&";
        }
      }

      
    }
    
    var path = sExec + "?" + sParam;
    path = path.replace(/ /g,"%20");
    
    jQuery(output).load(path, function() { 
      Forms.fixSubmit(formInfo);
      Help.init();
    });
    return false;
  }
}

function setServicingStore(servicingStore) {
  var newStore = document.getElementById(servicingStore),
      target = document.getElementById("ajxServicingStore");
  
  if (newStore != null && target != null) {
    target.innerHTML = newStore.innerHTML;
    
    framework_popout(this);
    return false;
  }
  
  return true;
}

// Sets a store in the cookie for store locator
function populateBack(storeCode){
    var sExec = "/products/searchStoreForProd.ex";
    var sParam = "dispatch=selectStore&storeCode=" + storeCode;

    var path = setPath( sExec, sParam );
    
    jQuery.get(path,"",function(response) {
      var container = document.getElementById("storeInfoContainer");
	    alert(storeCode + " is now your local store");
      
      if (container === null) {
        var parent = document.getElementById("hdrStoreLocator");
        
        container = document.createElement("a");
        container.id = "storeInfoContainer";
        container.className = "supplementaryText";
        parent.appendChild(container);
      }
      
      document.getElementById("storeInfoContainer").href = SITE_ROOT + "/storeInfo.ex?branch=" + storeCode + "&requestType=search";
	    document.getElementById("storeInfoContainer").innerHTML = response;	
      bProcessingAutoComp = false;
      return response;
    });

    return false;
}

// Stores.js
function populateStoreColumn(p_sLastVal) {
    var params = 'action=search&zip=' + p_sLastVal;
    //alert(params);
    new Ajax.Updater( 'divStoreResults'
                    , SITE_ROOT + 'locations.ex'
                    , { asynchronous:true
                      , parameters:params
                      , onComplete:function(transport){ displayStoreResults(transport); } 
                      , onException:function(transport,e){ ajaxExceptionHandler(transport, e); } 
                      } 
                    );  //todo ignore exceptions later.  just take out
  //} //end if-else
} //end doFinalAutoComp


function displayStoreResults(transport) {
  var response = transport.responseText;
  var urlLocation = transport.getResponseHeader("Content-Location");
  var hack = transport.hack;
  //alert('urlLocation: ' + urlLocation);
  
  //alert('response:' + response);
  
  document.getElementById("divStoreResults").innerHTML = response;
  
  //todo check if some value in response whether to display the div 
  

} //end displayAutoCompResult

/*
Table sorting script  by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .

Copyright (c) 1997-2007 Stuart Langridge, Joost de Valk.

Version 1.5.7
*/

/* You can change these values */
var image_path = SITE_ROOT + "common/images/icons/";
var image_up = "ico-arrow-asc.gif";
var image_down = "ico-arrow-desc.gif";
var image_none = "ico-sort.gif";
var europeandate = true;
var alternate_row_colors = true;

/* Don't change anything below this unless you know what you're doing */
addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;
var thead = false;

function sortables_init() {
	// Find all tables with class sortable and make them sortable
	if (!document.getElementsByTagName) return;
	tbls = document.getElementsByTagName("table");
	for (ti=0;ti<tbls.length;ti++) {
		thisTbl = tbls[ti];
		if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
			ts_makeSortable(thisTbl);
		}
	}
}

function ts_makeSortable(t) {
	if (t.rows && t.rows.length > 0) {
		if (t.tHead && t.tHead.rows.length > 0) {
			var firstRow = t.tHead.rows[t.tHead.rows.length-1];
			thead = true;
		} else {
			var firstRow = t.rows[0];
		}
	}
	if (!firstRow) return;
	
	// We have a first row: assume it's the header, and make its contents clickable links
	for (var i=0;i<firstRow.cells.length;i++) {
		var cell = firstRow.cells[i];
		var txt = ts_getInnerText(cell);
		if (cell.className != "unsortable" && cell.className.indexOf("unsortable") == -1) {
			cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this, '+i+');return false;">'+txt+'<span class="sortarrow">&nbsp;&nbsp;<img src="'+ image_path + image_none + '" alt="&darr;"/></span></a>';
		}
	}
	if (alternate_row_colors) {
		alternate(t);
	}
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk, clid) {
	var span;
	for (var ci=0;ci<lnk.childNodes.length;ci++) {
		if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
	}
	var spantext = ts_getInnerText(span);
	var td = lnk.parentNode;
	var column = clid || td.cellIndex;
	var t = getParent(td,'TABLE');
	// Work out a type for the column
	if (t.rows.length <= 1) return;
	var itm = "";
	var i = 0;
	while (itm == "" && i < t.tBodies[0].rows.length) {
		var itm = ts_getInnerText(t.tBodies[0].rows[i].cells[column]);
		itm = trim(itm);
		if (itm.substr(0,4) == "<!--" || itm.length == 0) {
			itm = "";
		}
		i++;
	}
	if (itm == "") return; 
	sortfn = ts_sort_caseinsensitive;
	if (itm.match(/^\d\d[\/\.-][a-zA-z][a-zA-Z][a-zA-Z][\/\.-]\d\d\d\d$/)) sortfn = ts_sort_date;
	if (itm.match(/^\d\d[\/\.-]\d\d[\/\.-]\d\d\d{2}?$/)) sortfn = ts_sort_date;
	if (itm.match(/^-?[?$???]\d/)) sortfn = ts_sort_numeric;
	if (itm.match(/^-?(\d+[,\.]?)+(E[-+][\d]+)?%?$/)) sortfn = ts_sort_numeric;
	SORT_COLUMN_INDEX = column;
	var firstRow = new Array();
	var newRows = new Array();
	for (k=0;k<t.tBodies.length;k++) {
		for (i=0;i<t.tBodies[k].rows[0].length;i++) { 
			firstRow[i] = t.tBodies[k].rows[0][i]; 
		}
	}
	for (k=0;k<t.tBodies.length;k++) {
		if (!thead) {
			// Skip the first row
			for (j=1;j<t.tBodies[k].rows.length;j++) { 
				newRows[j-1] = t.tBodies[k].rows[j];
			}
		} else {
			// Do NOT skip the first row
			for (j=0;j<t.tBodies[k].rows.length;j++) { 
				newRows[j] = t.tBodies[k].rows[j];
			}
		}
	}
	newRows.sort(sortfn);
	if (span.getAttribute("sortdir") == 'down') {
			ARROW = '&nbsp;&nbsp;<img src="'+ image_path + image_down + '" alt="&darr;"/>';
			newRows.reverse();
			span.setAttribute('sortdir','up');
	} else {
			ARROW = '&nbsp;&nbsp;<img src="'+ image_path + image_up + '" alt="&uarr;"/>';
			span.setAttribute('sortdir','down');
	} 
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0; i<newRows.length; i++) { 
		if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) {
			t.tBodies[0].appendChild(newRows[i]);
		}
	}
    // do sortbottom rows only
    for (i=0; i<newRows.length; i++) {
		if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) 
			t.tBodies[0].appendChild(newRows[i]);
	}
	// Delete any other arrows there may be showing
	var allspans = document.getElementsByTagName("span");
	for (var ci=0;ci<allspans.length;ci++) {
		if (allspans[ci].className == 'sortarrow') {
			if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
				allspans[ci].innerHTML = '&nbsp;&nbsp;<img src="'+ image_path + image_none + '" alt="&darr;"/>';
			}
		}
	}		
	span.innerHTML = ARROW;
	alternate(t);
}

function getParent(el, pTagName) {
	if (el == null) {
		return null;
	} else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) {
		return el;
	} else {
		return getParent(el.parentNode, pTagName);
	}
}

function sort_date(date) {	
	// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
	dt = "00000000";
	if (date.length == 11) {
		mtstr = date.substr(3,3);
		mtstr = mtstr.toLowerCase();
		switch(mtstr) {
			case "jan": var mt = "01"; break;
			case "feb": var mt = "02"; break;
			case "mar": var mt = "03"; break;
			case "apr": var mt = "04"; break;
			case "may": var mt = "05"; break;
			case "jun": var mt = "06"; break;
			case "jul": var mt = "07"; break;
			case "aug": var mt = "08"; break;
			case "sep": var mt = "09"; break;
			case "oct": var mt = "10"; break;
			case "nov": var mt = "11"; break;
			case "dec": var mt = "12"; break;
			// default: var mt = "00";
		}
		dt = date.substr(7,4)+mt+date.substr(0,2);
		return dt;
	} else if (date.length == 10) {
		if (europeandate == false) {
			dt = date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
			return dt;
		} else {
			dt = date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
			return dt;
		}
	} else if (date.length == 8) {
		yr = date.substr(6,2);
		if (parseInt(yr) < 50) { 
			yr = '20'+yr; 
		} else { 
			yr = '19'+yr; 
		}
		if (europeandate == true) {
			dt = yr+date.substr(3,2)+date.substr(0,2);
			return dt;
		} else {
			dt = yr+date.substr(0,2)+date.substr(3,2);
			return dt;
		}
	}
	return dt;
}

function ts_sort_date(a,b) {
	dt1 = sort_date(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
	dt2 = sort_date(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
	
	if (dt1==dt2) {
		return 0;
	}
	if (dt1<dt2) { 
		return -1;
	}
	return 1;
}
function ts_sort_numeric(a,b) {
	var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
	aa = clean_num(aa);
	var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
	bb = clean_num(bb);
	return compare_numeric(aa,bb);
}
function compare_numeric(a,b) {
	var a = parseFloat(a);
	a = (isNaN(a) ? 0 : a);
	var b = parseFloat(b);
	b = (isNaN(b) ? 0 : b);
	return a - b;
}
function ts_sort_caseinsensitive(a,b) {
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
	if (aa==bb) {
		return 0;
	}
	if (aa<bb) {
		return -1;
	}
	return 1;
}
function ts_sort_default(a,b) {
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
	if (aa==bb) {
		return 0;
	}
	if (aa<bb) {
		return -1;
	}
	return 1;
}
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,	NS6 and Mozilla
// By Scott Andrew
{
	if (elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent){
		var r = elm.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be removed");
	}
}
function clean_num(str) {
	str = str.replace(new RegExp(/[^-?0-9.]/g),"");
	return str;
}
function trim(s) {
	return s.replace(/^\s+|\s+$/g, "");
}
function alternate(table) {
	// Take object table and get all it's tbodies.
	var tableBodies = table.getElementsByTagName("tbody");
	// Loop through these tbodies
	for (var i = 0; i < tableBodies.length; i++) {
		// Take the tbody, and get all it's rows
		var tableRows = tableBodies[i].getElementsByTagName("tr");
		// Loop through these rows
		// Start at 1 because we want to leave the heading row untouched
		for (var j = 0; j < tableRows.length; j++) {
			// Check if j is even, and apply classes for both possible results
			if ( (j % 2) == 0  ) {
				if ( !(tableRows[j].className.indexOf('odd') == -1) ) {
					tableRows[j].className = tableRows[j].className.replace('odd', 'even');
				} else {
					if ( tableRows[j].className.indexOf('even') == -1 ) {
						tableRows[j].className += " even";
					}
				}
			} else {
				if ( !(tableRows[j].className.indexOf('even') == -1) ) {
					tableRows[j].className = tableRows[j].className.replace('even', 'odd');
				} else {
					if ( tableRows[j].className.indexOf('odd') == -1 ) {
						tableRows[j].className += " odd";
					}
				}
			} 
		}
	}
}
/* End of Table sorting script  by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
Copyright (c) 1997-2007 Stuart Langridge, Joost de Valk. */

// Popup.js
var Popup = {
  Dropdown: function(name, target, hide, state) {
    var obj = document.getElementById(name) || Popup.Create(name);
    var target = document.getElementById(target);

    if (state) {
      Popup.show(obj,target);
    } else if (state == false) {
      Popup.hide(obj,target);    
    } else if (target) {
      if (Popup.Toggle(target, hide)) {
        styleClick(obj,target);
        Popup.PositionDropdown(obj,target);
      } else {
        styleClick(obj,target);
      }
    }
  },
  
  AutoComplete: function(name, parent, response, show) {
    var obj = document.getElementById(name) || Popup.Create(name);
    var parent = document.getElementById(parent);
    
    //Popup.addEvent(document,"click",function(e){Popup.CheckMouseTarget(e,name);});  
    document.onclick = function(e){Popup.CheckMouseTarget(e,name);};

    if (show == 'false') obj.style.display = 'none'
    else {
      Popup.PositionAutoComplete(obj,parent);
      obj.style.display = 'block';
      obj.innerHTML = response;
    }
  },
  
  Create: function(name) {
    var obj = document.createElement('div');
    obj.setAttribute("id",name);
    obj.style.display = 'none';
    document.body.appendChild(obj);
    
    return obj;
  },
  
  Delete: function(name) {
      var deleteThis = document.getElementById(name) || 0;
      if (deleteThis) document.body.removeChild(deleteThis);
  },
  
  Toggle: function(obj, hide) {
    if (obj.style.display != 'none') {
      Popup.HideAll(obj,hide);
      obj.style.display = 'none';
      return false;
    } else {
      Popup.HideAll(obj,hide);
      obj.style.display = 'block';
      return true;
    }
  },
  
  show: function(obj, target) {
    obj = document.getElementById(obj) || obj;
    target = document.getElementById(target) || target;
    
    obj.className = "pseudoLink boxOn";
    target.style.display = 'block';
    Popup.PositionDropdown(obj,target);
  },
  
  hide: function(obj, target) {
    obj = document.getElementById(obj) || obj;
    target = document.getElementById(target) || target;
    
    obj.className = "pseudoLink cart";
    target.style.display = 'none';
    Popup.Delete(obj.id + "-hide-me");
  },
  
  HideAll: function(obj,hide) {
      // Hides all other divs... TODO clean this code.
      if (hide) {
        var byClass = getElementsByClassName(obj.className);
    
        for (i=0;i<byClass.length;i++) {
            document.getElementById("link" + byClass[i].id).className = "pseudoLink";
            Popup.Delete("link" + byClass[i].id + "-hide-me");
            byClass[i].style.display = 'none';
        }
      }
  },
  
  PositionDropdown: function(obj,target) {
    var position = Popup.findPos(obj);
    var offset = [obj.offsetWidth, obj.offsetHeight];
    
    var style = 'position: absolute;';
    style += 'right: ' + (document.documentElement.clientWidth - position[0] - offset[0]) + 'px;';
    style += 'top: ' + (position[1] + offset[1]) + 'px;';
    
    if (document.documentElement.clientWidth < 991) {
      style += 'right: ' + (991 - position[0] - offset[0]) + 'px;';
    }
  
    // set styles
    target.setAttribute("style",style);
    target.style.cssText = style;
    
    //create and place hidden bar
    var hiddenBar = document.getElementById(obj.id + "-hide-me") || Popup.Create(obj.id + "-hide-me");
    
    style = 'position: absolute;';
    style += 'left: ' + (position[0]) + 'px;';
    style += 'top: ' + (position[1] + offset[1]) + 'px;';
    style += 'z-index: 99;';
    style += 'width: ' + (obj.offsetWidth - 1) + 'px;';
    style += 'border-top: #fffbd2 1px solid;';

    hiddenBar.setAttribute("style",style);
    hiddenBar.style.cssText = style;
    
    Popup.ScrollTo(obj, target)
  },
  
  PositionAutoComplete: function(obj,parent) {
    var position = Popup.findPos(parent);
    var offset = [parent.offsetWidth, parent.offsetHeight];
    
    var style = 'position: absolute;';
    style += 'left: ' + (position[0] + 1) + 'px;';
    style += 'top: ' + (position[1] + offset[1]) + 'px;';
    style += 'width: ' + (offset[0] + 20-3)  + 'px;';
    style += 'max-height: 250px; overflow:auto; background:white;border:1px solid #c8ccce;';
    
    // for ie6 max-height
    if (document.documentElement && typeof document.documentElement.style.maxHeight=="undefined") style += 'height: 175px;';
    
    // set styles
    obj.setAttribute("style",style);
    obj.style.cssText = style;
  },
  
  ScrollTo: function(obj,target) {
    // Scrolls down to make sure popup fits window. TODO clean this code
    var offset = getScrollXY();
    var windowSize = Window.getWindowSize();
    var popBottom = Popup.findPos(target)[1] + target.offsetHeight;
    
    if ((offset[1] + windowSize[1]) < popBottom) {
        window.scrollBy(0,popBottom-(offset[1] + windowSize[1])+ 10);
    }
  },
  
  CheckMouseTarget: function(e, name) {
    e = e || window.event;
    target = e.target || e.srcElement;
    var hide = true;
    
    do {
      if (target.id == name) hide = false;
    } while(target = target.parentNode);
    
    if (hide) document.getElementById(name).style.display = 'none';
  },

  addEvent: function ( obj, type, fn ) {
    if (obj.addEventListener)
      obj.addEventListener( type, fn, false );
    else if (obj.attachEvent) {
      obj["e"+type+fn] = fn;
      obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
      obj.attachEvent( "on"+type, obj[type+fn] );
    }
  },

  findPos: function(obj) {
    var curleft = 0;
    var curtop = 0;
    
    if (obj.offsetParent) {
      do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent); /* this line is correct, this will return false when obj.offsetParent == 'HTML' */
      
      return [curleft, curtop];
    }
  }
}

// Special Pricing Popup
function togglePD(sku, target) {
  var obj = document.getElementById("pd" + sku);
  
  var offset = [target.offsetWidth, target.offsetHeight];
  var windowSize = Window.getWindowSize();
  var targetPos = Window.getElementPosition(target,1);
  
  if (obj) {
    if (obj.style.display == "none") {
      var byClass = getElementsByClassName(obj.className);
      for (i=0;i<byClass.length;i++) { // hide all popups with the same class
        byClass[i].style.display = 'none';
      }
    
      obj.style.display = "";
      obj.style.top = (targetPos[1] + offset[1]) + "px";
      obj.style.left = (targetPos[0] - offset[0]) + "px";
    } else {
      obj.style.display = "none";
    }
  }
}

/*****( BEGIN - @Pagination )********************************/
function handleProductsRoot(curUrl) {
  return curUrl.replace("products.ex&", "products.ex?");
}

function addParamToUrl(curUrl, paramName, paramValue)
{
	var res = '';
	var paramToCheck = paramName + '='; 
	var ind1 = curUrl.indexOf("?");
	var ind2 = curUrl.lastIndexOf(paramToCheck);
	if (ind1 >= 0 && ind2 >= 0)
	{
		var ind3 = curUrl.indexOf("&", ind2);
		if (ind3 >= 0)
		{	
			res = curUrl.substring(0, ind2) + paramToCheck + paramValue + curUrl.substring(ind3); 
		}
		else
		{
			res = curUrl.substring(0, ind2) + paramToCheck + paramValue;	
		} 
	}
	else if (ind1 >= 0 && ind2 < 0)
	{
		res = curUrl + '&' + paramToCheck + paramValue;
	}
	else
	{
		res = curUrl + '?' + paramToCheck + paramValue;
	}
	return res;
}

function addParamToNoneQuestionMarkUrl(curUrl, paramName, paramValue)
{
	var res = '';
	var paramToCheck = paramName + '='; 
	var ind2 = curUrl.lastIndexOf(paramToCheck);
	if (ind2 >= 0)
	{
		var ind3 = curUrl.indexOf("&", ind2);
		if (ind3 >= 0)
		{	
			res = curUrl.substring(0, ind2) + paramToCheck + paramValue + curUrl.substring(ind3); 
		}
		else
		{
			res = curUrl.substring(0, ind2) + paramToCheck + paramValue;	
		} 
	}
	else if (ind2 < 0)
	{
		res = curUrl + '&' + paramToCheck + paramValue;
	}
	return res;
}

function getParamFromNoQuestionMarkUrl(curUrl, paramName){
    var res = '';
    var paramToCheck = paramName + '='; 
    curUrl = decodeURI(curUrl);
    var ind2 = curUrl.lastIndexOf(paramToCheck);
    if (ind2 >= 0)
    {
            var ind3 = curUrl.indexOf("&", ind2);
            if (ind3 >= 0)
            {	
                res = curUrl.substring(ind2, ind3);
            }
            else
            {
                res = curUrl.substring(ind2, curUrl.length);
            } 
            res = res.split('=');
            return res[1];
    }
    else{
        return res;
    }
}


function goPrevPage(pageNo, noOfRecPerPage)
{
	var prevPage = '' + (parseInt(pageNo) - 1);
	goToPage(prevPage,  noOfRecPerPage);
}


function goNextPage(pageNo, noOfRecPerPage,url)
{
	var nextPage = '' + (parseInt(pageNo) + 1);
	goToPage(nextPage,  noOfRecPerPage,url);
}
/*****( END - @Pagination )**********************************/

/*****( BEGIN - @Results Table )*****************************/

// Ascending/Descending arrow for product results table
var arrowDesc = document.createElement("img");
arrowDesc.setAttribute("src", SITE_ROOT + "common/images/icons/ico-arrow-desc.gif");
arrowDesc.setAttribute("class", "sortArrow");

var arrowAsc = document.createElement("img");
arrowAsc.setAttribute("src", SITE_ROOT + "common/images/icons/ico-arrow-asc.gif");
arrowAsc.setAttribute("class", "sortArrow");

// Product Results Table
var sortPara = getParamFromNoQuestionMarkUrl(document.location.href,'Ns');
if (sortPara != '') { 
  
  if(sortPara.lastIndexOf('|')>0){
    sortPara = sortPara.split('|');
    var sortOrder = sortPara[1];
    sortID = sortPara[0];
      var headLabel = document.getElementById(rmWhiteSpace(sortID) + "Head");
      if (sortOrder == 1) { 
          if (headLabel) {
              insertAfter(arrowDesc, headLabel);
          }
          else{
            headLabel = jQuery("th>span:contains('"+sortID+"')")[0];
            if (headLabel) {
              insertAfter(arrowDesc, headLabel);
            }
          }
      } else {
          if (headLabel) {
              insertAfter(arrowAsc, headLabel);
          }
          else{
            headLabel = jQuery("th>span:contains('"+sortID+"')")[0];
            if (headLabel) {
              insertAfter(arrowAsc, headLabel);
            }
          }
      }
   }
}

function doSort(sortKey, sortID, hdrCell)
{
	var curUrl = document.location.href;
        if(curUrl.indexOf(";jsession")>-1){
            curUrl = curUrl.substring(0,curUrl.indexOf(";jsession"));
        }
        if(curUrl.lastIndexOf('products.ex')>0 && curUrl.lastIndexOf('N=')==-1){
            curUrl = curUrl.replace("products.ex", "search/products/_/N-0&in_dim_search=1");
        }
	var headingCell = hdrCell;
	var keyField = document.getElementById("sortKey");
	var orderField = document.getElementById("sortOrder");
	var pgNoField = document.getElementById("curPageNo");
	var existingKey = "";
	var existingOrder = "";
	var existingPageNo = "";
	var sortIdentifier = sortID;
	var sortOrder = 0;
	if (keyField) {
		existingKey = keyField.value;
	} if (orderField) {
		existingOrder = orderField.value;
	} if (pgNoField) {
		existingPageNo = pgNoField.value;
	}
	
	if (sortKey == existingKey) {
    //toggle the sort order

    if (existingOrder == '0') {
      sortOrder = '1';
    } else {
      sortOrder = '0';
    }
    
	}
    //delete hash
    if(curUrl.lastIndexOf('#')>0){
        curUrl = curUrl.substring(-1,(curUrl.lastIndexOf('#')));
    }
	
    curUrl = addParamToNoneQuestionMarkUrl(curUrl , 'Ns' , sortKey + '|' + sortOrder);
	
    if (existingPageNo != '') {
        var recNo = (parseInt(existingPageNo) - 1) * 10;
        curUrl = addParamToNoneQuestionMarkUrl(curUrl , 'No' , recNo);
    }
	 
  //curUrl = curUrl + '&dispatch=loadAttribTable';
  
  curUrl = handleProductsRoot(curUrl);
  document.location.href = curUrl;

//  var headLabel = document.getElementById(rmWhiteSpace(sortID) + "Head");
//  
//  if (sortOrder == 1) { 
//                  
//      if (headLabel) {
//          insertAfter(arrowDesc, headLabel);
//      }
//  } else {
//  
//      if (headLabel) {
//          insertAfter(arrowAsc, headLabel);
//      }
//  }
}

// Sorts product results table
function doAjaxSort(sortKey, sortID, hdrCell)
{
	var curUrl = document.location.href;
	var headingCell = hdrCell;
	var keyField = document.getElementById("sortKey");
	var orderField = document.getElementById("sortOrder");
	var pgNoField = document.getElementById("curPageNo");
	var existingKey = "";
	var existingOrder = "";
	var existingPageNo = "";
	var sortIdentifier = sortID;
	
	if (keyField) {
		existingKey = keyField.value;
	} if (orderField) {
		existingOrder = orderField.value;
	} if (pgNoField) {
		existingPageNo = pgNoField.value;
	}
	
	if (sortKey == existingKey) {
    //toggle the sort order

    if (existingOrder == '0') {
      sortOrder = '1';
    } else {
      sortOrder = '0';
    }
	}
    //delete hash
    if(curUrl.lastIndexOf('#')>0){
        curUrl = curUrl.substring(-1,(curUrl.lastIndexOf('#')));
    }
	
  curUrl = curUrl + '&Ns=' + sortKey + '|' + sortOrder;
  
	
	if (existingPageNo != '') {
		var recNo = (parseInt(existingPageNo) - 1) * 10;
    curUrl = curUrl + '&No=' + recNo;
	}
	 
  curUrl = curUrl + '&dispatch=loadAttribTable';
  
  curUrl = handleProductsRoot(curUrl);

  jQuery.get(curUrl,"",function(response) {
    var curDiv = document.getElementById("attribute-table");
            
    if (curDiv) {
      curDiv.innerHTML = response;
      
      if (curDiv.style.display == 'none') {
          curDiv.style.display = 'block';
      }
      
      var headLabel = document.getElementById(rmWhiteSpace(sortID) + "Head");
      
      if (sortOrder == 1) { 
                      
          if (headLabel) {
              insertAfter(arrowDesc, headLabel);
              
              //alert(headingCell.innerHTML);
          }
      } else {
      
          if (headLabel) {
              insertAfter(arrowAsc, headLabel);
              
              //alert(headingCell.innerHTML);
          }
      }
    }
    return response;
  });
}

//------start commonPagination -- TODO - is this being used??
function markHistoryForPaginationNew(curPageNo, noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback) {
	var state = {
		curPageNo: curPageNo,
		noOfRecPerPage: noOfRecPerPage,
		paginationParamName: paginationParamName,
		urlForPaginationAndSort: urlForPaginationAndSort,
		isAjaxCall: isAjaxCall,
		responseLoadedCallback: responseLoadedCallback,
		back: function() 
		{
			goToPageNew(this.curPageNo, this.noOfRecPerPage,this.paginationParamName,this.urlForPaginationAndSort,this.isAjaxCall,this.responseLoadedCallback);		
		},
		forward: function()
		{
			goToPageNew(this.curPageNo, this.noOfRecPerPage,this.paginationParamName,this.urlForPaginationAndSort,this.isAjaxCall,this.responseLoadedCallback);				
		},
		changeUrl: false							
	};
	//dojo.back.addToHistory(state);
}

function markHistoryForDoAjaxSortNew(sortKey, sortID, hdrCell,existingKey,existingOrder,sortParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback){
	var state = {
		sortKey: sortKey,
		sortID: sortID,
		hdrCell: hdrCell,
		existingKey: existingKey,
		existingOrder: existingOrder,
		sortParamName: sortParamName,
		urlForPaginationAndSort: urlForPaginationAndSort,
		isAjaxCall: isAjaxCall,
		responseLoadedCallback: responseLoadedCallback,
		back: function() 
		{
			doAjaxSortNew(this.sortKey, this.sortID,this.hdrCell,this.existingKey,this.existingOrder,this.sortParamName,this.urlForPaginationAndSort,this.isAjaxCall,this.responseLoadedCallback);	
		},
		forward: function()
		{
			doAjaxSortNew(this.sortKey, this.sortID,this.hdrCell,this.existingKey,this.existingOrder,this.sortParamName,this.urlForPaginationAndSort,this.isAjaxCall,this.responseLoadedCallback);
		},
		changeUrl: false							
	};
	//dojo.back.addToHistory(state);
} 

function goToPageNew(curPageNo, noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback)
{
	//markHistoryForPaginationNew(curPageNo, noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback);
	var recNo = 0;
	if (noOfRecPerPage)
	{
		recNo = (curPageNo - 1) * noOfRecPerPage;
	}
  var curUrl = urlForPaginationAndSort + '&'+paginationParamName+"=" + recNo;
  if(isAjaxCall){
    jQuery.get(curUrl,"", function(response) {
      var otherArgs = {};
      responseLoadedCallback(response,ioArgs,otherArgs);
      return response;
    });
  }else{
    window.location.href = curUrl;
  }

}

function goPrevPageNew(pageNo, noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback)
{
	var prevPage = '' + (parseInt(pageNo) - 1);
	goToPageNew(prevPage,  noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback);
	
}


function goNextPageNew(pageNo, noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback)
{
	var nextPage = '' + (parseInt(pageNo) + 1);
	goToPageNew(nextPage,  noOfRecPerPage,paginationParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback);
}

// Sorts resluts table
function doAjaxSortNew(sortKey, sortID, hdrCell,existingKey,existingOrder,sortParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback)
{
	//markHistoryForDoAjaxSortNew(sortKey, sortID,hdrCell,existingKey,existingOrder,sortParamName,urlForPaginationAndSort,isAjaxCall,responseLoadedCallback);

    //alert("call doAjaxSort");
	var headingCell = hdrCell;
        
	if (sortKey == existingKey) {
            //toggle the sort order

            if (existingOrder == '0') {
                sortOrder = '1';
            } else {
                sortOrder = '0';
            }
        }
        
        //var sortPartReg=new RegExp(sortParamName+"=","g"); 
        var handedUrlForPaginationAndSort = urlForPaginationAndSort;
        if(null!=sortKey && sortKey!=""){
            var sortValue = sortKey + '|' + sortOrder;
            handedUrlForPaginationAndSort = addParamToUrl(handedUrlForPaginationAndSort,sortParamName,sortValue);
        }
        
        var curUrl = handedUrlForPaginationAndSort;
        
        if(isAjaxCall){
          jQuery.get(curUrl,"",function(response) {
            var otherArgs = {};
            otherArgs.sortID = sortID;
            responseLoadedCallback(response,ioArgs,otherArgs);
                
            return response;
          });   
        }else{
            window.location.href = curUrl;
        }
}	

//------end commonPagination

/*****( END - @Results Table )*******************************/

//-----( @Tables )---------------------------------------------
var Tables = {
  stripe: function(table, evenColor, oddColor) {
    if (typeof table == "object") {
      var counter = 0;
      var odd = "odd";
      var tbodies = table.getElementsByTagName("tbody") || table;
      
      for (i=0;i<tbodies.length;i++) {
        var tr = tbodies[i].getElementsByTagName("tr");
        
        for (j in tr) {
          if (j%2 == 1)
            tr[j].className = odd;
        }
      }
    }
  },
  
  init: function() {
    var tables = getElementsByClassName("zebra-grid");
    
    for(i in tables) {
      Tables.stripe(tables[i], '#eee', '#fff');
    }
  }
}
//-----( END )-------------------------------------------------

//-----( @StoreLocator )---------------------------------------
var StoreLocator = {
  toggleForm: function (formType) {
    var zipForm = "zipForm";
    var stateForm = "stateForm";
    var branchForm = "branchForm";
                
    if (document.getElementById) {
    
        if (formType == zipForm) {
            document.getElementById(stateForm).style.display = "none";
            document.getElementById(branchForm).style.display = "none";
                    
            document.getElementById(zipForm).style.display = "";
        } else if (formType == stateForm) {
            document.getElementById(zipForm).style.display = "none";
            document.getElementById(branchForm).style.display = "none";
                    
            document.getElementById(stateForm).style.display = ""; 
        } else if (formType == branchForm) {
            document.getElementById(zipForm).style.display = "none";
            document.getElementById(stateForm).style.display = "none";
                    
            document.getElementById(branchForm).style.display = "";
        }
    }
  },
	
  toggleSearch: function(obj) {
    if (obj) {
      var zipCode = document.getElementById("locZip");
      var city = document.getElementById("locCity");
      var state = document.getElementById("locState");
      var country = document.getElementById("locCountry");
      var branchNumber = document.getElementById("locBranch");
      
      zipCode.style.display = "none";
      city.style.display = "none";
      state.style.display = "none";
      country.style.display = "none";
      branchNumber.style.display = "none";
      
      if (obj.value == "Zip") {
          zipCode.style.display = "";
      } else if (obj.value == "City") {
          city.style.display = "";
          state.style.display = "";
      } else if (obj.value == "Country") {
          country.style.display = "";        
      } else if (obj.value == "Branch") {
          branchNumber.style.display = "";
      }
    }
  },

  submitSearch: function () {
    obj = document.getElementById("searchOption");

    if (obj.value == "Zip") {
        document.getElementById("zipForm").submit();
    } else if (obj.value == "City") {
        document.getElementById("cityForm").submit();
    } else if (obj.value == "Country") {
        window.location.href = document.getElementById("country").value;
    } else if (obj.value == "Branch") {
        document.getElementById("branchForm").submit();
    }
  },
  
  validate: function() {
    // TODO We shouldn't need this, but the store availability and store locator use the same "searchOption" id.
    if ((document.getElementById("searchOption")) &&
        (document.getElementById("locZip")) &&
        (document.getElementById("locCity")) &&
        (document.getElementById("locState"))) {
      return true;
    } else {
      return false;
    }
  },
  
  init: function() {
    if (StoreLocator.validate()) {
      StoreLocator.toggleSearch(document.getElementById("searchOption"));
    }
  }
}
//-----( END )-------------------------------------------------

//-----( @ShoppingCart )---------------------------------------
var ShoppingCart = {
        showLocationAndSublocation : false,
	form: Object,
	init: function() {
		ShoppingCart.form = document.getElementById("updateCart");
                var showLocations = document.getElementById("showLocations");
		if (ShoppingCart.form) {
			Events.addEvent(ShoppingCart.form, "submit", ShoppingCart.updateCart);
		}
		if(showLocations != null && showLocations.value == "true")
                {
                    ShoppingCart.showHideLocations();
                }
	},
  updateCart: function(ev) {
  		//alert("cart update function");
/*		var allNodes = getElementsByClassName("cartQtyTextBox");
    for (i=0; i<allNodes.length; i++) {
			qty = allNodes[i].value;
			var num = parseInt(qty);
	    
			if (isNaN(qty) || qty < 0) {
				alert("Enter a valid value for quantity.");
				allNodes[i].focus();
				Event.stop(ev);
			}
    }
    */
  },
  empty: function(url) {
		var alertMsg = "Are you sure you want to empty your cart?";
		if (confirm(alertMsg)) { gotoUrl(url); updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display') }
  },
  remove: function(url) {
		var alertMsg = "Are you sure you want to remove this line item?";
		if (confirm(alertMsg)) { gotoUrl(url); updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display'); }
  },
    addLocations: function() {
      var classes = getElementsByClassName("cartLocation");
      for(i=0;i<classes.length;i++) {
        classes[i].style.display = "block";
      }
    },
    showHideLocations: function() {
      if(ShoppingCart.showLocationAndSublocation) {
        var classes = getElementsByClassName("cartLocation");
        for(i=0;i<classes.length;i++) {
          classes[i].style.display = "none";
        }
  
        if(document.getElementById('showHideLocations') != null){
          document.getElementById('showHideLocations').value = "Show Locations";
          ShoppingCart.showLocationAndSublocation = false;
        }
      }
      else {
        var classes = getElementsByClassName("cartLocation");
        for(i=0;i<classes.length;i++) {
          classes[i].style.display = "block";
        }
        
        if(document.getElementById('showHideLocations') != null) {
          document.getElementById('showHideLocations').value = "Hide Locations";
          ShoppingCart.showLocationAndSublocation = true;
        }             
      }        
    }    
};
//-----( END )-------------------------------------------------

//-----( @Textarea )-------------------------------------------
var Textarea = {
	init: function() {
		Textarea.setMaxLength();
	},
	isMaxLength: function(obj) {
		obj = this;
		var maxlen = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
		if (obj.getAttribute && obj.value.length>maxlen) {
			obj.value = obj.value.substring(0, maxlen);
		}
	},
	setMaxLength: function() {
	  var counter = document.createElement("div");
	  counter.setAttribute("class", "");    
    
	  var textareas = $A(document.getElementsByTagName("textarea"));
	  textareas.each(function(textarea) {
			if (textarea.getAttribute("maxlength")) {
      
        //Added for one step checkout special instructions textarea so it does
        //not keep stacking divs.  Instead delete div if it exists before
        //redrawing the "X of Y characters used" text.
        var sDivId = "div" + textarea.getAttribute("id");
        if ( document.getElementById(sDivId) != null ) {
          removeElement( document.getElementById(sDivId) );
        }
        counter.setAttribute("id", sDivId);
      
			  var counterClone = counter.cloneNode(true);
  			counterClone.relatedElement = textarea;
	  		counterClone.innerHTML = "<span>0</span> of " + textarea.getAttribute("maxlength") + " characters used";
		  	textarea.parentNode.insertBefore(counterClone, textarea.nextSibling);
			  textarea.relatedElement = counterClone.getElementsByTagName("span")[0];
  			textarea.onkeyup = Textarea.checkMaxLength;
  			textarea.onchange = Textarea.checkMaxLength;
	  		textarea.onkeyup();
		  }
	  });
  }, 
	checkMaxLength: function() {
	  var maxLength = this.getAttribute("maxlength");
	  var currentLength = this.value.length;
    if (currentLength > maxLength) {
		  this.relatedElement.className = "overlimit";
    } else {
	  	this.relatedElement.className = "";
    }
	  this.relatedElement.firstChild.nodeValue = currentLength;
  }
}
//-----( END )-------------------------------------------------


//-----( @CheckBox )-------------------------------------------
var CheckBox = {
	checkAll: function(chkAll, checks) {
		chkAll = document.getElementById(chkAll);
		checks = document.getElementsByName(checks);
		
		if (chkAll.checked == true) {
			for (var i=0; i<checks.length; i++) {
				checks[i].checked = true;
			}
		} else {
			for (var i=0; i<checks.length; i++) {
				checks[i].checked = false;
			}
		}
	},
	checkOnce: function(chkAll, checks) {
		var allChecked = false;
		chkAll = document.getElementById(chkAll);
		checks = document.getElementsByName(checks);
		
		for (var i=0; i<checks.length; i++) {
			if (checks[i].checked == true) {
				allChecked = true;
				continue;
			} else {
				allChecked = false;
				break;
			}
		}
		
		if (allChecked == true) {
			chkAll.checked = true;
		} else {
			chkAll.checked = false;
		}
	}	,
	getTotalChecked: function(checks) {
		var totalChecked = 0;
		checks = document.getElementsByName(checks);
		
		for (var i=0; i<checks.length; i++) {
			if (checks[i].checked == true) {
				totalChecked++;
			}
		}
		return totalChecked;
	}
        ,
        ifCheckedOne: function (checks,errorDiv) {
                var checked = false;
                checks = document.getElementsByName(checks);
                for (var i=0; i<checks.length; i++) {
                        if (checks[i].checked == true) {
                                checked = true;
                                break;
                        }
                }
                if(!checked){
                        document.getElementById(errorDiv).className = "error";
                        document.getElementById(errorDiv).style.visibility = 'visible';
                        return false;
                }
                else{
                        document.getElementById(errorDiv).className = "";
                        document.getElementById(errorDiv).style.visibility = 'hidden';
                        return true;
                }
        }
};
//-----( END )-------------------------------------------------

//-----( @Msds )-----------------------------------------------
var Msds = {
	init: function() {
		var msdsLinks = getElementsByClassName("msds");
		msdsLinks.each(function(msdsLink) {
			Event.observe(msdsLink, "click", Msds.showPopup.bind(this), false);
		});
	},
	showPopup: function(event) {
		var href = Event.element(event);
		if (href != null || href != "") {
			var name = "fcom_msds_popup";
			var features = "width=785,height=589,";
			features += "directories=no,location=yes,menubar=yes,";
			features += "resizable=yes,scrollbars=yes,status=yes,toolbar=yes";
			popupUrl(href, name, features);
			Event.stop(event);
		}
	}
}
//-----( END )-------------------------------------------------

//-----( @Help )---------------------------------------------
var Help = {
  init: function() {
    var links = getElementsByClassName("help");
    for (i=0; i<links.length; i++) {
      var container = document.getElementById(links[i].id + "-container")
      if (container) {
        container.className = "help-container";
        document.body.appendChild(container); // move the object to the bottom of the page because CSS is too picky about overflow
        Events.addEvent(links[i],"mouseover",function(event) {
          Help.togglePopup(event);
        });
        Events.addEvent(links[i],"mouseout",function(event) {
          Help.togglePopup(event);
        });
        Events.addEvent(links[i],"click",function(event) {
          Help.togglePopup(event);
        });
      }
    }
  },
  
  togglePopup: function(e) {
    e = e || window.event;
    var obj = e.target || e.srcElement
    if (obj) {
      var container = document.getElementById(obj.id + "-container");
      if(container) {
        if (e.type == "mouseover" || (e.type == "click" && container.style.display == "none")) {
          container.className = "help-container";
          jQuery(container).fadeIn("fast");
          var pos = Window.getElementPosition(obj,0);
          var wrap = document.getElementById("wrap");
          if (wrap) {
            wrap.size = [wrap.offsetWidth,wrap.offsetHeight];
            wrap.position = Window.getElementPosition(wrap,0);
          }
          if ((container.offsetWidth + pos[0]) < (wrap.size[0] + wrap.position[0])) {
            container.style.top = pos[1] + 5 + "px";
            container.style.left = pos[0] + obj.offsetWidth + 5 + "px";
          } else {
            container.style.top = pos[1] + obj.offsetHeight + 5 + "px";
            container.style.left = pos[0] - container.offsetWidth + obj.offsetWidth - 0 + "px";
          }
          var zi = 100; // IE6/7 bug fix
          var tempObj = container;          
          while (tempObj = tempObj.parentNode)
            if (tempObj.style) {
            if(tempObj.id!='left'){
                tempObj.style.zIndex = zi++;
                }
            }
        } else if (e.type == "mouseout" || (e.type == "click" && container.style.display != "none")) {
          jQuery(container).fadeOut("fast");

          var tempObj = container; // IE6/7 bug fix
          while (tempObj = tempObj.parentNode)
            if (tempObj.style) tempObj.style.zIndex = "";
        }
        Events.stopBubble(e);
      }
    }
  }
}
//-----( END )-------------------------------------------------*/

/* Change + or - character for related items section on click event. */
var stateOther, stateRelated, fastPad;	// states of icons

//-----( @SalesDrawings )-----------------------------------------
var SalesDrawings = {
	init: function() {
		var salesDrawings = getElementsByClassName("salesDrawings");
		salesDrawings.each(function(salesDrawing) {
			Event.observe(salesDrawing, "error", SalesDrawings.noSalesDrawing, false);
		});
	},

	noSalesDrawing: function(element, root) {
		element.src = root + "/common/images/misc/nosalesdrawingavailable.jpg";
	}
}
//-----( END )-------------------------------------------------


//-----( @LinkPreview )----------------------------------------
// DESCRIPTION: Preview Your Links with Unobtrusive JavaScript 
//              (http://particletree.com/features/preview-your-links)
var LinkPreview = {
	extensions: new Array("doc", "pdf", "ppt", "txt", "xls", "zip", "mdi", "vcf", "mdb", "pub", "mpp"),
	
	// gets all non-image links from the page
	init: function() {
		var links = document.getElementsByTagName("a");

		for (var i=0; i<links.length; i++) {
			var currentLink = links[i];
			var	images = currentLink.getElementsByTagName("img");
			
	 		// check if the link is an image we don't want icons next to images
			if (images.length == 0) {
				var linkHref = currentLink.href;
				LinkPreview.checkLink(linkHref, currentLink)
			}
		}
	},
	
	// checks if the link goes to an external file (ie. .doc, .pdf)
	checkLink: function(linkHref, currentLink) {
		var linkHrefParts = linkHref.split(".");
			
		// extension is the last element in the LinkSplit array
		var extension = linkHrefParts[linkHrefParts.length - 1];
		
		// in some browsers there is a "/" placed after the link. removes the "/"
		extension = extension.replace("/","");
		
		for (var i=0; i<LinkPreview.extensions.length; i++) {
			if (extension == LinkPreview.extensions[i]) {
				LinkPreview.appendClass(currentLink, extension);
			}
		}
	},
	
	// creates a span after the object passed in and sets the class to the link type
	appendClass: function(currentLink, extension) {
		var span = document.createElement('span');
		span.innerHTML = "&nbsp;";
		currentLink.parentNode.insertBefore(span, currentLink.nextSibling);
		span.className = extension;
	}
};
//-----( END )-------------------------------------------------

//-----( @avDescribe )-----------------------------------------
var avDescribe = {
	toolTip: Object,
	iframe: Object,
	init: function() {
  
  
		if (!document.getElementById 
		|| !document.createElement
		|| !document.getElementsByTagName) {
			return;
		}
		
		avDescribe.toolTip = document.createElement('div');
		avDescribe.toolTip.id = 'toolTip';
		document.getElementsByTagName('body')[0].appendChild(avDescribe.toolTip);
		avDescribe.toolTip.style.top = 0;
		avDescribe.toolTip.style.visibility = 'hidden';
		
		var helpLinks = getElementsByClassName('help');
		helpLinks.each(function(helpLink) {
			if (helpLink.rel != "") {
				Event.observe(helpLink, 'mouseover', avDescribe.tipOver, false);
				Event.observe(helpLink, 'mouseout', avDescribe.tipOut, false);
			}
		});
    
    
	},
	tipOut: function() {
		avDescribe.toolTip.style.visibility = 'hidden';
		if (avDescribe.iframe != null) {
			avDescribe.iframe.style.display = "none";
		}
	},
	tipOver : function(event) {		
		var avhtml = avDescribe.getTip(Event.element(event).rel);
		avDescribe.toolTip.innerHTML = "<p>" + avhtml + "</p>";
		avDescribe.toolTip.style.left = (Event.pointerX(event) + 15) + 'px';
		avDescribe.toolTip.style.top = (Event.pointerY(event) + 10) + 'px';
		avDescribe.toolTip.style.visibility = 'visible';
		avDescribe.makeIframe(avDescribe.toolTip);

		//avDescribe.toolTip.style.opacity = '.90';
		//avDescribe.toolTip.style.filter = "alpha(opacity:90)";
	},
	makeIframe: function(tt) {
		// make the iframe
		var iframetemp = document.createElement("iframe");
		iframetemp.frameBorder = 0;
		iframetemp.src = "javascript:false";
		iframetemp.style.display = "none";
		iframetemp.style.position = "absolute";
		iframetemp.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
		tt.iframetemp = tt.parentNode.insertBefore(iframetemp, tt);

		// position the iFrame under the tooltip
		tt.iframetemp.style.top  = tt.style.top;
		tt.iframetemp.style.left = tt.style.left;
		tt.iframetemp.style.width  = tt.offsetWidth + "px";
		tt.iframetemp.style.height = tt.offsetHeight + "px";
		tt.iframetemp.style.display = "block";
		
		avDescribe.iframe = tt.iframetemp;
	},
	getTip: function(avcode) {
		switch (avcode) {
			case "avSTR":
				avhtml = "Inventory generally available in the majority of our "
				+ "local store locations for immediate in-store pick-up or shipping.";
				break;
			case "avSTK":
				avhtml = "Inventory generally available for immediate shipping from a "
				+ "Fastenal stocking location. Inventory may also be stocked in some local "
				+ "stores. Inventory is usually available for in-store pick-up in 1-2 days.";
				break;
			case "avSFM":
				avhtml = "Inventory generally available directly from a Fastenal approved "
				+ "manufacturer. Item is not generally stocked in our local store or stocking "
				+ "location. Lead times may vary and product may be available for in-store "
				+ "pick-up. Contact your local store for specific information.";
				break;
			case "avSLL":
				avhtml = "Inventory only available in a limited number of Fastenal locations. "
				+ "Product may be available to ship immediately and usually available for in-store "
				+ "pickup in 1-4 days. Contact your local store for specific information.";
				break;
			case "avLTV":
				avhtml = "Product generally not stocked in our local store location but usually "
				+ "available to ship in 2-5 days with local in-store pick-up in 3-10 days. "
				+ "Lead times, minimum order quantities, and freight are subject to change. "
				+ "Contact your local store for specific information.";
				break;
			case "avDIS":
				avhtml = "Product has been discontinued but still may be available in "
				+ "limited quantities. Find an alternative part or contact your local "
				+ "store for specific information.";
				break;
		}
		return avhtml;
	}
};
//-----( END )-------------------------------------------------

//-----( @CMIListOperations )--------------------------------------
    var CMIListOperations = {
      target: 'importUI', 
      url: SITE_ROOT + 'cmiListAction.ex', 
      /**
      init: function() {
        CMIListOperations.target = 'importUI';
        CMIListOperations.url = '/web/cmiListAction.ex';//'/web/cmi/cmiListAction.ex';//'/web/cmi/importCSV.html';
      },
      **/
      importUI: function(action) {
        var pars = 'noRedirect=true&action='+ action; 
        //var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onSuccess: showResponse});
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        {method: 'get', onComplete: CMIListOperations.showResponse, parameters: pars, evalScripts: true, asynchronus: true}
                                      );
      },  //end importUI

      lookupSku: function(action) {
        var sku =document.cmiForm.sku.value;
        
        var pars = 'noRedirect=true&action='+ action + '&sku=' + sku; 
        //var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onSuccess: showResponse});
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        { method: 'get'
                                        , onComplete: CMIListOperations.showLookupSkuResponse
                                        , parameters: pars
                                        , evalScripts: true
                                        , asynchronus: true}
                                      );
            
            
      },  //end lookupSku
      
      addSku: function(action, listId, sku, productId, partType, qty) {
        //var sku =document.cmiForm.sku.value;
        var pars = 'noRedirect=true&action='+ action 
                    + '&listId='    + listId
                    + '&addSku='    + sku 
                    + '&productId=' + productId
                    + '&qty=' + qty
                    + '&partType='  + partType; 
        //alert (pars);
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        { method: 'get'
                                        , onComplete: CMIListOperations.showAddSkuResponse
                                        , parameters: pars
                                        , evalScripts: true
                                        , asynchronus: true}
                                      );
      },  //end addSku
      
      listQuantities: function(e, reviewId, recordId) {
        //var sku =document.cmiForm.sku.value;
        var mouseX = Event.pointerX(e);
        var mouseY = Event.pointerY(e); 
        var action = 'displayListQtys';
        var pars = 'noRedirect=true&action='+ action 
                    + '&reviewId='  + reviewId
                    + '&recordId='  + recordId ; 
        //alert (pars);
        mouseX+=20 ;
        mouseY-=65
        document.getElementById("QuantityList").style.left = mouseX + 'px';
        document.getElementById("QuantityList").style.top = mouseY + 'px';
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        { method: 'get'
                                        , onComplete: CMIListOperations.showQtyListResponse
                                        , parameters: pars
                                        , evalScripts: true
                                        , asynchronus: true}
                                      );
        return false;
      },  //end listQuantities
      
      printSubLocation: function(){
        CMIListOperations.importUI('displayPrintSubLocation');
		CMIListOperations.NLBparam = 'subLocationContainer';
		CMIListOperations.callbackNLBfadeBg();
      }, //end printSubLocation
      
	  NLBparam:"",
      printBinLocation: function(){
        CMIListOperations.importUI('displayPrintBinLocation');
		CMIListOperations.NLBparam = 'binLocationContainer';
		CMIListOperations.callbackNLBfadeBg();
      }, //end printBinLocation

	  callbackNLBfadeBg: function(){
			if(document.getElementById(CMIListOperations.NLBparam) != null){
				NLBfadeBg(CMIListOperations.NLBparam, '#fff776', '#ffffff', '2000');
			}else{
				setTimeout('CMIListOperations.callbackNLBfadeBg()', 200);
			}
	  },
      
      importSku: function(){
        CMIListOperations.importUI('displayImportSku');
        
      }, //end importSku
      
      importCSV: function() {
        CMIListOperations.importUI('displayImportCSV');
      },  //end importCSV
      
      importCart: function() {
        CMIListOperations.importUI('displayImportCart');
      },  //end importCart
      
      importCart: function() {
        CMIListOperations.importUI('displayImportCart');
      },  //end importCSV
      
      importOrdTemplate: function() {
        CMIListOperations.importUI('displayImportOrdTemplate');
      },  //end importOrdTemplate
      
      showResponse: function(originalRequest){
        var response=originalRequest.responseText;
//        alert('show response: ' + response);
//        alert('target:' + CMIListOperations.target);
		document.getElementById(CMIListOperations.target).innerHTML = response;	
        //document.getElementById(CMIListOperations.target).innerHTML = response;
	
        //set focus
        if(document.cmiForm.sku){
          document.cmiForm.sku.focus();
        }

        //window.innerHTML = originalRequest.responseText;
      }, //end showResponse
      
      showLookupSkuResponse: function(originalRequest){
        var skuNo=document.cmiForm.sku.value;
        var response=originalRequest.responseText;
        //alert('show response: ' + response);
        try{
          //look for a possible error redirect
          var json= eval('(' + response + ')');
          if (json.url && json.url.length > 0){//some error occurred display the error and forward to page
            alert('Unable to service request.  \nReason:  [' + json.reason + ']');
            window.location = json.url;
          }else if (json.found){
            //alert('sku found:' + json.sku);
            var beginTag = '<span class="item-data" align="left" >';
            var endTag = '</span>';
            
            //alert('orig price: ' + json.price);           
            var sFinalPrice = json.price + "";
            if (sFinalPrice.indexOf(".") + 2 >= sFinalPrice.length || sFinalPrice.indexOf(".") == -1) {
              sFinalPrice = parseFloat(sFinalPrice).toFixed(2);
            }
            //alert('sFinalPrice: ' + sFinalPrice);
            
            //document.getElementById('sku').innerHTML = beginTag + 'json.sku' + endTag;
            document.getElementById('item-description').innerHTML = beginTag + json.description + endTag;
            document.getElementById('item-pkgQty').innerHTML = beginTag + json.pkgQty + endTag;
            document.getElementById('item-price').innerHTML = beginTag + "$" + sFinalPrice + endTag;
            //enable the add qty functionality
            document.cmiForm.addSku.value=json.sku;
            document.cmiForm.productId.value=json.productId;
            document.cmiForm.qty.disabled=false;
            document.cmiForm.add.disabled=false;
            //set focus
            document.cmiForm.qty.focus();
          }else if((skuNo==null)||(skuNo=="")||(skuNo.length==0) ){//not found
            alert("Enter a valid SKU.");
           }
           else{
            //alert("SKU not found!");
            CMIListOperations.showUnknownPartPopup();
            
           }
          return;
        }catch(e){
          alert('Unable to service request.  \nReason:  [' + json.reason + ']' + e);
        }
        
        
        //window.innerHTML = originalRequest.responseText;
      }, //end showLookupSkuResponse
      
      showAddSkuResponse: function(originalRequest){
        var pkgQty=document.cmiForm.qty.value;
        var response=originalRequest.responseText;
        //alert('show response: ' + response);
        try{
          //look for a possible error redirect
          var json= eval('(' + response + ')');
          if (json.url && json.url.length > 0){//some error occurred display the error and forward to page
            alert('Unable to service request.  \nReason:  [' + json.reason + ']');
            window.location = json.url;
          }else if (json.added){
            //alert('Successfully added item to list.');
            //CMIListOperations.importSku();
            //reset the form
            //document.getElementById('sku').innerHTML = beginTag + 'json.sku' + endTag;
           CMIListOperations.resetSkuForm();
            
          }else if((pkgQty==null)||(pkgQty=="")||(pkgQty.length==0)||(isNaN(pkgQty))){//not found
            alert("Enter a valid package quantity.");
          }
          return;
        }catch(e){
          alert('Unable to service request.  \nReason:  [' + json.reason + ']' + e);
        }
        //window.innerHTML = originalRequest.responseText;
      }, //end showAddSkuResponse
      
      showQtyListResponse: function(originalRequest){
        var response=originalRequest.responseText;
        try{
           document.getElementById("QuantityList").innerHTML = response;
           CMIListOperations.showQuantityListPopup();
          return;
        }catch(e){
          alert('Unable to service request.  \nReason:  [' + json.reason + ']' + e);
        }
      }, //end showQuantityListResponse
      
      resetSkuForm: function(){
        document.getElementById('item-description').innerHTML = '';
        document.getElementById('item-pkgQty').innerHTML = '';
        document.getElementById('item-price').innerHTML = '';
        //enable the add qty functionality
        document.cmiForm.addSku.value='';
        document.cmiForm.productId.value='';
        document.cmiForm.sku.value='';
        document.cmiForm.qty.value='';
        document.cmiForm.qty.disabled=true;
        document.cmiForm.add.disabled=true;
        //set focus
        document.cmiForm.sku.focus();
      },//end resetSkuForm
      
      updateAction: function (actionValue){
        document.cmiForm.action.value = actionValue;
      }, //end updateAction
      
      validateImportOrdTemplate: function (){
        //updateAction('addTemplateToList');
        //var templateId = $F('templateId'); //buggy for Firefox
        var templateId =document.cmiForm.templateId.value;
        //alert(templateId);
        if (templateId==''){
          //alert('Select an Order Template.');
          return false;
        }else{
          //alert('else');
          CMIListOperations.updateAction('addTemplateToList');
          //form should now submit
          return true;
        }//end else
        return false;
      }, //end validateImportOrdTemplate
      
      validateImportCart: function (){
        CMIListOperations.updateAction('addCartToList');
        return true;
      }, //end validateImportOrdTemplate
      
      validateImportCsv: function (){
        var form = document.cmiForm;
        var csvVal=document.cmiForm.csvFile.value;
        form.encoding='multipart/form-data';
        
        if(csvVal){
        //alert(form.encoding);
          CMIListOperations.updateAction('addCsvToList');
          return true;
        }else{
          alert("Select a file");
          return false;
        }
      }, //end validateImportCsv
      
      validateCreateList: function (){
        //var listName =document.cmiManagementForm.listName.value;
        var listNameVal=document.cmiForm.listName.value;
        
        if(listNameVal.length==0){
          alert("Enter a name for the new list");
          return false;
        }else{
          CMIListOperations.updateAction('createList');
          return true;
        }
      }, //end validateImportOrdTemplate
      validateAddSku: function (){
        
        //validate the value of the sku and the qty
        //CMIListOperations.updateAction('addSku');
        var listId =document.cmiForm.listId.value;
        var sku =document.cmiForm.sku.value;
        var productId = document.cmiForm.productId.value;
        var partType = document.cmiForm.partType.value;
        var qty = document.cmiForm.qty.value;
        CMIListOperations.addSku('addSku', listId, sku, productId, partType, qty);
        return false;
      },
      
      validateLookupSku: function (){
        //CMIListOperations.updateAction('lookupSku');
        //make ajax call
        var sku =document.cmiForm.sku.value;
        CMIListOperations.lookupSku('lookupSku');
        return true;
       },
      
      deleteSelected: function (){
        //TODO some validation mabye
        if (confirm('Are you sure you want to delete the selected items?')){
          CMIListOperations.updateAction('deleteSelectedItems');
          return true;
        }else{
          return false;
        }
      }, //end deleteSelected
      
      deleteList: function(url) {
        var alertMsg = "Are you sure you want to delete this Item List?";
    		if (confirm(alertMsg)) { gotoUrl(url); }
      }, 
      
      printSelected: function (){
        //TODO some validation mabye
        var confirmMsg = 'Are you sure you want to print the selected items?\n'
                        + 'When the print dialog appears, select your Zebra Label Printer from the list of available printers.';
        if (confirm(confirmMsg)){
          CMIListOperations.updateAction('printSelectedItems');
          //window.open();
          return true;
        }else{
          return false;
        }
      }, //end printSelected
      
      updateSelected: function (){
        //TODO some validation mabye
        var confirmMsg = 'Are you sure you want to update the selected items?\n';
        if (confirm(confirmMsg)){
          CMIListOperations.updateAction('updateSelectedItems');
          return true;
        }else{
          return false;
        }
      }, //end updateSelected
      
      updateListProperties: function (){
        //TODO some validation mabye
        var confirmMsg = 'Are you sure you want to update the Item List Properties\n';
        if (confirm(confirmMsg)){
          CMIListOperations.updateAction('updateListProperties');
          return true;
        }else{
          return false;
        }
      }, //end updateSelected
      handleKeyPressCreateList : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          return CMIListOperations.validateCreateList();
          
        }else{
          return true;
        }//end else
      }, //end handleKeyPressCreateList
      handleKeyPressItems : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          return false;
        }else{
          return true;
        }//end else
      }, //end handleKeyPressItems
      
      handleKeyPressLookup : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          CMIListOperations.validateLookupSku();
          return false;
        }else{
          return true;
        }//end else
      }, // end handleKeyPressLookup
      
      handleKeyAddSku : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          CMIListOperations.validateAddSku();
          return false;
        }else{
          return true;
        }//end else
      }, // end handleKeyPressAddSku
      
      handleKeypressQtyIssue : function (e, form, recordId) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          CMIListOperations.updateSuggestedQty(form, recordId);
          return false;
        }else{
          return true;
        }//end else
      }, // end handleKeypressQtyIssue

      showQuantityListPopup : function () {
        document.getElementById("QuantityList").style.visibility = "visible";
      }, // end showListPopup
      hideQuantityListPopup : function () {
        document.getElementById("QuantityList").style.visibility = "hidden";
      }, //end hideQuantityListPopup      
      
      showUnknownPartPopup : function () {
        document.getElementById("UnknownPartPopupCMI").style.visibility = "visible";
        document.getElementById("btnFastenal").focus();
      }, // end showUnknownPartPopup
      hideUnknownPartPopup : function () {
        document.getElementById("UnknownPartPopupCMI").style.visibility = "hidden";
        //document.getElementById("btnFastenal").focus();
      }, //end hideUnknownPartPopup
      customFastenalPart : function () {
        CMIListOperations.hideUnknownPartPopup();
        var beginTag = '<span class="item-data" align="left" >';
        var endTag = '</span>';
        //document.getElementById('sku').innerHTML = beginTag + 'json.sku' + endTag;
        document.getElementById('item-description').innerHTML = beginTag + 'CUSTOM FASTENAL PART' + endTag;
        document.getElementById('item-pkgQty').innerHTML = beginTag + '1' + endTag;
        document.getElementById('item-price').innerHTML = beginTag + 'N/A' + endTag;
        //enable the add qty functionality
        document.cmiForm.addSku.value=document.cmiForm.sku.value;
        //document.cmiForm.productId.value=
        document.cmiForm.qty.disabled=false;
        document.cmiForm.add.disabled=false;
        //set focus
        document.cmiForm.qty.focus();
        //document.getElementById("btnFastenal").focus();
      }, //end customFastenalPart
      cancelPart : function () {
        CMIListOperations.hideUnknownPartPopup();
        document.getElementById('item-description').innerHTML = '';
        document.getElementById('item-pkgQty').innerHTML = '';
        document.getElementById('item-price').innerHTML = '';
        //enable the add qty functionality
        document.cmiForm.addSku.value='';
        document.cmiForm.productId.value='';
        //document.cmiForm.sku.value='';
        document.cmiForm.qty.value='';
        document.cmiForm.qty.disabled=true;
        document.cmiForm.add.disabled=true;
        document.cmiForm.sku.focus();
      }, //end cancelPart
      
      updateSuggestedQty : function (form, recordId) {
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        var newQty = qty.value;
        
        var pkgQty = form.elements['pkgQty|'+recordId].value;
        var newSugQty = newQty * pkgQty;
        //alert('before set' + form.elements['qty-issue|'+recordId].value);
        document.getElementById('sug-qty|' + recordId).innerHTML = newSugQty;
        //alert('after set');
        return false;
      }, //end updateSuggestedQty
      
      updateSuggestedQtyFromPopup : function (recordId, newQty) {
        var form = document.cmiForm;
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        qty.value=newQty;
        
        CMIListOperations.updateSuggestedQty(form, recordId);
        CMIListOperations.hideQuantityListPopup();
      }, //end updateSuggestedQty
      
      incSuggestedQty : function (form, recordId) {
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        
        qty.value++;
        CMIListOperations.updateSuggestedQty(form, recordId);
        return false;
      }, //incSuggestedQty
      
      decSuggestedQty : function (form, recordId) {
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        if (qty.value > 1){
          qty.value--;
        }
        CMIListOperations.updateSuggestedQty(form, recordId);
        return false;
      } //decSuggestedQty
    };
    
//-----( END )-------------------------------------------------    

// set store for header -- TODO not sure if this is used...
function setCurrentStore(storeCode) {
    var sExec = "products/searchStoreForProd.ex";
    var sParam = "dispatch=selectStore&storeCode=" + storeCode;

    var path = setPath( sExec, sParam );

    jQuery.get(path, "", function (response) {
      bProcessingAutoComp = false;
      window.location = SITE_ROOT + "home.ex";
      return response;
    });	
}	

// END header.js

/******************************
****** Cart Summary Code ******
******************************/

var globalCurrent;
var globalRelated;

// Update shopping cart popup after user updates the cart
function updateCartPopup(file) {
  jQuery.get(file,"",function(response) {
    var test = document.getElementById("cartContainer");
    
    var cartContainer = document.getElementById("cartContainer");
    var cartPopup = document.getElementById("cartPopup");
    var separator = "-------separator------";
    var l1 = response.indexOf(separator);
    var content1 = response.substring(0, l1);
    var content2 = response.substring(l1 + separator.length);
    cartPopup.innerHTML = content2;
    
    var myNode = document.createElement("div");
    myNode.innerHTML = content1;
    cartContainer.innerHTML = content1;
  });
}

// Clear cart popup content
function clearCartPopup() {
    
    if (document.getElementById("cartPopup") != null) {
        var cartPop = document.getElementById("cartPopup");
        
        cartPop.innerHTML = "Your Shopping Cart is empty.";
        
        var count = document.getElementById("cartIconCount");
        count.innerHTML = "";
    }
}

// Return true if node a contains node b
function contains(a, b) {

    if (a != null & b != null) {
  
        while (b.parentNode) {
    
            if ((b = b.parentNode) == a) {
                return true;
            }
        }
    }
    return false;
}

function sameParent(a, b) {

    if (a != null & b != null) {
  
        while (b.parentNode) {
    
            if ((b = b.parentNode) == a) {
                return b;
            }
        }
    }
    return false;
}
    
//-----( START - @Accounts )-------------------------------------------------------------------------
//-----( @AccountInformation )---------------------------------
var AccountInformation = {
	init: function() {
		AccountInformation.enableOtherState();
		AccountInformation.enableOtherCountry();
	},
	enableOtherState: function() {
		var billState = document.getElementById("fBillState");
		var billOtherState = document.getElementById("fBillStateOther");

		if (billState != null) {
			var billStateValue = document.getElementById("fBillState").value;
			if (billStateValue == "-1") {
				billOtherState.disabled = false;
			} else {
				billOtherState.value = "";
				billOtherState.disabled = true;
			}
		}	
	},
	enableOtherCountry: function() {
		var billCountry = document.getElementById("fBillCountry");
		var billOtherCountry = document.getElementById("fBillCountryOther");

		if (billCountry != null) {
			var billCountryValue = document.getElementById("fBillCountry").value;
			if (billCountryValue == "-1") {
				billOtherCountry.disabled = false;
			} else {
				billOtherCountry.value = "";
				billOtherCountry.disabled = true;      
			}
		}
	}
};
//-----( END )-------------------------------------------------
//-----( @Custs )----------------------------------------------
var Custs = {
	form: Object,
	init: function() {
		Custs.form = document.getElementById("CustAccountsListForm");
	},
	remove: function(url) {
		if (Custs.validate()) {
			if (confirm("Are you sure you want to remove these account(s)?")) {
			    Custs.form.action = url;
			    Custs.form.submit();
                        }
		} else {
			alert("You must select at least one account to remove.");
		}
	},
	validate: function() {
		for (var i=0; i<Custs.form.elements.length; i++) {
			if (Custs.form.elements[i].checked) { return true; }
		}
		return false;
	}
};
//-----( END )-------------------------------------------------
//-----( @EditAddress )----------------------------------------
var EditAddress = {
  init: function() {
    EditAddress.enableOtherState();
    EditAddress.enableOtherCountry();
  },
  enableOtherState: function() {
    var state = document.getElementById("fState");
    var stateOther = document.getElementById("fStateOther");
    var stateValue = document.getElementById("fState");
    
    if (stateOther != null) {
      if (stateValue.value == "-1") {
        stateOther.disabled = false;
      } else {
        stateOther.value = "";
        stateOther.disabled = true;
      }
    }
  },
  enableOtherCountry: function(curSelection) {
    var country = document.getElementById("fCountry");
    var countryOther = document.getElementById("fCountryOther");
    var countryValue = document.getElementById("fCountry");
    
    if (countryOther != null) {
      if (countryValue.value == "-1") {
        countryOther.disabled = false;
      } else {
        countryOther.value = "";
        countryOther.disabled = true;
      }
    }
  },
  updateServicingStores: function() {    
    var obj = document.getElementById("saveLocation");
    if (obj) {
      var action = "refreshServicingStores",
          postalCode = obj.postalCode.value;
      
      jQuery.post(
        obj.getAttribute("action"),
        "action=" + action + "&postalCode="+ postalCode + "&ajax=1",
        function (data) {
            jQuery("#servicingStoreList").html(data);
        }
      )
      
      return false;
    }
    
    alert('pause');
  }
};
//-----( END )-------------------------------------------------
//-----( @EditUserAccount )------------------------------------
var EditUserAccount = {
  init: function() {
    var theForm = document.getElementById("editUsers");
    if (!theForm) return false;
    if (theForm.admin.checked) {
      EditUserAccount.togglePurchasingOptionsAdmin();
    } else {
      EditUserAccount.togglePurchasingOptionsApprover();
    }
  },
  togglePurchasingOptionsAdmin: function() {
    var theForm = document.getElementById("editUsers");
    if (theForm.admin.checked) {
      theForm.grantApprover.disabled = true;
      theForm.grantApprover.checked = true;
      EditUserAccount.disablePurchasingOptions();
      EditUserAccount.disableRequestApprovers();
      EditUserAccount.disableLimitPurchases();
    } else {
      theForm.grantApprover.disabled = false;
      theForm.grantApprover.checked = false;
      EditUserAccount.enablePurchasingOptions();
      EditUserAccount.determineSelectApprover();
      EditUserAccount.determineLimitPurchases();
    }
  },
  togglePurchasingOptionsApprover: function() {
    var theForm = document.getElementById("editUsers");
    if (theForm.grantApprover.checked) {
      EditUserAccount.disablePurchasingOptionsApprover();
      //EditUserAccount.disableRequestApprovers();
      //EditUserAccount.disableLimitPurchases();
    } else {
      theForm.grantApprover.disabled = false;
      theForm.grantApprover.checked = false;
      EditUserAccount.enablePurchasingOptions();
      EditUserAccount.determineSelectApprover();
      EditUserAccount.determineLimitPurchases();
    }
  },
  enablePurchasingOptions: function() {
    var theForm = document.getElementById("editUsers");
    for (var i = 0; i < theForm.purchasingOption.length; i++) {
      theForm.purchasingOption[i].disabled = false;
    }
  },
  disablePurchasingOptions: function() {
    var theForm = document.getElementById("editUsers");
    for (var i = 0; i < theForm.purchasingOption.length; i++) {
      if (theForm.purchasingOption[i].value == "allowUnlimited") {
        theForm.purchasingOption[i].checked = true;
      }
      theForm.purchasingOption[i].disabled = true;
    }
  },
  
  disablePurchasingOptionsApprover: function() {
    var theForm = document.getElementById("editUsers");
    var checkUnlimited = false;
    for (var i = 0; i < theForm.purchasingOption.length; i++) {
      if (theForm.purchasingOption[i].value == "requestOnly") {
        if (theForm.purchasingOption[i].checked == true){
          checkUnlimited=true;
        }
        theForm.purchasingOption[i].disabled = true;
      }//end if request only button
    }//end for 
    if (checkUnlimited){
      for (var i = 0; i < theForm.purchasingOption.length; i++) {
        if (theForm.purchasingOption[i].value == "allowUnlimited") {
          theForm.purchasingOption[i].checked = true;
        }
      }
    }//end if checkUnlimited
  },
  
  determineLimitPurchases: function() {
    var theForm = document.getElementById("editUsers");
    if (theForm.dollars.value == null || theForm.dollars.value == "") {
      var bLimitPurchasesChecked = false;
      for (var i = 0; i < theForm.purchasingOption.length; i++) {
        if (theForm.purchasingOption[i].value == "limitPurchases") {
          if (theForm.purchasingOption[i].checked) {
            bLimitPurchasesChecked = true;
          }
        }
      }
  
      if (bLimitPurchasesChecked) {
        EditUserAccount.enableLimitPurchases();
      } else {
        EditUserAccount.disableLimitPurchases();
      }
    }
  },
  enableLimitPurchases: function() {
    var theForm = document.getElementById("editUsers");
    for (var i = 0; i < theForm.rdgLimitType.length; i++) {
      theForm.rdgLimitType[i].disabled = false;
    }
  
    theForm.every.disabled = false;
    theForm.dollars.disabled = false;
    theForm.time.disabled = false;
    theForm.dollars.select();
    theForm.dollars.focus();
  },
  disableLimitPurchases: function() {
    var theForm = document.getElementById("editUsers");
    for (var i = 0; i < theForm.rdgLimitType.length; i++) {
      theForm.rdgLimitType[i].checked = false;
      theForm.rdgLimitType[i].disabled = true;
    }
    theForm.every.disabled = true;
    theForm.dollars.disabled = true;
    theForm.dollars.value = "";
    theForm.time.value = "";
    theForm.time.disabled = true;
  },
  determineSelectApprover: function() {
    var theForm = document.getElementById("editUsers");
    var bUnlimitedPurchasesChecked = false;
    for (var i = 0; i < theForm.purchasingOption.length; i++) {
      if (theForm.purchasingOption[i].value == "allowUnlimited") {
        if (theForm.purchasingOption[i].checked) {
          bUnlimitedPurchasesChecked = true;
        }
      }
    }
  
    if (bUnlimitedPurchasesChecked) {
      EditUserAccount.disableRequestApprovers();
    } else {
      EditUserAccount.enableRequestApprovers();
    }
  },
  enableRequestApprovers: function() {
    var theForm = document.getElementById("editUsers");
    var checks = theForm.approverValuesSelected;
    
    if (typeof checks != "undefined") {
      var iLen = checks.length;
    
      if (typeof iLen == "undefined") {
        //only one checkbox
        var chkSingle = theForm.elements['approverValuesSelected'];
        chkSingle.disabled = false;
      } else {
        //two plus checkboxes
        for (var i = 0; i < checks.length; i++) {
          checks[i].disabled = false;
        }
      }
    }
  },
  disableRequestApprovers: function() {
    var theForm = document.getElementById("editUsers");
    var checks = theForm.approverValuesSelected;
    
    if (typeof checks != "undefined") {
      var iLen = checks.length;
    
      if (typeof iLen == "undefined") {
        //only one checkbox
        var chkSingle = theForm.elements['approverValuesSelected'];
        chkSingle.checked = false;
        chkSingle.disabled = true;
      } else {
        //two plus checkboxes
        for (var i = 0; i < checks.length; i++) {
          checks[i].checked = false;
          checks[i].disabled = true;
        }
      }
    }
  },
  focusDollar: function() {
    var theForm = document.getElementById("editUsers");
    theForm.dollars.select();
    theForm.dollars.focus();
  },
  focusTime: function() {
    var theForm = document.getElementById("editUsers");
    theForm.time.select();
    theForm.time.focus();
  },
  clearTime: function() {
    var theForm = document.getElementById("editUsers");
    theForm.time.value = "";
  }
};
//-----( END )-------------------------------------------------
var Locations = {
	form: Object,
	init: function() {
		Locations.form = document.getElementById("locationForm");
	},
  remove: function(url) {
    if (Locations.validate()) {
      if (confirm("Are you sure you want to remove these location(s)?")) {
        Locations.form.action = url;
				Locations.form.submit();
      }
    } else {
      alert("You must select at least one location to remove.");
    }
  },
  validate: function() {
    Locations.form = document.getElementById("locationForm");
    for (var i=0; i<Locations.form.elements.length; i++) {
      if (Locations.form.elements[i].checked == true) { return true; }
    }
    return false;
  }
};


//-----( @Users )----------------------------------------------
var Users = {
	form: Object,
	init: function() {
		Users.form = document.getElementById("userForm");
	},
	remove: function(url) {
		if (Users.validate()) {
			if (confirm("Are you sure you want to remove these user(s)?")) {
			    Users.form.action = url;
			    Users.form.submit();
      }
		} else {
			alert("You must select at least one user to remove.");
		}
	},
	validate: function() {
		for (var i=0; i<Users.form.elements.length; i++) {
			if (Users.form.elements[i].checked) { return true; }
		}
		return false;
	}
};
//-----( END )-------------------------------------------------

var Requests = {
  form: Object,
  update: function(url) {
    Requests.form = document.getElementById("requestForm");
		Requests.form.action = url;
    Requests.form.submit();
  },
  merge: function(url) {
    Requests.form = document.getElementById("requestForm");
    if (Requests.validate()) {
      var idConcat = ''; 		
      for(var i=0; i<Requests.form.elements.length; i++) {
      	 if (Requests.form.elements[i].name == 'requests[]' && Requests.form.elements[i].checked == true) {
	    idConcat = idConcat + Requests.form.elements[i].value + '|';			
	 }	 	
      }	
      if (idConcat.lastIndexOf('|') == idConcat.length-1) {
      	  idConcat = idConcat.substring(0, idConcat.length-1);
      }		
      var params = 'orderIds='+idConcat;		
      new Ajax.Request('/web/accounts.ex?action=validateMergeReqForClearance', 
	{method: 'post', 
	 onComplete: function(response)
		     {
			if (response.responseText == 'Y') {
			    Requests.form.action = url;
        		    Requests.form.submit();	
			}
			else {
			    alert('Cannot merge order requests with clearance and non-clearance items');	 	
			}	
		     }, 
	 parameters: params, 
	 evalScripts: true, 
	 asynchronus: true});  	
        		
      
    } else {
      alert("You must select at least one request to merge.");
    }
  },
  remove: function(url) {
    Requests.form = document.getElementById("requestForm");
    if (Requests.validate()) {
      if (confirm("Are you sure you want to remove these requests?")) {
        Requests.form.action = url;
        Requests.form.submit();
      }
    } else {
      alert("You must select at least one request to remove.");
    }
  },
  validate: function() {
    Requests.form = document.getElementById("requestForm");
    for (var i=0; i<Requests.form.elements.length; i++) {
      if (Requests.form.elements[i].checked == true) { return true; }
    }
    return false;
  }
};

// eQuotes

    function submitSearchForm(sPage) {
      var hPage, sForm;
      if (document.getElementById) {
        hPage = document.getElementById("page");
        sForm = document.getElementById("quoteSearch");
      }
      hPage.value = sPage;
      
      sForm.submit();
      return false;
    }
    
    function getDetailURL(sHeaderId, sQuoteNumber) {
      var sURL = '/web/eQuoteAction.ex?action=quoteDetail' 
      + '&hid=' + sHeaderId
      + '&qn=' + sQuoteNumber;
      window.location.href = sURL;
    }
    
// Custom Catalog
function toggleChildren(obj) {
  var parent = obj.parentNode;
  for (i=0; i<parent.childNodes.length; i++) {
    if (parent.childNodes[i] != obj) {
      if (parent.childNodes[i].className == 'hidden') {
        parent.childNodes[i].className = '';
      } else {
        parent.childNodes[i].className = 'hidden';
      }
    } else {
      var node = parent.childNodes[i].firstChild;
      
      do {
        if (node.className == "maximize") {
            node.className = "minimize";
        } else if (node.className == "minimize") {
            node.className = "maximize";
        }
      } while (node = node.nextSibling);
    }
  }
}






function recurseCheckbox(node, value) {
  if(node) {
    do {
      if (node.nodeType == 1) {
        if(node.type == 'checkbox') {
          node.checked = value;
        }
        recurseCheckbox(node.firstChild,value);
      }
    } while (node = node.nextSibling);
  }
}



var globalIsChecked = "";

function isCheckedBox(node) {
  if(node) {
    do {
      if (node.nodeType == 1) {
        if (node.checked == true) globalIsChecked += node.id + ",";
        isCheckedBox(node.firstChild);
      }
    } while (node = node.nextSibling);
    
    return globalIsChecked;
  }
}

var Locations = {
	form: Object,
	init: function() {
		Locations.form = document.getElementById("addressForm");
	},
  remove: function(url) {
    if (Locations.validate()) {
      if (confirm("Are you sure you want to remove these address(es)?")) {
        Locations.form.action = url;
        Locations.form.submit();
      }
    } else {
      alert("You must select at least one address to remove.");
    }
  },
  validate: function() {
    Locations.form = document.getElementById("addressForm");
    for (var i=0; i<Locations.form.elements.length; i++) {
      if (Locations.form.elements[i].checked == true) { return true; }
    }
    return false;
  }
};

// FIX EVENT
function changeCountry(country)
{
    var isDefault = document.getElementById("fDefault");
    if (isDefault)
    {
        isDefault = isDefault.value;
    }
    var isDefaultChkBx = document.getElementById("fDefaultChkBx");
    if (isDefaultChkBx)
    {
        isDefault = document.getElementById("fDefaultChkBx").checked;
    }
    var isPublic = document.getElementById("fPublic");
    if (isPublic)
    {
        isPublic = isPublic.value;
    }
    var isPublicChkBx = document.getElementById("fPublicChkBx");
    if (isPublicChkBx)
    {
        isPublic = document.getElementById("fPublicChkBx").checked;
    }
    var locAlias = document.getElementById("fAlias").value;
    var address1 = document.getElementById("fAddress1").value;
    var address2 = document.getElementById("fAddress2").value;
    var city = document.getElementById("fCity").value;
    var zipCode = document.getElementById("fPostalCode").value;
    
    var company = "";
    if (document.getElementById("companyName")) {
        company = document.getElementById("companyName").value;
    }
    
    if (document.getElementById("autoSelectState") != null) {
      document.getElementById("autoSelectState").innerHTML = "Getting list of states...";
    }
    
    fastenal.gotoUrl(SITE_ROOT + 'addresses.ex?action=changeCountry&country=' + escape(country) +
                                                                    '&address1=' + escape(address1) +
                                                                    '&address2=' + escape(address2) +
                                                                    '&city=' + escape(city) +
                                                                    '&zip=' + escape(zipCode) +
                                                                    '&isDefault=' + escape(isDefault) +
                                                                    '&isPublic=' + escape(isPublic) +
                                                                    '&locAlias=' + escape(locAlias) +
                                                                    '&companyName=' + escape(company) );
}

function changeState(state)
{
    var isDefault = document.getElementById("fDefault");
    if (isDefault)
    {
        isDefault = isDefault.value;
    }
    var isDefaultChkBx = document.getElementById("fDefaultChkBx");
    if (isDefaultChkBx)
    {
        isDefault = document.getElementById("fDefaultChkBx").checked;
    }
    var isPublic = document.getElementById("fPublic");
    if (isPublic)
    {
        isPublic = isPublic.value;
    }
    var isPublicChkBx = document.getElementById("fPublicChkBx");
    if (isPublicChkBx)
    {
        isPublic = document.getElementById("fPublicChkBx").checked;
    }
    var locAlias = document.getElementById("fAlias").value;
    var address1 = document.getElementById("fAddress1").value;
    var address2 = document.getElementById("fAddress2").value;
    var city = document.getElementById("fCity").value;
    var zipCode = document.getElementById("fPostalCode").value;
    
    var company = "";
    if (document.getElementById("companyName")) {
        company = document.getElementById("companyName").value;
    }
    
    document.getElementById("autoSelectCity").innerHTML = "Getting list of cities...";
    
    fastenal.gotoUrl(SITE_ROOT + 'addresses.ex?action=changeState&state=' + escape(state) +
                                                                '&address1=' + escape(address1) +
                                                                '&address2=' + escape(address2) +
                                                                '&city=' + escape(city) +
                                                                '&zip=' + escape(zipCode) +
                                                                '&isDefault=' + escape(isDefault) +
                                                                '&isPublic=' + escape(isPublic) +
                                                                '&locAlias=' + escape(locAlias) +
                                                                '&companyName=' + escape(company));
}


//Fast search
function fastChangeSortOption(p_sUrl) {
  fastenal.gotoUrl(p_sUrl);
}




//-----( @Templates )------------------------------------------
var Templates = {
	remove: function(url) {
		var alertMsg = "Are you sure you want to delete this template?";
		if (confirm(alertMsg)) { gotoUrl(url); }
	},
	removeItem: function(url) {
		var alertMsg = "Are you sure you want to delete this line item?";
		if (confirm(alertMsg)) { gotoUrl(url); }
	}
};
//-----( END )-------------------------------------------------
//-----(  END  - @Accounts )-------------------------------------------------------------------------

//-----( START - @History )--------------------------------------------------------------------------

modifyLink();

  function modifyLink(){
    var array = document.getElementsByTagName('a');
    var fastnetEIAcctNo = document.getElementById('fastnetEIAcctNo');
    var byPassLogin = 'true';
    for(i=0;i<array.length;i++){
      var tempLink = array[i].href;
      if(tempLink.indexOf('invoiceHistory.ex')!=-1 || tempLink.indexOf('fnei.ex')!=-1){
        if(tempLink.indexOf('fastnetEIAcctNo')==-1 && fastnetEIAcctNo != null){
            if(tempLink.indexOf('?')==-1){
                tempLink = tempLink+'?fastnetEIAcctNo='+fastnetEIAcctNo.value;;
            }
            else{
                tempLink = tempLink+'&fastnetEIAcctNo='+fastnetEIAcctNo.value;
            }
        }
        if(tempLink.indexOf('bypassLogin')==-1){
            if(tempLink.indexOf('?')==-1){
                tempLink = tempLink+'?bypassLogin='+byPassLogin;;
            }
            else{
                tempLink = tempLink+'&bypassLogin='+byPassLogin;
            }
        }
        array[i].href = tempLink;
      }
    }
  }

function validateLoginForm() {
       
    var userName = document.getElementById("obUsername");
    var password = document.getElementById("obPassword");

    if ((userName.value == null || userName.value == "") && (password.value == null || password.value == "")){
    alert("Fields cannot be empty.");
    return false;
    }else if(userName.value == null || userName.value == ""){
     alert("Username cannot be empty.");
     return false;
    }
    else if(password.value == null || password.value == ""){
     alert("Password cannot be empty.");
     return false;
    }
    else{
    return true;
          }
}

function validateStmtForm() {
       
    var custId = document.getElementById("fStmtLogoutCustId");
    var stmtId = document.getElementById("fLogoutStmtId");

    if ((custId.value == null || custId.value == "") && (stmtId.value == null || stmtId.value == "")){
    alert("Fields cannot be empty.");
    return false;
    }else if(custId.value == null || custId.value == ""){
     alert("Customer Id cannot be empty.");
     return false;
    }
    else if(stmtId.value == null || stmtId.value == ""){
     alert("Statement Id cannot be empty.");
     return false;
    }
    else{
    return true;
          }
}


function validateInvcFormLogOut() {
       
    var custId = document.getElementById("fInvcLogoutCustId");
    var invcId = document.getElementById("fLogoutInvcId");

    if ((custId.value == null || custId.value == "") && (invcId.value == null || invcId.value == "")){
    alert("Fields cannot be empty.");
    return false;
    }else if(custId.value == null || custId.value == ""){
     alert("Customer Id cannot be empty.");
     return false;
    }
    else if(invcId.value == null || invcId.value == ""){
     alert("Invoice Id cannot be empty.");
     return false;
    }
    else{
    return true;
          }
}

function validateInvcFormLogIn() {
       
    var invcId = document.getElementById("fLoginInvcId");

    if(invcId.value == null || invcId.value == ""){
     alert("Invoice Id cannot be empty.");
     return false;
    }
    else{
    return true;
          }
}


function resetCheckboxes() {
  //clear checkboxes to avoid bugginess with checkboxes checked and click on
  //sort column, subtotal dropdown, pagination and it does invoice lookup.  due 
  //in part to adding multipleInvoiceWindow functionality.  refactor later
  var myArray = window.document.frmStatement.elements;
  for (var i = 0; i < myArray.length; i++) {
    if ( myArray[i].name == "invoiceNumber" ) {
      myArray[i].checked = false;
    }
  }
  disableThis( window.document.frmStatement.btnPrintInvoices );
  window.document.frmStatement.checkAll.checked = false;
  window.document.frmStatement.checkAll.disabled = false;
}

function createMultipleInvoiceWindow() {
  window.open("about:blank", "multipleInvoiceWindow");
}


function printInvoice() {
  createMultipleInvoiceWindow();
  
  window.document.frmStatement.target = "multipleInvoiceWindow"; //open in new window rather than _self
  window.document.frmStatement.submit();

  resetCheckboxes();
}
    

function checkChecks(mycheck) {

  var myArray = window.document.frmStatement.elements;
  
  if ( mycheck.checked ) {
    enableThis( window.document.frmStatement.btnPrintInvoices );

    for (var i = 0; i < myArray.length; i++) {
      if ( myArray[i].name == "invoiceNumber" && myArray[i].checked == false ) {
        flag = true;
        break;
      }
    }
        
    if ( !flag ) {
      window.document.frmStatement.checkAll.checked = true;
    }

  } else {
    window.document.frmStatement.checkAll.checked = false;
    var flag = false;
      
    for (var i = 0; i < myArray.length; i++) {
      if ( myArray[i].name == "invoiceNumber" && myArray[i].checked ) {
        flag = true;
        break;
      }
    }
        
    if ( !flag ) {
      disableThis( window.document.frmStatement.btnPrintInvoices );
    }
  }
  
}
    

function doChecks(theForm, theArray) {

  theForm = document.getElementById(theForm);
  var myArray = window.document.frmStatement.elements;
  
  if ( window.document.frmStatement.checkAll.checked ) {
    for (var i = 0; i < myArray.length; i++) {
      if ( myArray[i].name == theArray ) {
        myArray[i].checked = true;
      }
    }
    
    enableThis( window.document.frmStatement.btnPrintInvoices );
  } else {
    for (var i = 0; i < myArray.length; i++) {
      if ( myArray[i].name == theArray ) {
        myArray[i].checked = false;
      }
    }
    
    disableThis( window.document.frmStatement.btnPrintInvoices );
  }
}
//-----(  END  - @History )--------------------------------------------------------------------------

//-----( START - @Locations )------------------------------------------------------------------------
/**
    Toggle between zip, state, and branch in store locator form (/locations/storeSelector.jsp)
*/
function toggleForm(formType) {
    var zipForm = "zipForm";
    var stateForm = "stateForm";
    var branchForm = "branchForm";
                
    if (document.getElementById) {
    
        if (formType == zipForm) {
            document.getElementById(stateForm).style.display = "none";
            document.getElementById(branchForm).style.display = "none";
                    
            document.getElementById(zipForm).style.display = "";
        } else if (formType == stateForm) {
            document.getElementById(zipForm).style.display = "none";
            document.getElementById(branchForm).style.display = "none";
                    
            document.getElementById(stateForm).style.display = ""; 
        } else if (formType == branchForm) {
            document.getElementById(zipForm).style.display = "none";
            document.getElementById(stateForm).style.display = "none";
                    
            document.getElementById(branchForm).style.display = "";
        }
    }
}
	
function toggleSearch(obj) {
    var zipCode = document.getElementById("locZip");
    var city = document.getElementById("locCity");
    var state = document.getElementById("locState");
    var country = document.getElementById("locCountry");
    var branchNumber = document.getElementById("locBranch");
    
    zipCode.style.display = "none";
    city.style.display = "none";
    state.style.display = "none";
    country.style.display = "none";
    branchNumber.style.display = "none";
    
    if (obj.value == "Zip") {
        zipCode.style.display = "";
    } else if (obj.value == "City") {
        city.style.display = "";
        state.style.display = "";
    } else if (obj.value == "Country") {
        country.style.display = "";        
    } else if (obj.value == "Branch") {
        branchNumber.style.display = "";
    }
}

function submitSearch() {
    obj = document.getElementById("searchOption");

    if (obj.value == "Zip") {
        document.getElementById("zipForm").submit();
    } else if (obj.value == "City") {
        document.getElementById("cityForm").submit();
    } else if (obj.value == "Country") {
        window.location.href = document.getElementById("country").value;
    } else if (obj.value == "Branch") {
        document.getElementById("branchForm").submit();
    }
}
//-----(  END  - @Locations )------------------------------------------------------------------------

//-----( START - @Products )-------------------------------------------------------------------------
var Details = {
  init: function() {
    if (document.getElementById("prodAvailability")) {
      showZipSearch();  
    }
  }
}

function showTableRow(rowId) {
	var showRowStyle = document.all ? 'inline' : 'table-row';
	document.getElementById(rowId).style.display = showRowStyle;	
}

function showZipSearch() {
    clearFields();
    //document.getElementById("rowZip").style.display = '';
    showTableRow("rowZip");	
    document.getElementById("rowCity").style.display = 'none';
    document.getElementById("rowState").style.display = 'none';
    //document.getElementById("rowDistance").style.display = '';
    showTableRow("rowDistance");
    showTableRow("rowInventory");
    document.getElementById("rowStoreCode").style.display = 'none';
}

function showCityState() {
    clearFields();
    document.getElementById("rowZip").style.display = 'none';
    //document.getElementById("rowCity").style.display = '';
    showTableRow("rowCity");	
    //document.getElementById("rowState").style.display = '';
    showTableRow("rowState");
    //document.getElementById("rowDistance").style.display = '';
    showTableRow("rowDistance");
    showTableRow("rowInventory");
    document.getElementById("rowStoreCode").style.display = 'none';
}

function showStoreCode() {
    clearFields();
    document.getElementById("rowZip").style.display = 'none';
    document.getElementById("rowCity").style.display = 'none';
    document.getElementById("rowState").style.display = 'none';
    document.getElementById("rowDistance").style.display = 'none';
    document.getElementById("rowInventory").style.display = 'none';
    showTableRow("rowStoreCode");
}

function showNothing() {
    clearFields();
    document.getElementById("rowZip").style.display = 'none';
    document.getElementById("rowCity").style.display = 'none';
    document.getElementById("rowState").style.display = 'none';
    document.getElementById("rowDistance").style.display = 'none';
    showTableRow("rowInventory");
    document.getElementById("rowStoreCode").style.display = 'none';
}

function changeSearchDetails(){
    var selectedIndex = document.getElementById("searchOption").selectedIndex;
    if(selectedIndex == 0){
        showZipSearch();
    }else if(selectedIndex == 1){
        showCityState();
    }else if(selectedIndex == 2){
        showStoreCode();
    }else if(selectedIndex == 3){
        showNothing();
    }
}

function clearFields() {
  var formInfo = document.getElementById("prodAvailability");
  
  for (var i=0; i < formInfo.length; i++) {
  
    if ((formInfo.elements[i].getAttribute("type") != "hidden") && 
        (formInfo.elements[i].type != "select-one") &&  
        (formInfo.elements[i].name != "btnSearch") && 
        (formInfo.elements[i].name != "searchOption")) {
      formInfo.elements[i].value = "";
    }
  }
}

// open a popup window with params
function popupUrl() {
	var newWindow = window.open(SITE_ROOT + "products/includes/greenProducts.html");
	newWindow.focus();
}

var Tabination = {
  toggle: function(e, obj) {
    e = e || window.event;
    target = e.target || e.srcElement;

    if (target) {    
      var tab = document.getElementById(target.id);
      var container = document.getElementById(target.id + "-container");
      
      if (tab && container && (tab.tagName != "UL")) {
        var ulTab = tab;
        while (ulTab != obj) {
          ulTab = ulTab.parentNode;
        }
        
        liTab = ulTab.children;
        for (i=0; i<liTab.length; i++) {
          if (liTab[i] == tab) {
            liTab[i].className = "active";
          } else {
            liTab[i].className = "";        
          }
        }
        
        var divContainers = document.getElementById(ulTab.id + "-container");
        if (divContainers) {
          divContainers = divContainers.children;
          
          for (i=0; i<divContainers.length; i++) {
            if (divContainers[i] == container) {
              divContainers[i].style.display = "block";
            } else {
              divContainers[i].style.display = "none";
            }
          }
        }
      }
      
      return false;
    }
  },
  
  init: function() {
    jQuery(".tabs").each(function(index, Element) {
        jQuery(Element).click(function(event) {
            Tabination.toggle(event, this);
        });
        
        if (Element.id != null && Element.id.length > 0) {
            jQuery("#" + Element.id + " li").each(function (j, obj) {
                if(!jQuery(obj).hasClass("active")) {
                    jQuery("#" + obj.id + "-container").hide();
                }
            });
        }
    });
  }
}

function showDetailTab(tab, obj) {
    allTabsUnselected = getElementsByClassName('productTab');
    allTabsSelected = getElementsByClassName('productTabSelected');
    allTabs = new Array();
    allTabContent = getElementsByClassName('productTabContent');
    
    if (document.getElementById('initialProductTab') != null) {
      var initialTab = document.getElementById('initialProductTab')
      initialTab.setAttribute("id", "");
    }
    
    for (i = 0; i < allTabsUnselected.length; i++) {
      allTabs.push(allTabsUnselected[i]);
    }
    
    for (i = 0; i < allTabsSelected.length; i++) {
      allTabs.push(allTabsSelected[i]);
    }
    
    for (i = 0; i < allTabs.length; i++) {
	/*allTabs[i].style.backgroundColor = '#00599c';
	allTabs[i].style.borderBottomColor = '#00599c';*/
	allTabs[i].className = 'productTab';
    }
    
    if (document.getElementById(tab) != null) {
	var selectedTab = document.getElementById(tab);
	
	for (i = 0; i < allTabContent.length; i++) {
	    
	    if (allTabContent[i] == selectedTab) {
		selectedTab.style.display = 'block';
		
		/*obj.style.backgroundColor = '#003b69';
		obj.style.borderBottomColor = '#003b69';*/
		
		obj.className = 'productTabSelected';
	    } else {
		allTabContent[i].style.display = 'none';
	    }
	}
    }
}

function displayQueryString() {
    fullURL = parent.document.URL;
    //alert(fullURL.substring(fullURL.indexOf('?'), fullURL.length));
    queryString = fullURL.substring(fullURL.indexOf('?')+1, fullURL.length);
    document.writeln('<a href="../products.ex?' + queryString + '#productResults" class="seeAllProducts">See Product Results</a>');
}

function validateAddToCart(form, qtyField) {
  if (document.getElementById) {
    var cartErrors = document.getElementById("addCartErrors");
    var qty = document.getElementById("addCartQty");
    
    if (cartErrors != null && qty != null) {
    
      if (isNaN(parseInt(qty.value))) {
	  cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be numeric</li><ul>";
	  cartErrors.style.display = "block";
	  
	  return false;
      } else if ((qty.value % 1) != 0) {
	  cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be an integer</li><ul>";
	  cartErrors.style.display = "block";
	  
	  return false;
      }else if (qty.value <= 0) {
	  cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be greater than zero</li><ul>";
	  cartErrors.style.display = "block";
	  
	  return false;
      }
    }
  }
  return true;
}

function submitFormLink(formName) {
  document.forms[formName].submit();
}

function showAllRefinements(ref) {
  var refinement = document.getElementById(ref);
  var showAllLink = document.getElementById(ref + "SeeAll");
  
  if (refinement && showAllLink) {
    refinements = refinement.getElementsByTagName("li");
  
    for (i = 0; i < refinements.length; i++) {
      refinements[i].style.display = "block";
    }
  
    showAllLink.style.display = "none";
  }
}

function swap(id) {
		var divholder = document.getElementById("content-divs");
		var contentholder = divholder.getElementsByTagName("div");
		for (i=0; i<contentholder.length; i++) {
			contentholder[i].style.display = "none";
		}
		var contentDiv = document.getElementById(id + "-content");
		contentDiv.style.display = "block";
		displayAllChildDivs(contentDiv);
}


function displayAllChildDivs(parentDiv){
	var childDivs = parentDiv.getElementsByTagName("div");
	//alert(childDivs.length);
  
  if (!childDivs.length || childDivs.length==0) {
    return;
  }
  
	for (i=0; i<childDivs.length; i++) {
		var childDiv = childDivs[i];
		childDiv.style.display = "block";
		//displayAllChildDivs(childDiv);
	}//end for
}//end displayAllChildDivs


function tabChange(tab) {
  var listContainer = document.getElementById("tabbed-product-menu");
  var listItemContainer = listContainer.getElementsByTagName("li");    
  for (i=0; i < listItemContainer.length; i++) {
    if (Element.hasClassName(listItemContainer[i], "active")) {
      Element.removeClassName(listItemContainer[i], "active");
      Element.addClassName(listItemContainer[i], "inactive");
    } 
  }
    var holdThis = document.getElementById(tab);
    if (holdThis.hasClassName("inactive")){
      Element.removeClassName(holdThis, "inactive");
    }
    Element.addClassName(holdThis, "active");
}
//-----(  END  - @Products )-------------------------------------------------------------------------

//-----( START - @Resources )------------------------------------------------------------------------

//-----(  END  - @Resources )------------------------------------------------------------------------

//-----( @OrderPad )-------------------------------------------
var OrderPad = {
  array : new Object(),
  obj : new Object(),  
  init: function() {
    OrderPad.obj["sku"] = document.getElementById("fastSku");
    OrderPad.obj["qty"] = document.getElementById("fastQty");    
    OrderPad.obj["description"] = document.getElementById("fastDescription");    
    OrderPad.obj["qtyPkg"] = document.getElementById("fastQtyPkg");    
    OrderPad.obj["price"] = document.getElementById("fastPrice");
    
    OrderPad.resetArray();
    
    jQuery("#fastSku").focus();
  },  
  checkArray: function() {
    for (var i in OrderPad.array)
      if (OrderPad.array[i] == null)
        return true;

    return false;
  },  
  resetArray: function () {
    for (var i in OrderPad.array) {
      OrderPad.array[i] = null;
    }

    for (var i in OrderPad.obj) {
      if (OrderPad.obj[i]) {
        OrderPad.obj[i].value = "";
      }
    }
  },  
  partFound: function (part, qtypkg, price, prodid, unk2) {
    OrderPad.displayPartNotFound(false);
    
    OrderPad.array['description'] = part;
    OrderPad.array['qtyPkg'] = qtypkg;
    OrderPad.array['price'] = price;
    OrderPad.array['prodId'] = prodid;
    OrderPad.array['partId'] = 1 + "|" + OrderPad.array["prodId"] + "|" + OrderPad.array["sku"];

    OrderPad.obj["description"].value = OrderPad.array["description"];
    OrderPad.obj["qtyPkg"].value = OrderPad.array["qtyPkg"];
    
    if (OrderPad.array['price'].indexOf(".") + 2 >= OrderPad.array['price'].length) {
        OrderPad.obj["price"].value = parseFloat(OrderPad.array['price']).toFixed(2);
    } else {
        OrderPad.obj["price"].value = OrderPad.array['price'];
    }
  },  
  setClearanceInfo : function(qty ,sku, productId){
    document.getElementById('orderProductType').value = 'C';
    document.getElementById('orderAvailableInvQty').value = qty;
    document.getElementById('sku').value = sku;
    document.getElementById('productId').value = productId;
  },
  setNonClearanceInfo : function(){
    document.getElementById('orderProductType').value = 'N';
  },
  checkClearance : function(){
    OrderPad.cleanMsg();
    var fastQty = document.getElementById('fastQty').value;
    
    if(!OrderPad.checkQty(fastQty))return false;
    if(document.getElementById('orderProductType').value != 'C')return true;
    
    var sku = document.getElementById('sku').value;
    var productId = document.getElementById('productId').value;
    if(document.getElementById('orderAvailableInvQty').value == 0){
        //alert("This item is out of stock and no longer available for order.");
        alert(OUT_OF_STOCK(sku));
        return false;
    }
    var avblQty = document.getElementById('orderAvailableInvQty').value;
    var cartQty = OrderPad.getCartItemQty(productId);
    
    if(avblQty - cartQty - fastQty < 0){
        var leftQty = (avblQty - cartQty)<0?0:(avblQty - cartQty);
        if(leftQty == 0){
            //alert("Product "+sku+" is only "+avblQty+" remaining and all of them are in your shopping cart.")
            alert("There is no additional inventory available for SKU "+sku+". This SKU will not be added to your shopping cart.");
            return false;
        }
        if(confirm(LESS_THAN_ORDER_QTY(sku, fastQty, leftQty))){
            document.getElementById('fastQty').value = leftQty;
            return true;
        }else
            return false;
    }else
        return true;
  },
  
  getCartItemQty : function(productId){
      var qty = 0;
      var myAjax = new Ajax.Request('/web/OrderPad.ex?action=getCartQty&productId='+productId, 
			{method: 'post', 
                         onComplete: function(response){
                                         var res = response.responseText;
                                         if(!res)return;
                                         qty = isNaN(res)?0:parseInt(res);
                                     }, 
	 		 parameters: null, 
	 		 evalScripts: false, 
	 		 asynchronous: false
                         }
                    ); 
      return qty; 	
  },
  checkQty : function(sQty){
    var tempMsg = '';
    if (isNaN(sQty)) {
        tempMsg = "Quantity must be numeric";
    } else if (parseInt(sQty)!= sQty) {
        tempMsg = "Quantity must be an integer"; 
    }else if (sQty <= 0) {
        tempMsg = "Quantity must be greater than zero";
    }else
        return true;
    
    var errDiv = document.getElementById('errDiv');
    var errList = document.getElementById('errList');
    
    var li_obj = document.createElement("li");
        li_obj.innerHTML = tempMsg;
    errList.appendChild(li_obj);
    errDiv.style.display = "block";
    return false;
  },
  cleanMsg : function(){
    var errDiv = document.getElementById('errDiv');
    var errList = document.getElementById('errList');
    
    errDiv.style.display = "none";
    while(errList.childNodes.length>1){
        errList.removeChild(errList.lastChild);
    }
  },
  displayPartNotFound : function(p_bDisplay) {
    var obj = document.getElementById('divPartNotFound');
    if (obj != null) {
      if (p_bDisplay) {
        obj.style.display = 'block';
      } else {
        obj.style.display = 'none';
      }
    }
  },
  partNotFound: function () {
    OrderPad.displayPartNotFound(true);
    
    var sWhichType = "F"; //null should never happen, but default it to Fastenal Part Number (F)
    
    var radioWhichType = jQuery("input[name=rdgWhichType]:checked");
    if (radioWhichType != null && radioWhichType.length > 0) {
      sWhichType = radioWhichType.val();
    }
    
    if (sWhichType == 'C') {
      OrderPad.addCustomerPart();
    } else { //'F'
      OrderPad.addFastenalPart();
    }
  },
  setInitialFocus: function () {
    if ((OrderPad.obj["sku"]) && (isVisible(OrderPad.obj["sku"])))
      OrderPad.obj["sku"].focus();
  },  
  // TODO Cleanup below  
  togglePopup: function (obj,cancel) {
    var obj = document.getElementById(obj) || obj;
    var submit = document.getElementById("fastSubmit");
      
    if (obj.style.display != 'none') {
      obj.style.display = 'none';
      
      if (cancel) {
        OrderPad.obj["qty"].setAttribute("disabled","disabled");
        submit.setAttribute("disabled","disabled");
        OrderPad.obj["sku"].value = "";
        OrderPad.obj["sku"].focus();
      }
    } else { 
      FAST.popupObject("newPopupWindow","framework_popup", obj.innerHTML);
    }
  },  
  formToggle: function (e, element) {
    e = e || window.keyup;
    var code = e.keyCode || e.which;
    
    if ((code == 1) || (e.type == 'click')) code = 13; // Checks to see if user clicks, then changes code to 13
    
    if (code == 13) {
      if (element.id == 'fastSku') {
        if (OrderPad.obj["sku"].value != '') {
          OrderPad.array["sku"] = OrderPad.obj["sku"].value;
          if (OrderPad.array["sku"].indexOf("'") > -1) {
            OrderPad.array["sku"] = OrderPad.array["sku"].replace(/'/g,"");
            OrderPad.obj["sku"].value = OrderPad.array["sku"];
          }
          OrderPad.ajaxGetProdDescription();
        } else {
          alert("You must enter a SKU");
          OrderPad.obj["sku"].focus();
        }
      } else {
        if(!OrderPad.checkClearance())return;
        OrderPad.array["qty"] = OrderPad.obj["qty"].value;
        OrderPad.obj["sku"].focus();
        
        if (trim(OrderPad.array["qty"]) == '' || (OrderPad.array["sku"]) < 1) {
          OrderPad.obj["qty"].value = '';
          OrderPad.array["qty"] = null;
          alert("You must enter a quantity");
          OrderPad.obj["qty"].focus();
        } 
      }
      
      if (OrderPad.array["sku"] != null && OrderPad.array["qty"] != null) {
        if (OrderPad.array["partId"] == null) {
          alert("Wait for the description to load, then add the item to the cart.");
        } else {
          OrderPad.ajaxAddProdToCart();
        }
      }
      
      return false;
    }
    
    return true;
  },  
  addFastenalPart: function () {
    OrderPad.array["qtyPkg"] = "1";
    OrderPad.array["description"] = "Custom Fastenal Part Number";
    OrderPad.array["price"] = "0";
    OrderPad.array["partId"] = "";
    
    var submit = document.getElementById("fastSubmit");
    
    OrderPad.obj["qty"].removeAttribute("disabled");
    submit.removeAttribute("disabled");
    OrderPad.obj["qty"].focus();
    
    OrderPad.obj["description"].value = OrderPad.array["description"];
    OrderPad.obj["qtyPkg"].value = "NA";
    OrderPad.obj["price"].value = "NA";
  },
  addCustomerPart: function () {
    OrderPad.array["qtyPkg"] = "1";
    OrderPad.array["description"] = "Customer Part Number";
    OrderPad.array["price"] = "0";
    OrderPad.array["partId"] = "";
    
    var submit = document.getElementById("fastSubmit");
    
    OrderPad.obj["qty"].removeAttribute("disabled");
    submit.removeAttribute("disabled");
    OrderPad.obj["qty"].focus();
    
    OrderPad.obj["description"].value = OrderPad.array["description"];
    OrderPad.obj["qtyPkg"].value = "NA";
    OrderPad.obj["price"].value = "NA";
  },
  cancelPart: function () {
    OrderPad.resetArray();
    OrderPad.displayPartNotFound(false);
    
    var submit = document.getElementById("fastSubmit");
    OrderPad.obj["qty"].setAttribute("disabled","disabled");
    submit.setAttribute("disabled","disabled");
    
    OrderPad.setInitialFocus();
  },
  ajaxGetProdDescription: function () {
    var sExec = "OrderPad.ex";
    var sParam = "action=lookup";
    var path = setPath( sExec, sParam );
    var params = "add=NO&Sku=" + OrderPad.array["sku"];
    
    var radioWhichType = jQuery("input[name=rdgWhichType]:checked");
    if (radioWhichType != null && radioWhichType.length > 0) {
      params = params + "&rdgWhichType=" + radioWhichType.val();
    }
    
    var submit = document.getElementById("fastSubmit");
    jQuery.get(path, params, function (response) {
      eval(response);
      OrderPad.obj["qty"].removeAttribute("disabled");
      submit.removeAttribute("disabled");
      OrderPad.obj["qty"].focus();
      return response;
    });
  },
  ajaxAddProdToCart: function () {
    if (OrderPad.array["description"] == "Custom Fastenal Part Number") {
        var sExec = "OrderPad.ex";
        var sParam = "action=add";
        var path = setPath( sExec, sParam );
        var params = "add=YES&Sku=" + OrderPad.array["sku"] + "&Quantity=" + OrderPad.array["qty"] + "&CustomType=Fastenal";
    } else if (OrderPad.array["description"] == "Customer Part Number") {
        var sExec = "OrderPad.ex";
        var sParam = "action=add";
        var path = setPath( sExec, sParam );
        var params = "add=YES&Sku=" + OrderPad.array["sku"] + "&Quantity=" + OrderPad.array["qty"] + "&CustomType=Customer";
    } else {
        var sExec = "products.ex";
        var sParam = "dispatch=addToCart";
        var path = setPath( sExec, sParam );
        var params = "productDetailId=" + OrderPad.array["partId"] + "&qty" + OrderPad.array["partId"] + "=" + OrderPad.array["qty"];
    }
    
    var submit = document.getElementById("fastSubmit");
    
    jQuery.get(path,params,function(response) {
      OrderPad.resetArray();
      OrderPad.displayPartNotFound(false);
      OrderPad.ajaxUpdateCart();
      OrderPad.obj["qty"].setAttribute("disabled","disabled");
      submit.setAttribute("disabled","disabled");
      return response;
    });
  },
  ajaxUpdateCart: function () {
    var sExec = "ShoppingCart.ex";
    var sParam = "printable=true";
    var path = setPath( sExec, sParam );
    
    var myAjax = new Ajax.Request(  path, 
                                        { method: 'get'
                                        , onComplete: function(response){
                                            document.getElementById("shoppingCartContainer").innerHTML = response.responseText;
                                            updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display');
                                            Help.init();
                                            return response.responseText;
                                            
                                        }
                                        , onFailure : function(response){
                                            document.getElementById("fastResponse").innerHTML = "<font style='color:red;'>An error occurred updating your shopping cart.  Try again.</font>";
                                        }
                                        , parameters: null
                                        , evalScripts: true
                                        , asynchronous: true}
                                      );
  },  
  promoFound: function()  {
    // Leave this blank; it gets called, but is not used in current development.
  },  
  promoNotFound: function () {
    // Leave this blank; it gets called, but is not used in current development.
  },
  getParameter: function ( name ){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }
};
//-----( END )-------------------------------------------------

//-----( @Performance )----------------------------------------
var Performance = {
  createCookie: function (name, value, days) {
    var expires = "";
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      expires = "; expires=" + date.toString();
    }
    else {
          expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
  },
  readCookie: function (name) {
    var ca = document.cookie.split(';');
    var nameEQ = name + "=";
    for(var i=0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)===' ') { c = c.substring(1, c.length); }
      if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); }
    }
    return null;
  },
  eraseCookie: function (name) {
    Performance.createCookie(name, "", -1);
  },
  
  getDateString: function () {
    var dt1 = new Date();
    var dtStr = dt1.getFullYear() + "/" + (dt1.getMonth() + 1) + "/" + dt1.getDate() + " " + 			dt1.getHours() + ":" + dt1.getMinutes() + ":" + dt1.getSeconds() + ":" + dt1.getMilliseconds();
    return dtStr;
  },
  
  trim: function (str) {
    var a = str.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
  },

  addOnBeforeUnloadEvent: function () {
    var oldOnBeforeUnload = window.onbeforeunload;
    window.onbeforeunload = function() {
      var ret;
      if ( oldOnBeforeUnload ) {
              ret = oldOnBeforeUnload();
      }
      Performance.captureTimeOnBeforeUnload();
      if ( ret ) return ret;
    }
  },
  
  captureTimeOnBeforeUnload: function () {
    Performance.createCookie('pagepostTime', Performance.getDateString() );
  },
  
  captureLoadTime: function ()  {
    Performance.restorePreviousPostTime();
    var docLocation = window.location.href;
    Performance.createCookie('pageLoadName', docLocation);
    Performance.createCookie('pageloadTime', Performance.getDateString());
    Performance.addOnBeforeUnloadEvent();
  },
  
  restorePreviousPostTime: function () {
    var prevPagePostTime = Performance.readCookie('pagepostTime');
    Performance.createCookie('prevPagePostTime', prevPagePostTime );
  },

  captureTimeShowModalDialog: function () {
    var args = Performance.captureTimeShowModalDialog.arguments;
    Performance.createCookie('pagepostTime', Performance.getDateString());
    if (args.length == 0) return Performance.origWindowMD();
    if (args.length == 1) return Performance.origWindowMD(args[0]);
    else if (args.length == 2) return Performance.origWindowMD(args[0],args[1]);
    else if (args.length == 3) return Performance.origWindowMD(args[0],args[1],args[2]);
    else return Performance.origWindowMD(args[0],args[1],args[2]);
  },

  captureSubmit: function () {	
    try {
      var allForms = document.forms;
      if ( allForms !== null ) {
        for ( var i=0; i < allForms.length; i++) {
          allForms[i].onsubmit = Performance.capturePostTimeForSubmit;
        }
      }
    }catch(e){}
    return true;
  },

  capturePostTimeForSubmit: function (event) {
    var target = event ? event.target : this;
    var actionValue = "UNKNOWN";
    if ( target.action != null && target.action != "undefined") {
      actionValue = target.action;
    }
    Performance.createCookie('pagepostTime', Performance.getDateString());
  },

  captureJavaScriptSubmit: function () {
    for (var form, i = 0; (form = document.forms[i]); ++i) {
      form.realSubmit = form.submit
      form.submit = function () {
        Performance.capturePostTimeForJavaScriptSubmit(this);
        this.realSubmit();
      }
    }
  },

  capturePostTimeForJavaScriptSubmit: function (aForm) {
    var actionValue = "UNKNOWN";
    if ( aForm.action != null && aForm.action != "undefined") {
      actionValue = aForm.action;
    }
    Performance.createCookie('pagepostTime', Performance.getDateString());
    return true;
  },

  captureLinkClicks: function () {
    try {
      var links = document.getElementsByTagName('a'); 		
      for (var i = 0; i < links.length; i++) { 
        var hrefString = links[i].href + "";
        if ( hrefString.indexOf("#") == -1 && hrefString !== "" && !Performance.hrefContainsScript(hrefString) ) {
          Events.addEvent(links[i],'click', function(event) {
            var event = event || window.event;
            var target = event.target || event.srcElement;
            Performance.capturePostTimeForLink(target);		      			      
          });
        }
      }
    } catch(e){}
    return true;		
  },

  hrefContainsScript: function (hrefString) {
    hrefString = hrefString.toUpperCase();
    hrefString = Performance.trim(hrefString);
    if ( hrefString.substring(0,10) == "JAVASCRIPT") {
            return true;
    }
    return false;
  },

  capturePostTimeForLink: function (aLink) {
    Performance.createCookie('pagepostTime', Performance.getDateString());
  },

  captureTimeAJAXSend: function (vData) {
    Performance.createCookie('pagepostTime', Performance.getDateString());	
    this.originalSend(vData);
  },
  captureTimeAJAXReturn: function (xmlHttp) {
    //Here you have to capture the load time of ajax return
  },
  
  origWindowMD: window.showModalDialog,

  init: function() {
    Performance.captureLinkClicks();
    Performance.captureSubmit();
    Performance.captureLoadTime();
    window.showModalDialog = Performance.captureTimeShowModalDialog;
    
    //ajax call to log time
    var path = SITE_ROOT + 'performance.ex?action=logPerformance';
    
    jQuery.get(path,"",function(response) {
      return null;
    });
  }
}
//-----( END )-------------------------------------------------

// customerProductCrossRef.js


var mtr = {
  hidden: null,
  messages: null,
  results: null,
  handleResponse: function (response, ioArgs){
    mtr.results.innerHTML = response;
  },
  handleFailure: function (response, textStatus, errorThrown){   
    mtr.hidden.innerHTML = response;
    if( response.responseText ){
      mtr.messages.innerHTML = response.responseText;
    }else{
      mtr.messages.innerHTML = response;
    }
    mtr.results.innerHTML = "";
  },    
  handleCreate: function (response, ioArgs){
    mtr.messages.innerHTML = "";
    mtr.hidden.innerHTML = "";
    mtr.results.innerHTML = document.getElementById("loading").innerHTML;
  },
  submit: function(e) {
    var e = e || window.event;
    var action = this.attributes["action"].value;
    mtr.handleCreate();

    jQuery.ajax({
      path: action,
      data: Forms.serialize(this),
      success: mtr.handleResponse,
      error: mtr.handleFailure
    });
    
    Events.stopDefaultAction(e);
  },    
  init: function() {
    var obj = document.getElementById("mtr_search");
    
    if (obj) {        
      mtr.hidden = document.getElementById("messages-hidden");
      mtr.messages = document.getElementById("messages");
      mtr.results = document.getElementById("mtrResults");
      
      Events.addEvent(obj,"submit",mtr.submit);
    }
  }
}

function rmWhiteSpace(str) {
  spaceFree = str.replace(/\s+/g,'');

  return spaceFree;   
}
  
var goToPageCallback =  function(response, ioArgs,otherArgs) {
			var curDiv = document.getElementById("attribute-table");
			if (curDiv) {
			    curDiv.innerHTML = response;
			    
			    var curTop = 0;
			    var obj = curDiv;
			    
			    do {
				curTop += obj.offsetTop;
			    } while (obj = obj.offsetParent);

			    //window.scroll(0, curTop);
			    if (curDiv.style.display == 'none') {
				    curDiv.style.display = 'block';
			    }
			}           
            		return response;
};

var doAjaxSortCallback =  function(response, ioArgs,otherArgs) {
                
                var shouldReloginMsg = "shouldRelogin";
                if(shouldReloginMsg==response){
                    //window.location.href = '<html:rewrite page="/accounts.ex"/>';
                    //window.location.href = "/web/accounts.ex";
                    window.location.href="<%=request.getContextPath() %>/accounts.ex";
                }else{
                  var sortID;
                if(otherArgs){
                    sortID = otherArgs.sortID;
                }
		var curDiv = document.getElementById("attribute-table");
			
		if (curDiv) {
			curDiv.innerHTML = response;
			
			if (curDiv.style.display == 'none') {
			    curDiv.style.display = 'block';
			}
			
			var headLabel = document.getElementById(rmWhiteSpace(sortID) + "Head");
    
			if (sortOrder == 1) { 
			    if (headLabel) {
				insertAfter(arrowDesc, headLabel);
				//alert(headingCell.innerHTML);
			    }
			} else {
			
			    if (headLabel) {
				insertAfter(arrowAsc, headLabel);
				//alert(headingCell.innerHTML);
			    }
			}
                    }
                }
           
		return response;
}

//-----( @Rotate )---------------------------------------------
var Rotate = {
  rotate: function (e) {
    e = e || window.event;
    target = e.target || e.srcElement;
    obj = target.container;
    items = target.items;
    direction = target.direction;  
    if (obj.scroll.length > items) {
      if (direction == 0) {  
        obj.pos--;
        if (obj.pos < 0) {
          obj.pos = ((obj.scroll.length - (obj.scroll.length % items)) / items);
          if (obj.scroll.length % items == 0) obj.pos--;
        }
      } else {
        obj.pos++;
        if (obj.pos * items >= obj.scroll.length) obj.pos = 0;
      }
      
      for (i=0;i<obj.scroll.length;i++) {
        if (( i >= obj.pos*items)
           && (i < (obj.pos+1)*items)) {
          obj.scroll[i].style.display = "block";
        } else {
          obj.scroll[i].style.display = "none";
        }
      }

      if (objCount = document.getElementById(obj.id + "-count")) objCount.innerHTML = ((obj.pos) * items + 1) + " - " + ((obj.pos + 1) * items < obj.scroll.length ? (obj.pos + 1) * items : obj.scroll.length) +  " of " + obj.scroll.length;
    }
  },

  init: function (e) {
    var obj = getElementsByClassName("hor-scroller");
    
    for (i=0; i<obj.length; i++) {
      var container = document.getElementById(obj[i].id + "-container");
      var children = obj[i].children;

      if (container && children && obj[i] && obj[i].attributes["items"]) {
        var noItems = obj[i].attributes["items"].value;
        
        if (noItems) {
          obj[i].scroll = [];
          obj[i].pos = 0;
          
          if (noItems < children.length) {
            if (cntParent = document.getElementById(obj[i].id + "-header")) {
              var divCount = FAST.createObject("div", cntParent,obj[i].id + "-count", "", "");
              cntParent.style.position = "relative";
              if (divCount) {
                divCount.innerHTML = "1 - " + noItems +  " of " + children.length;
                divCount.className = "small";
                FAST.styleObject(divCount, {
                  "position": "absolute",
                  "bottom": "5px",
                  "right": "5px"
                });
              }
            }
            
            obj[i].style.margin = "0px 30px";
            var left = FAST.createObject("img", container, obj[i].id + "-left", "", ""); 
            var right = FAST.createObject("img", container, obj[i].id + "-right", "", "");
            
            left.src = SITE_ROOT + "common/images/misc/arrow-left.gif";
            right.src = SITE_ROOT + "common/images/misc/arrow-right.gif";
            
            left.alt = right.alt = "Show More";
            left.container = right.container = obj[i];
            left.items = right.items = noItems;
            
            left.direction = 0; right.direction = 1;
            
            FAST.styleObject(left, {
              "position": "absolute",
              "left": 0 + "px",
              "top": 50 + "%",
              "marginTop": -25 + "px",
              "cursor": "pointer"
            });
            
            FAST.styleObject(right, {
              "position": "absolute",
              "right": 0 + "px",
              "top": 50 + "%",
              "marginTop": -25 + "px",
              "cursor": "pointer"
            });
  
            Events.addEvent(left, "click", Rotate.rotate);
            Events.addEvent(right, "click", Rotate.rotate);
  
            for (j=0; j<children.length; j++) {
              if (children[j].nodeType == 1) {
                obj[i].scroll.push(children[j]);
                if (i>(noItems-1)) {
                  children[j].style.display = "none";
                }
              }
            }
          }
        }
      }
    }
  }
}
//-----( END )-------------------------------------------------

var Clearance = {
	// the qty input class
	qtyClassName : 'cartQtyTextBox',	
		
	// Clearance product type
	clearanceProType : 'C',
        normalProType : 'N',
        normalAndClearanceProTypeMixed : 'N+C',
		
	// Error message
	errDiv : null,
	errList: null,
	
        tpltErrMsg : "Your cart includes clearance product which can't be added to Order Template",
        
        // init errmsg
        init : function(){
            Clearance.errDiv = document.getElementById('errDiv');
            Clearance.errList = document.getElementById('errList');
            Clearance.cleanErrMsg();
        },
        
	// get all qty input list
	getElementsByClassName : function(){
            var res = [];
            var temp = getElementsByClassName(Clearance.qtyClassName);
            for(i=0;i<temp.length;i++){
                if(temp[i].getAttribute("sku"))
                    res[res.length] = temp[i];	
            }
            return res;
	},
		
	checkQty : function(obj){
            var tempMsg = "Product "+ obj.getAttribute("sku") +" ";
            if (isNaN(obj.value)) {
   		tempMsg = tempMsg + "quantity must be numeric";
            }else if(parseInt(obj.value)!= obj.value){
   		tempMsg = tempMsg + "quantity must be an integer"; 
            }else if (obj.value <= 0) {
   		tempMsg = tempMsg + "quantity must be greater than zero";
            }else if(obj.getAttribute("productType") == Clearance.clearanceProType){
  		if(obj.getAttribute("aQty") - 1 < 0)
                    tempMsg = tempMsg + "is out of stock, please delete it from your order";
                else if(obj.value - obj.getAttribute("aQty") > 0)
                    tempMsg = tempMsg + "is no longer available in the quantity you requested ("+obj.value+"). Please change your order quantity to "+obj.getAttribute("aQty") +".";
  		else
                    return;
            }else
   		return;
 
            var newMsg = document.createElement("li");
     		newMsg.innerHTML = tempMsg;
            Clearance.errList.appendChild(newMsg);
        },
		
	cleanErrMsg : function(){
            if(document.getElementById('htmlErrDiv'))
		document.getElementById('htmlErrDiv').style.display = "none";
	    Clearance.errDiv.style.display = "none";
            while(Clearance.errList.childNodes.length>1){
     		Clearance.errList.removeChild(Clearance.errList.lastChild);
            }
	},
		
	showErrMsg : function(){
            if(Clearance.errList.childNodes.length > 1){
		Clearance.errDiv.style.display = "block";
		return false;
	    }else
		return true;
	},
		
	checkAllQty : function(){
            Clearance.init();
				
            var objList = Clearance.getElementsByClassName();
            for(i=0;i<objList.length;i++){
                Clearance.checkQty(objList[i]);			
            }

	    return Clearance.showErrMsg();
	},
        
        checkTemplate : function(){
            Clearance.init();
            
            var temp = getElementsByClassName(Clearance.qtyClassName);
            for(i=0;i<temp.length;i++){
                if(temp[i].getAttribute("sku") &&  temp[i].getAttribute("productType") == Clearance.clearanceProType){
                    var newMsg = document.createElement("li");
                    newMsg.innerHTML = Clearance.tpltErrMsg;
                    Clearance.errList.appendChild(newMsg);
                    break;
                }                    	
            }
            
            return Clearance.showErrMsg();
        },
        
        isHasClearanceAndNonClearanceItems : function(){
                var returnValue = false;
                var hasClearanceItem = false;
                var hasNonClearanceItem = false;
		var objList = Clearance.getElementsByClassName();
			for(i=0;i<objList.length;i++){
                            var inputObj = objList[i];
                            if(inputObj.getAttribute("productType") == Clearance.clearanceProType){
                                hasClearanceItem = true;
                            }else{
                                hasNonClearanceItem = true;
                            }
                            if(hasClearanceItem && hasNonClearanceItem){
                                returnValue = true;
                                break;
                            }
			}
                return returnValue;
    },
    
    getCartProductsType : function(){
                var returnValue = "";
                var normalAndClearanceItemsMixed = false;
                var hasClearanceItem = false;
                var hasNonClearanceItem = false;
		var objList = Clearance.getElementsByClassName();
			for(i=0;i<objList.length;i++){
                            var inputObj = objList[i];
                            if(inputObj.getAttribute("productType") == Clearance.clearanceProType){
                                hasClearanceItem = true;
                            }else{
                                hasNonClearanceItem = true;
                            }
                            if(hasClearanceItem && hasNonClearanceItem){
                                normalAndClearanceItemsMixed = true;
                                break;
                            }
			}
                if(normalAndClearanceItemsMixed){
                    returnValue = Clearance.normalAndClearanceProTypeMixed;
                }else if(hasClearanceItem){
                    returnValue = Clearance.clearanceProType;
                }else if(hasNonClearanceItem){
                    returnValue = Clearance.normalProType;
                }
                return returnValue;        
    }
}

function refineResults(e, me, obj) {
  var e = e || window.event;
  obj = document.getElementById(obj) || obj;
  
  if (typeof obj == 'object') {
    obj = obj.getElementsByTagName("LI");
    var count = 0; var href = null;
    
    for (i=0; i<obj.length; i++) {
      var search = (obj[i].innerText || obj[i].textContent).toLowerCase();
      if (search.indexOf("(") != -1) search = search.substring(0,search.indexOf("(")); // ignore the product count, or "(".
      if (search.indexOf(me.value.toLowerCase()) != -1) {
        obj[i].style.display = "block";
        href = obj[i].getElementsByTagName("A")[0].href;
        count++;
      } else {
        obj[i].style.display = "none";
      }
    }
    
    if (e) {
      var key = e.keyCode || e.which;
      if (key == 13 && count == 1) window.location = href;
    }
  }
}

//session management code
var countdownTimer;
var initTimer;
var warningMarkup = "";

var Session = {
  init: function(maxInactive, sessionWarnDivisor) {
    var maxInactiveTime = maxInactive * 1000;
    var warnInactiveTime = maxInactiveTime / sessionWarnDivisor;
    
    if (warnInactiveTime >= 0) {
      initTimer = setTimeout(function(){Session.warn(maxInactiveTime, warnInactiveTime, sessionWarnDivisor)}, maxInactiveTime - warnInactiveTime);
    }
  },
  
  checkSaved: function() {
    if ( readCookie("fast-opt1") != null && 
        (readCookie("fast-opt2") != null || readCookie("fast-opt2-new") != null) ) {
      return true;
    } else {
      return false;
    }
  },
  
  warn: function(maxInactiveTime, warnInactiveTime, sessionWarnDivisor) {
    var currentTime = new Date();
    var futureTime = new Date(currentTime.getTime() + warnInactiveTime);
    
    if (!Session.checkSaved()) {
      clearTimeout(initTimer);
      
      warningMarkup = "<div id=\"sessionWarning\"><span id=\"warnMessage\">Your session will expire soon.  <span class=\"pseudoLink\">Remain logged in.<\/span><\/span><\/div>"; 
      jQuery("#wrap").prepend(warningMarkup);
      
      Session.showRemainingTime(futureTime, maxInactiveTime);
    
      jQuery("#sessionWarning").click( function() {
        var loc = SITE_ROOT + "sessionCheck.ex?action=resetSession";
        
        jQuery.ajax({
          url: loc,
          success: function(response, textStatus) {
            clearTimeout(countdownTimer);
            jQuery("#sessionWarning").detach();
            Session.init(maxInactiveTime / 1000, sessionWarnDivisor);
          },
          error: function(response, textStatus, errorThrown) {
            clearTimeout(countdownTimer);
            jQuery("#sessionWarning").detach();
            console.error("HTTP status code:", textStatus);
          }
        });
      });
    }
  },
  
  showRemainingTime: function(timeRemaining, maxInactiveTime) {
    var currentTime = new Date();
    var remainingTime = timeRemaining - currentTime.getTime();
    var warnTimeMessage = "";
    
    if (remainingTime > 0) {
      days = 0;
      hours = 0;
      mins = 0;
      secs = 0;
      timeLeft = "";
  
      remainingTime = Math.floor(remainingTime / 1000);
  
      days = Math.floor(remainingTime / 86400);
      remainingTime = remainingTime % 86400;
  
      hours = Math.floor(remainingTime / 3600);
      remainingTime = remainingTime % 3600;
  
      mins = Math.floor(remainingTime / 60);
      remainingTime = remainingTime % 60;
  
      secs = Math.floor(remainingTime);
      
      if (days != 0) {
        timeLeft += days + " day" + ((days != 1 ) ? "s" : "") + ", ";
      }
		  
      if (days != 0 || hours != 0) {
        timeLeft += hours + " hour" + ((hours != 1 ) ? "s" : "") + ", ";
      }
		
      if (days != 0 || hours != 0 || mins != 0) {
        timeLeft += mins + " minute" + ((mins != 1) ? "s" : "") + ", ";
      }
      
      timeLeft += secs + " seconds";
      
      warnTimeMessage = "Your session will expire in " + timeLeft + ".  <span class=\"pseudoLink\">Stay signed in.<\/span>";
  
      jQuery("#warnMessage").html(warnTimeMessage); 
        
      countdownTimer = setTimeout(function(){Session.showRemainingTime(timeRemaining, maxInactiveTime)}, 1000);
    } else {
      Session.expire(maxInactiveTime);
    }
  },
  
  showSessionTimeout: function() {
    warningMarkup = "<div id=\"sessionWarning\"><span id=\"warnMessage\">Your session has expired.  Sign in again.<\/span><\/div>"; 
    jQuery("#wrap").prepend(warningMarkup); 
  },
  
  expire: function(maxInactiveTime) {
    var loc = SITE_ROOT + "sessionCheck.ex";
    
    clearTimeout(countdownTimer);
    
    jQuery.ajax({
      url: loc,
      success: function(response, textStatus) {
        if (parseInt(response.trim()) >=  maxInactiveTime) {
          encodedURI = encodeURIComponent(location.protocol + "//" + location.host + location.pathname + location.search);
          window.location.href = SITE_ROOT + "login/signin.ex?sessionTimeout=true&pageFrom=" + encodedURI;
        } else {
          jQuery("#sessionWarning").detach();
          Session.init(parseInt(response.trim()) / 1000, sessionWarnDivisor);
        }
      },
      error: function(response, textStatus, errorThrown) {
        console.error("HTTP status code:", textStatus);
      }
    });
  }
}; 

(function() {
  var divGovernment,
      divInfo,
      btnList,
      btnGovernment;
                  
  function showElement(obj) {
    jQuery(obj.parentNode).addClass("box");
    obj.parentNode.appendChild(divInfo);
    
    if (obj == btnGovernment) {
      jQuery(divGovernment).removeClass("hidden");
    } else {
      jQuery(divGovernment).addClass("hidden");
    }
  }
  
  function hideElement(obj) {
    jQuery(obj.parentNode).removeClass("box");
  }

  function Initialize() {
    btnGovernment = document.getElementById("accountStatusG");
    divGovernment = document.getElementById("governmentOptions");
    divInfo = document.getElementById("additionalInfo");
    btnList = [];

    (document.getElementById("accountStatusP")) ? btnList.push(document.getElementById("accountStatusP")) : null;
    (document.getElementById("accountStatusI")) ? btnList.push(document.getElementById("accountStatusI")) : null;
    (document.getElementById("accountStatusG")) ? btnList.push(document.getElementById("accountStatusG")) : null;
    
    for (var i=0; i < btnList.length; i++) {
      if (btnList[i].checked) {
        showElement(btnList[i]);
      }
    
      Events.addEvent(btnList[i], "click", function() {
        for (var j=0; j < btnList.length; j++) {
          (btnList[j] == this) ? showElement(btnList[j]) : hideElement(btnList[j]);
        }
      });
    }
  }
  
  window.Registration = {
    Initialize: Initialize
  }
})(window);

//share shopping cart in shopping cart prompted page
var ShareShoppingCart = {
    cleanText : function(obj){
        if(obj.getAttribute("isFirst")!="true")return;
        obj.value = "";
        obj.style.color = "#000";
        obj.setAttribute("isFirst", "false");
    },
    
    checkMail : function(str){
        var mails = str.split(",");
        var pattern = /^(?:[a-z\d]+[_\-\+\.]?)*[a-z\d]+@(?:([a-z\d]+\-?)*[a-z\d]+\.)+([a-z]{2,})+$/i;
        var mailTo = "";
        for(i=0;i<mails.length;i++){
            if(mails[i].trim()){
                if(pattern.test(mails[i].trim())){
                    mailTo = mailTo + " " + mails[i].trim();
                }else{
                    ShareShoppingCart.showMsg("Please enter a valid email address to send this Shopping Cart.");
                    return null;
                }
            }
        }
        
        return mailTo;
    },
    
    showMsg : function(msg){
        document.getElementById("cartErrMsg").innerHTML = msg;
        document.getElementById("cartErrMsg").style.display = "";
    },
    
    clearMsg : function(){
        document.getElementById("cartErrMsg").innerHTML = "";
        document.getElementById("cartErrMsg").style.display = "none";
    },
    
    sendMail : function(){
        ShareShoppingCart.clearMsg();
        if(!document.forms["mailCart"].userName.value.trim()){ShareShoppingCart.showMsg("Please Input Your Name.");return;}
        if(!document.forms["mailCart"].mailTo.value.trim()){ShareShoppingCart.showMsg("Please enter a valid email address to send this Shopping Cart.");return;}
        if(!document.forms["mailCart"].message.value.trim()){ShareShoppingCart.showMsg("Please Input the Mail Message.");return;}
        var mailTo = ShareShoppingCart.checkMail(document.forms["mailCart"].mailTo.value.trim());
        if(mailTo == ""){ShareShoppingCart.showMsg("Please enter a valid email address to send this Shopping Cart.");return;}
        if(mailTo == null)return;
        
        if(document.forms["mailCart"].isCC.checked == true)mailTo = mailTo + " " + document.forms["mailCart"].userMail.value;
        
        var params = "mailTo=" + mailTo.trim()
                   + "&userName=" + document.forms["mailCart"].userName.value.trim()
                   + "&message=" + document.forms["mailCart"].message.value.trim();
        document.getElementById("cartSendMailBtn").disabled = true;
        new Ajax.Request('/web/ShoppingCart.ex?action=sendEmail', 
                        {method: 'post', 
                         onComplete: function(response){
                                          var result = response.responseText;
                                          if(result=="0"){
                                              document.getElementById("cartSendMailBtn").style.display="none";
                                              //document.getElementById("cartCloseBtn").style.display="";
                                              document.getElementById("cartErrMsg").className="success"; 
                                              ShareShoppingCart.showMsg("Mail Sent Successfully.");
                                              window.setTimeout(ShareShoppingCart.closeFrame, 2000);
                                          }else if(result == "1"){
                                              document.getElementById("cartSendMailBtn").disabled = false;
                                              ShareShoppingCart.showMsg("There is no valid product in your shopping cart.");
                                          }else{
                                              document.getElementById("cartSendMailBtn").disabled = false;
                                              ShareShoppingCart.showMsg("There is a server internal error, please try again later.");
                                          }
                                      }, 
                          parameters: params, 
                          evalScripts: true, 
                          asynchronus: true}); 
    },
    
    closeFrame : function(){
        framework_popout(this);
    },
    
    limitLength : function(obj){
        var maxLength = 200;
        if(obj.value.length <= maxLength)return;
        obj.value = obj.value.substring(0, maxLength);
    }
};


//Autocomplete search box
function doSearchBox(sSearchTermField) {
  var objSearchBox = document.getElementById(sSearchTermField);
  if (objSearchBox != null) {
    var sSearchTerm = objSearchBox.value;
    if (sSearchTerm != null) {
      sSearchTerm = jQuery.trim(sSearchTerm);
      
      // magic from the framework object
      var count = 0;
      for (i in objSearchBox.tags) {
        if (objSearchBox.tags[i].title && (objSearchBox.value.toLowerCase() == objSearchBox.tags[i].title.toLowerCase())) {
          loc = objSearchBox.tags[i].href;
          count++;
        }
      }

      if (count == 1) {
        fastenal.gotoUrl(loc);
        return;
      }
      // end magic
      
      if (sSearchTerm != '') {
        fastenal.gotoUrl('/web/Search.ex?action=prepSearch&searchterm=' + urlEncode(sSearchTerm));
      }
    }
  }
}

