// JavaScript Document

//Browser dependant styles
var userAgent=navigator.userAgent;
if ((userAgent.indexOf('Firefox') != -1) || (userAgent.indexOf('Netscape') != -1) || (userAgent.indexOf('Safari') != -1) || (userAgent.indexOf('Opera') != -1)) {
  	document.write('<link href="TW_assets/styles/mozilla.css" rel="stylesheet" type="text/css">');
}

if ((userAgent.indexOf('MSIE 6') != -1))  { //IE 7
	document.write('<link href="TW_assets/styles/ie6.css" rel="stylesheet" type="text/css">');
	//var wid = document.documentElement.clientWidth;
	//alert(wid);
}

function submitenter(myfield,e)
{
var keycode;
if (window.event) { keycode = window.event.keyCode; }
else if (e) { keycode = e.which; }
else { return true; }

if (keycode == 13)
   {
   //myfield.form.submit();
   tw_process_quickorder();
   return false;
   }
else { return true; }
}

function checkhideOS() {
	var OS = document.getElementById('OrderSummaryBox');	
	if (OS) {
		MM_showHideLayers('OrderSummaryBox','','hide');
		TW_changeStyle('OrderSummaryBox','hideme');
	}
}

function checkshowOS() {
	var OS = document.getElementById('OrderSummaryBox');	
	if (OS) {
		MM_showHideLayers('OrderSummaryBox','','show');
		TW_changeStyle('OrderSummaryBox','showme');	
	}
}


function TW_ChangeTableWidth(thisTable,x)
{
  document.getElementById(thisTable).width=x;
}

function tw_process_quickorder() {
	var loading = '<img src="TW_assets/js/TW_assets/images/misc/small_loading.gif" alt="Processing... Loading..." width="13" height="13" />';
	Spry.Utils.submitForm('QuickOrderForm', updateResponse_QuickOrder);
	Spry.Utils.setInnerHTML('msg_quickorder',loading);
	return false;
}

function updateResponse_QuickOrder(req) {
	var returnmsg = req.xhRequest.responseText;
	switch (returnmsg) {
		case "0":
			Spry.Utils.setInnerHTML('msg_quickorder','Item not found');
		break;
		case "Multiple matches":
			returnmsg = '<a href="TW_assets/js/SH_Search.asp?Term='+document.QuickOrderForm.qoino.value+'"><span class="alert">Multiple matches</span></a>';
			Spry.Utils.setInnerHTML('msg_quickorder',returnmsg);
		break;
		default:
			if (returnmsg.indexOf("added to order") > -1) { // Item added to order
				Spry.Utils.setInnerHTML('msg_quickorder','Added to order');
				Spry.Utils.submitForm('OrderSummaryUpdate', updateResponse_OS);
				TW_changeStyle('OrderSummary','hideme');
				TW_changeStyle('loading_update','loading');					
			} else { // Some other kind of message.
				Spry.Utils.setInnerHTML('msg_quickorder',returnmsg);
			} // added if
			break;
	} // End switch	
}

function updateResponse_OS(req) { // Reload the order summary pane.
	TW_changeStyle('loading_update','hideme');	
	//TW_changeStyle('OrderSummary','showme');
	Spry.Utils.setInnerHTML('OrderSummaryBox',req.xhRequest.responseText);

}

function TW_CheckOrderUpdate(form) {
	// version 1.0
	// Checks data entered into order summary pane before allowing submission.
	var i, j;
	
	for (i = 0; i < form.elements.length; i++)
	{
		if (form.elements[i].id.substring(0,3) == "qty")
		{
			if (form.elements[i].value.length > 4)
			{
				alert("Field cannot be longer than 4 characters!");
				form.elements[i].select();
				form.elements[i].focus();
				return false;
				
			}
			
			for (j = 0; j < form.elements[i].value.length; j++)
			{
				if (form.elements[i].value.charAt(j) < "0" || form.elements[i].value.charAt(j) > "9")
				{
					alert("Field must contain only whole numbers 0-9!");
					form.elements[i].select();
					form.elements[i].focus();
					return false;
					
				}
			}
		}
	}
	
	return processUpdate();
}

function processUpdate() {
	Spry.Utils.submitForm('OrderSummary', updateResponse_Update);

	// Show loading graphic
	TW_changeStyle('OrderSummary','hideme');
	TW_changeStyle('loading_update','loading');
	return false;
}
	
function updateResponse_Update(req) {
	var returnmsg = req.xhRequest.responseText;	
	Spry.Utils.setInnerHTML('OrderSummaryBox',returnmsg);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function TW_changeStyle(id, newClass) {
	identity=document.getElementById(id);
	identity.className=newClass;
}

function WAAddError(formElement,errorMsg,focusIt,stopIt)  {
  if (document.WAFV_Error)  {
	  document.WAFV_Error += "\n" + errorMsg;
  }
  else  {
    document.WAFV_Error = errorMsg;
  }
  if (!document.WAFV_InvalidArray)  {
    document.WAFV_InvalidArray = new Array();
  }
  document.WAFV_InvalidArray[document.WAFV_InvalidArray.length] = formElement;
  if (focusIt && !document.WAFV_Focus)  {
	document.WAFV_Focus = focusIt;
  }

  if (stopIt == 1)  {
	document.WAFV_Stop = true;
  }
  else if (stopIt == 2)  {
	formElement.WAFV_Continue = true;
  }
  else if (stopIt == 3)  {
	formElement.WAFV_Stop = true;
	formElement.WAFV_Continue = false;
  }
}

function WAValidateAN(formElement,value,errorMsg,allowUpper,allowLower,allowNumbers,allowSpace,extraChars,focusIt,stopIt,required)  {
  var isValid = true;
  extraChars = extraChars.replace(/"/g,'"');
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) || formElement.WAFV_Continue)  {
    for (var x=0; x<value.length; x++)  {
	  var charGood = false;
	  var nextChar = value.charAt(x);
	  var charCode = value.charCodeAt(x);
	  if (allowLower)  {
	    if (charCode >= 97 && charCode <= 122)  {
		  charGood = true;
		}
	  }
	  if (allowUpper)  {
	    if (charCode >= 65 && charCode <= 90)  {
		  charGood = true;
		}
	  }
	  if (allowNumbers)  {
	    if (charCode >= 48 && charCode <= 57)  {
		  charGood = true;
		}
	  }
	  if (allowSpace)  {
	    if (nextChar == " ")  {
		  charGood = true;
		}
	  }
	  if (extraChars)  {
	    if (unescape(extraChars).indexOf(nextChar) >= 0)  {
		  charGood = true;
		}
	  }
	  if (!charGood)  {
	    isValid = false;
		x = value.length;
	  }
	}
	if (required && value=="")
	  isValid = false;
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}
function WAAlertErrors(errorHead,errorFoot,setFocus,submitForm)  { 
  if (!document.WAFV_StopAlert)  { 
	  document.WAFV_StopAlert = true;
	  if (document.WAFV_InvalidArray)  {  
	    document.WAFV_Stop = true;
        var errorMsg = document.WAFV_Error;
	    if (errorHead!="")
		  errorMsg = errorHead + "\n" + errorMsg;
		if (errorFoot!="")
		  errorMsg += "\n" + errorFoot;
		document.MM_returnValue = false;
		if (document.WAFV_Error!="")
		  alert(errorMsg.replace(/"/g,'"'));
		else if (submitForm)
		  submitForm.submit();
	    if (setFocus && document.WAFV_Focus)  {
		  document.tempFocus = document.WAFV_Focus;
          setTimeout("document.tempFocus.focus();setTimeout('document.WAFV_Stop = false;document.WAFV_StopAlert = false;',1)",1); 
        }
        else {
          document.WAFV_Stop = false;
          document.WAFV_StopAlert = false;
        }
        for (var x=0; x<document.WAFV_InvalidArray.length; x++)  {
	      document.WAFV_InvalidArray[x].WAFV_Stop = false;
	    }
	  }
	  else  {
        document.WAFV_Stop = false;
        document.WAFV_StopAlert = false;
	    if (submitForm)  {
	      submitForm.submit();
	    }
	    document.MM_returnValue = true;
	  }
      document.WAFV_Focus = false;
	  document.WAFV_Error = false;
	  document.WAFV_InvalidArray = false;
  }
}

function WAtrimIt(theString,leaveLeft,leaveRight)  {
  if (!leaveLeft)  {
    while (theString.charAt(0) == " ")
      theString = theString.substring(1);
  }
  if (!leaveRight)  {
    while (theString.charAt(theString.length-1) == " ")
      theString = theString.substring(0,theString.length-1);
  }
  return theString;
}

function WAValidateEL(formElement,value,errorMsg,minLength,maxLength,reformat,focusIt,stopIt,required)  {
  var isValid = true;
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
	if (reformat)  {
	  if (reformat == "left")  {
	    value = WAtrimIt(value,false,true);
	  }
	  if (reformat == "right")  {
	    value = WAtrimIt(value,true);
	  }
	   if (reformat == "both")  {
	    value = WAtrimIt(value);
	  }
    }
	if ((value.length < minLength) || (value.length > maxLength && maxLength > 0))  {
	  isValid = false;
	}
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
  else if (reformat)  {
    formElement.value = value;
  }
}
function WAValidateRQ(formElement,errorMsg,focusIt,stopIt,trimWhite,inputType)  {
  var isValid = true;
  if (!document.WAFV_Stop && !formElement.WAFV_Stop)  {
    if (inputType == "select")  {
	  if (formElement.selectedIndex == -1)  {
	    isValid = false;
	  }
	  else if (!formElement.options[formElement.selectedIndex].value || formElement.options[formElement.selectedIndex].value == "") {
	    isValid = false;
	  }
	}
	else if (inputType == "checkbox")  {
	  if (!formElement.checked)
	    isValid = false;
	}
	else if (inputType == "radio")  {
	  isValid = false;
	  if (formElement.checked)
	    isValid = true;
	}
	else if (inputType == "radiogroup")  {
	  isValid = false;
	  for (var x=0; x<formElement.length; x++)  {
	    if (formElement[x].checked && formElement[x].value!="")  {
		  isValid = true;
		  break;
		}
	  }
	  formElement = formElement[0];
	}
	else  {
	  var value = formElement.value;
	  if (trimWhite)  {
	    value = WAtrimIt(value);
	  }
	  if (value == "")  {
	    isValid = false;
	  }
	}
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAValidateEM(formElement,value,errorMsg,focusIt,stopIt,required) {
  var isValid = true;
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var accepted = "\[^\\s\\(\\)><@,;:\\\\\\\"\\.\\[\\]\]+";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var section = "(" + accepted + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + section + "(\\." + section + ")*$");
    var domainPat = new RegExp("^" + accepted + "(\\." + accepted +")*$");
    var theMatch = value.match(emailPat);
    var acceptedPat = new RegExp("^" + accepted + "$");
    var userName = "";
    var domainName = "";
    if (theMatch==null) {
      isValid = false;
    }
    else  {
      userName = theMatch[1];
      domainName = theMatch[2];
	  var domArr = domainName.split(".");
	  var IPArray = domainName.match(ipDomainPat);
      for (x=0; x < userName.length; x++) {
        if (userName.charCodeAt(x) > 127) {
          isValid = false;
        }
      }
      for (x=0; x < domainName.length; x++) {
        if (domainName.charCodeAt(x) > 127) {
          isValid = false;
        }
      }
      if (userName.match(userPat) == null) {
        isValid = false;
      }
      if (IPArray != null) {
        for (var x=1; x<=4; x++) {
          if (IPArray[x] > 255) {
            isValid = false;
          }
        }
      }
      for (x=0; x < domArr.length; x++) {
        if (domArr[x].search(acceptedPat) == -1 || domArr[x].length < 2) {
          isValid = false;
        }
      }
      if (domArr[domArr.length-1].length !=2 && domArr[domArr.length-1].search(knownDomsPat) == -1) {
        isValid = false;
      }
      if (domArr.length < 2) {
        isValid = false;
      }
    }
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}
function WAValidateNM(formElement,errorMsg,minLength,maxLength,allowDecimals,roundDecimals,reformatDecimals,punctuationMarks,focusIt,stopIt,required)  {
  var isValid = true;
  var theThousand = punctuationMarks.charAt(0);
  var theDecimal = punctuationMarks.charAt(1);
  var theCheck = 11/10;
  var trueDecimal = (String(theCheck).charAt(1));
  var value = formElement.value;
  var decimalIndex = value.length;
  if (punctuationMarks.indexOf(trueDecimal)<0 && value.indexOf(trueDecimal)>=0)  {
    isValid = false;
  }
  if (value.lastIndexOf(theDecimal)>=0) {
    decimalIndex = value.lastIndexOf(theDecimal);
  }
  while (value.indexOf(theThousand)>=0)  {
    decimalIndex = value.length;
    if (value.lastIndexOf(theDecimal)>=0) {
      decimalIndex = value.lastIndexOf(theDecimal);
    }
    if ((decimalIndex-(value.lastIndexOf(theThousand)+1))%3 != 0)
	  isValid = false;
    value = value.substring(0,value.lastIndexOf(theThousand)) + value.substring(value.lastIndexOf(theThousand)+1);
  }
  if (trueDecimal != theDecimal)  {
    while (value.indexOf(theDecimal)>=0)  {
      value = value.substring(0,value.indexOf(theDecimal)) + trueDecimal + value.substring(value.indexOf(theDecimal)+1);
    }
  }
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    for (var x=0; x<value.length; x++)  {
	  if  ((value.charAt(x)<0 || value.charAt(x) > 9) && (value.charAt(x) != " " && value.charAt(x) != "," && value.charAt(x) != "."))  {
        isValid = false;
      }
	}
    if (value == "")  {
	  isValid = false;
	}
	var oldVal = String(value);
	if (oldVal.indexOf(trueDecimal)>=0)  {
	  while (oldVal.charAt(oldVal.length-1)=="0" || oldVal.charAt(oldVal.length-1) == trueDecimal)
	    oldVal = oldVal.substring(0,oldVal.length-1);
	  if (oldVal.indexOf(trueDecimal)==0)
	    oldVal = "0" + oldVal;
	}
    if (String(allowDecimals) !="" )  {
	  if (String(value).indexOf(".") > 0 && ((String(value).indexOf(".") + allowDecimals + 2 <= String(value).length) || allowDecimals == 0))  {
	    isValid = false;
	  }
	}
	value = parseFloat(value);
	if (isNaN(value))  {
	  isValid = false;
	}
	else if (String(value).length!=String(oldVal).length) {
	  isValid = false;
	}
	else if ((minLength != "" && minLength > value) || (maxLength != "" && maxLength < value)) {
	  isValid = false;
	}
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
  else  {
    if (value != "")  {
	  if (roundDecimals != "")  {
	    value = Math.round(value*roundDecimals)/roundDecimals;
	  }
	  if (reformatDecimals != "")  {
	    value = String(value);
		if (value.indexOf(trueDecimal)<0)
		  value += trueDecimal;
		if (value.indexOf(trueDecimal) < value.length - reformatDecimals)  {
		  value = value.substring(0,value.indexOf(trueDecimal) + reformatDecimals + 1);
		}
		else  {
		  while (value.indexOf(trueDecimal) > value.length - reformatDecimals - 1)  {
		     value += "0";
		  }
		}
	  }
	}
    if (trueDecimal != theDecimal)  {
	  value = String(value);
      while (value.indexOf(trueDecimal)>=0)  {
        value = value.substring(0,value.indexOf(trueDecimal)) + theDecimal + value.substring(value.indexOf(trueDecimal)+1);
      }
    }
	if (roundDecimals != "" || reformatDecimals != "")
	  formElement.value = value;
  }
}
function WAValidateRT(formElement,value,errorMsg,notAllowed,focusIt,stopIt,required)  {
  var isValid = true;
  var augValue = " " + value.toLowerCase() + " ";
  var tempVal = augValue;
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    var notAllowed = notAllowed.split(", ");
	for (var x=0; x<notAllowed.length; x++)  {
	  var notAllowedInfo = notAllowed[x].split("|");
	  notAllowedInfo[0] = unescape(notAllowedInfo[0]);
      notAllowedInfo[1] = unescape(notAllowedInfo[1]);
	  while (tempVal.indexOf(notAllowedInfo[0].toLowerCase())>=0)  {
	    isValid = false;
		var theIndex = tempVal.indexOf(notAllowedInfo[0].toLowerCase())
		tempVal = tempVal.substring(0,theIndex) + tempVal.substring(theIndex+notAllowedInfo[0].length);
		if (notAllowedInfo[1]!="")  {
          theIndex = augValue.indexOf(notAllowedInfo[0].toLowerCase())
		  augValue = augValue.substring(0,theIndex) + notAllowedInfo[1] + augValue.substring(theIndex+notAllowedInfo[0].length);
		}
	  }
	}
  }
  if (required && value=="")
    isValid = false;
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
	formElement.value = augValue.substring(1,augValue.length-1);
  }
}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

/* Cookie code */

function WA_setCookie(cookieobj, cookiename, cookievalue, cookiecheck, settype)     {
  var theValue = "";
  if (settype == 1)     {
    for (var n=0; n<cookievalue.length; n++)    {
      if (cookievalue[n].checked)     {
        theValue = cookievalue[n].value;
      }
    }
  }
  else if (settype == 2)     {
    for (var n=0; n<cookievalue.options.length; n++)    {
      if (cookievalue.options[n].selected)     {
        if (theValue != "")
          theValue += ", ";
        theValue += cookievalue.options[n].value;
      }
    }
  }
  else      {
    theValue = cookievalue
  }

  if (cookiecheck)     {
    cookieobj.setValue(cookiename, theValue);
  }
}
function WA_deleteCookie(cookieobj, cookiename, cookiecheck)     {
  if (cookiecheck)     {
    cookieobj.setValue(cookiename, "");
    cookieobj.expire(cookiename);
  }
}

function WA_decodeCookieSelectVal(theVal)     {
  theVal = theVal.replace(/\|WACS\|/g, ", ");
  return theVal;
}

function WA_checkCookieSelectOption(theList, theOption, theVal)     {
  var testVal = "";
  if (theList.options[theOption].value)     {
    testVal = theList.options[theOption].value;
  }
  else      {
    testVal = theList.options[theOption].text;
  }
  if (testVal == WA_decodeCookieSelectVal(theVal))     {
    theList.options[theOption].selected = true;
    return true;
  }
  return false;
}

function WA_getCookie(cookieobj, cookiename, cookieset, settype)     { // TW Updated
  var theValue = cookieobj.getValue(cookiename);
  if (theValue != '') {
	  if (settype == 1)     {
		cookieset.value = theValue;
	  }
	  else if (settype == 2)     {
		cookieset.checked = (String(theValue)!="" && String(theValue).toUpperCase() !="FALSE");
	  }
	  else if (settype == 3)     {
		for (var n=0; n< cookieset.length; n++)     {
		  if (cookieset[n].value == theValue)     {
			cookieset[n].checked = true;
			break;
		  }
		}
	  }
	  else if (settype == 4)     {
		var setArr = theValue.split(", ");
		for (var m=0; m<setArr.length; m++)     {
		  for (var n=0; n<cookieset.options.length; n++)     {
			if (n+m < cookieset.options.length && cookieset.options[n+m])     {
			  if (WA_checkCookieSelectOption(cookieset, n+m, setArr[m]))     {
				break;
			  }
			}
			if (n!=0 && n-m >= 0 && cookieset.options[n-m])     {
			  if (WA_checkCookieSelectOption(cookieset, n-m, setArr[m]))     {
				break;
			  }
			}
			if (n-m < 0 && n+m >= cookieset.options.length)     {
			  break;
			}
		  }
		}
	  }
  }
}

/* End cookie code */

function MM_popupMsg(msg) { //v1.0
  alert(msg);
}

function MM_showHideLayers() { //v9.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function WA_setCookie(cookieobj, cookiename, cookievalue, cookiecheck, settype, expdays)     {
  var theValue = "";
  if (settype == 1)     {
    for (var n=0; n<cookievalue.length; n++)    {
      if (cookievalue[n].checked)     {
        theValue = cookievalue[n].value;
      }
    }
  }
  else if (settype == 2)     {
    for (var n=0; n<cookievalue.options.length; n++)    {
      if (cookievalue.options[n].selected)     {
        if (theValue != "")
          theValue += ", ";
        theValue += cookievalue.options[n].value;
      }
    }
  }
  else      {
    theValue = cookievalue
  }

  if (cookiecheck)     {
	if (expdays)  {
	  cookieobj.expires = daysToExpire(expdays);
	}
	else  {
	  cookieobj.expires = "";
	}
    cookieobj.setValue(cookiename, theValue, expdays);
  }
}
function MM_showHideLayers() { //v9.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
function WA_deleteCookie(cookieobj, cookiename, cookiecheck)     {
  if (cookiecheck)     {
    cookieobj.setValue(cookiename, "");
    cookieobj.expire(cookiename);
  }
}
