var submitted = false;

function submitMe()
{
	if ( submitted == false )
	{
		submitted = true;
		showWait();
		return true;
	} else return false;

}

function saveSelected(sSaveAction, sPageNumber,form)
{
  if(!checkPageBoxes(form)){
  form.clearDisplayed.value = "yes";
  }
  form.saveaction.value = sSaveAction;
  form.pagenumber.value = sPageNumber;
  form.submit();
}

/**
 * Submit a form to a different action than that specified on the form element.
 * WARNING:  This will not call any onsubmit method specified on the form.
 */
function submitAction(form, action) {
	form.action = action; 
	form.submit();
}

function navigateToPage(form, page) {
	form.pageClicked.value = page;
	form.submit();
}

function checkPageBoxes(form) {

	var formField;
	var fieldType;
	var fieldName;
	var number = 0;

	for (var i = 0; i < form.elements.length; i++) {
		formField = form.elements[i];
		fieldType = formField.type;
		if (fieldType == 'checkbox') {
			if (formField.checked == '1') {
				number++;
			}
		}
	}
	if (number > 0) {
		return true;
	} else {
		return false;
	}
}

function checkAll(form, val)  
{

  for (var i = 0; i < form.elements.length; i++) 
  {
    var formField = form.elements[i]
    var fieldType = formField.type
    if (fieldType == 'checkbox') 
    {
      formField.checked = val;
    }
  }
}

function refreshAction(form, action)
{
	form.action.value = action; 
	form.submit();
}

function getContext(pathname)
{
	return pathname.substring(pathname.indexOf("/"), pathname.lastIndexOf("/"));
}

function viewDetails(form, itm_id, itm_uom, multi, itemIndex, custItm_id)
{
	var context = getContext(document.location.pathname);	
	var url = "";
	var qty = 1; // default qty to 1

	//Pull the Qty out of the form.  The variable is built with a combination of the Item ID and QtyUOM.
	for (var i = 0; i < form.elements.length; i++) 
  	{
  		formField = form.elements[i];
  		fieldName = formField.name;
  		
  		if (fieldName == "qty"+itm_id+itm_uom)
      	{
      		if (IsNumeric(formField.value) && IsNumeric(multi))
      		{
	      		qty = formField.value * multi;
	      		if (IsPositiveInteger(qty)) {
	      			qty = qty * multi;
	      		}
      		}
      		else if (formField.value == "") {
      			qty = 1; // default qty to 1 if left blank by user
      		}
      		else {
      			qty = 0; // handle invalid qty (change to 0 to avoid URL encoding problems)
      		}
      		break;
      	}
  	}
	
	url = "/itemDetail.do?itm_id=" + itm_id + itemIndex + "&orderQty=" + qty + "&cust_item=" + custItm_id;
	window.location = context + url ;  	
}

function cartAdd(form, itm_id, itm_uom, multi)
{

	var context = getContext(document.location.pathname);
	var qty = 1; // default qty to 1
	var uom = "";
	var url = "";
	for (var i = 0; i < form.elements.length; i++) 
  	{
  		formField = form.elements[i];
  		fieldName = formField.name;
  		if (fieldName == "qty"+itm_id+itm_uom)
      	{
      		if (IsNumeric(formField.value) && IsNumeric(multi))
      		{
	      		qty = formField.value * multi;
	      		if (IsPositiveInteger(qty)) {
	      			qty = qty * multi;
	      		}
      		}
      		else if (formField.value == "") {
      			qty = 1; // default qty to 1 if left blank by user
      		}
      		else {
      			qty = 0; // handle invalid qty (change to 0 to avoid URL encoding problems)
      		}
      		break;
      	}
  	}
  	
  	for (var i = 0; i < form.elements.length; i++) 
  	{
  		formField = form.elements[i];
  		fieldName = formField.name;
  		if (fieldName == "uom"+itm_id)
      	{
      		uom = formField.value;
      		break;
      	}
  	}
  	
  	
	url = context+"/cartAddItem.do?order_qty="+qty+"&itm_id="+itm_id+"&order_uom="+uom;
	document.location = url;  	
}

function trim (str) 
{
  while (str.charAt(0) == ' ')
    str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
    str = str.substring(0, str.length - 1);
  return str;
}

function IsInteger(sText)
{
  var ValidChars = "0123456789.-";
  var IsNumber=true;
  var Char;
  
  for (i = 0; i < sText.length && IsNumber == true; i++) 
  {
    Char = sText.charAt(i); 
    if (ValidChars.indexOf(Char) == -1) 
    {
      IsNumber = false;
    }
  }
  return IsNumber;  
}

function IsPositiveInteger(sText)
{
  var ValidChars = "0123456789.";
  var IsNumber=true;
  var Char;
  
  for (i = 0; i < sText.length && IsNumber == true; i++) 
  {
    Char = sText.charAt(i); 
    if (ValidChars.indexOf(Char) == -1) 
    {
      IsNumber = false;
    }
  }
  return IsNumber;  
}

function hideAdvSearch()
{
	document.all['advSearch'].style.visibility = 'hidden';
	document.all['advSearch'].style.display = 'none';
	document.all['advBrdCrmb'].style.visibility = 'hidden';
	document.all['advBrdCrmb'].style.display = 'none';
}

function showAdvSearch()
{
	document.all['advBrdCrmb'].style.visibility = 'visible';
	document.all['advBrdCrmb'].style.display = 'block';
	document.all['advSearch'].style.visibility = 'visible';
	document.all['advSearch'].style.display = 'block';
	if ( document.getElementById('fromItmNum') != null )
	{
		itemSearchForm.fromItmNum.focus();
	}
}

function hideWait()
{
    document.getElementById('waitMessage').style.visibility = 'hidden';
	document.getElementById('waitMessage').style.display = 'none'; 
}

function showWait()
{
	document.getElementById('waitMessage').style.visibility = 'visible';
    document.getElementById('waitMessage').style.display = 'block';
}

function IsNumeric(sText, greaterthanzerocheck)
{
  var ValidChars = "0123456789.-";
  var IsNumber=true;
  var Char;
  var hasDecimal=false;
  var greaterthanzero = false;
  if (sText == "" || sText == ".")
  {
  	return false; 
  }
  for (i = 0; i < sText.length && IsNumber == true; i++) 
  {
    Char = sText.charAt(i); 
	if ( Char == "." )
	{
		if ( hasDecimal == true )
		{
			IsNumber = false;
		}
		else 
		{
			hasDecimal = true;
		}
	}
    if (ValidChars.indexOf(Char) == -1) 
    {
      IsNumber = false;
    }
    else
    {
    	if ( Char != "0" && Char != "." )
    	{
    		greaterthanzero = true;
    	}
    }
  }
  if ( greaterthanzerocheck == true && greaterthanzero == false )
  {
  	IsNumber = false;
  }
  return IsNumber;  
}

function saveCheckoutForm(action)
{
	var form = document.checkoutForm;
	form.action.value = action;
	form.submit();
}
//#N-A BEGIN ADD
function openwindow(var1, var2, var3, var4, sendurl) 
{
 	// Url example: /storefrontB2BWEB/order.do?print=true&action=order_detail&order_number={1}&order_gen={2}" 
 	var vParm1 = var1;
 	var vParm2 = var2;
 	var vParm3 = var3;
 	var vParm4 = var4;
 	sUrl = new String(sendurl);
 	sUrl = sUrl.replace('{1}', var1);
 	sUrl = sUrl.replace('{2}', var2);
 	sUrl = sUrl.replace('{3}', var3);
 	sUrl = sUrl.replace('{4}', var4);
 	window.open(sUrl,null,"height=600,width=800,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");
 }
//#N-A END ADD

 /**
  * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com), 
  * http://javascript.internet.com 
  * Version: 1.1.4 (updated in our source code 4/5/2010 in 1.5.300)
  * from: http://javascript.internet.com/forms/email-address-validation.html
  * Changes: ajw 4/5/2010 - I commented out the descriptive error messages and just
  *                         let it return 'false'.  The UI will handle the error
  *                         message, and use the bean property for the message.
  */
function checkEmail(emailStr) {
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */

	var checkTLD=1;

	/* The following is the list of known TLDs that an e-mail address must end with. */

	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */

	var emailPat=/^(.+)@(.+)$/;

	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/

	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */

	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */

	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	/* The following string represents an atom (basically a series of non-special characters.) */

	var atom=validChars + '+';

	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */

	var word="(" + atom + "|" + quotedUser + ")";

	// The following pattern describes the structure of the user

	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */

	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	/* Finally, let's start trying to figure out if the supplied address is valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */

	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {

	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */

	//alert("Email address seems incorrect (check @ and .'s)");
	return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).

	for (i=0; i<user.length; i++) {
	if (user.charCodeAt(i)>127) {
	//alert("Ths username contains invalid characters.");
	return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
	if (domain.charCodeAt(i)>127) {
	//alert("Ths domain name contains invalid characters.");
	return false;
	   }
	}

	// See if "user" is valid 

	if (user.match(userPat)==null) {

	// user is not valid

	//alert("The username doesn't seem to be valid.");
	return false;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {

	// this is an IP address

	for (var i=1;i<=4;i++) {
	if (IPArray[i]>255) {
	//alert("Destination IP address is invalid!");
	return false;
	   }
	}
	return true;
	}

	// Domain is symbolic name.  Check if it's valid.
	 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
	//alert("The domain name does not seem to be valid.");
	return false;
	   }
	}

	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */

	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	domArr[domArr.length-1].search(knownDomsPat)==-1) {
	//alert("The address must end in a well-known domain or two letter " + "country.");
	return false;
	}

	// Make sure there's a host name preceding the domain.

	if (len<2) {
	//alert("This address is missing a hostname!");
	return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}

function translateFreeformNumber(numFreeform, num1, num2, num3) {
	var freeformNumber = numFreeform.value;
	var endIndex = 0;
	
	// clear existing data
	num1.value = "";
	num2.value = "";
	num3.value = "";
	
	// check length
	if (freeformNumber.length > 3)
		endIndex = 3;
	else
		endIndex = freeformNumber.length;
	
	// fill freeformNumber part 1 and truncate freeformNumber
	num1.value = freeformNumber.substr(0, endIndex);
	freeformNumber = freeformNumber.substr(endIndex);
	
	// check length
	if (freeformNumber.length > 3)
		endIndex = 3;
	else
		endIndex = freeformNumber.length;
	
	// fill number part 2 and truncate freeformNumber
	num2.value = freeformNumber.substr(0, endIndex);
	freeformNumber = freeformNumber.substr(endIndex);
	
	// put the rest of freeformNumber into number part 3
	num3.value = freeformNumber.substr(0);
}

function updateSearchStringWithMultipleAttributes() {
	var currentlyCheckedAttributes = $('#attributeNavigationSelectionForm :checkbox:checked');
	var attributeSearchString = [];
	for (var i = 0; i < currentlyCheckedAttributes.length; i++) {
	   var workString = "";
	   workString = currentlyCheckedAttributes[i].name + " = '" + currentlyCheckedAttributes[i].value + "'"
		attributeSearchString.push(workString);
	}
	document.refineByAttributeSelectionForm.selectedAttributeRefinementString.value = attributeSearchString.join(";;;;");
}

function updateSearchStringWithSingleAttributeAndSubmit(attributeName, attributeValue) {
	var attributeSearchString = attributeName + " = '" + attributeValue + "'";
	document.refineByAttributeSelectionForm.selectedAttributeRefinementString.value = attributeSearchString;
	document.refineByAttributeSelectionForm.submit();
}
