function toggleClass()
{
	if (this.className == 'button')
	{
		this.className = 'buttonO';
	}
	else if (this.className == 'buttonO')
	{
		this.className = 'button';
	}
}

var elems = document.getElementsByTagName("input");

for (var i = 0; i < elems.length; i++)
{
	if (elems[i].className == 'button')
	{
		elems[i].onmouseover = toggleClass;
		elems[i].onmouseout  = toggleClass;
	}
}

/*
See http://www.howtocreate.co.uk/perfectPopups.html and http://www.howtocreate.co.uk/jslibs/termsOfUse.html
for details and terms of use.
To call this script, use something like (the number is a delay before it closes or 0 for no timed closing -
the true/false says if the window should close when they switch to another window):
<script type="text/javascript"><!--
//you can style this, but don't try to text-align it to the right, it will break the resizing effect
//keep it narrow, if it is wider than the image, the window will wrap to this width
//the makeright class tells the script to automatically align it to the right
var extraHTML = '<br><a href="javascript:window.close()" style="text-decoration:none;color:#777;background-color:#bbb;font-weight:bold;border-left:2px solid #000;outline:none !important" class="makeright">Close<\/a>';
//--></script>
<a href="me.jpg" onclick="return popImageExtra(this.href,'Site author',true,3000,extraHTML);">link</a>
*/

//really not important (the first two should be small for Opera's sake)
PositionX = 10;
PositionY = 10;
defaultWidth  = 600;
defaultHeight = 400;

//don't touch (except to modify the window contents). used by ShowDetail servlet for accessory details
function popImageExtra(imageURL,imageTitle,AutoClose,oTimeClose,extraHTML){
	var imgWin = window.open('','_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
	if( !imgWin ) { return true; } //popup blockers should not cause errors
	imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
		'function getRefToDivMod( divID, oDoc ) {\n'+
			'if( !oDoc ) { oDoc = document; }\n'+
			'if( document.layers ) {\n'+
			'if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {\n'+
			'for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {\n'+
			'y = getRefToDivNest(divID,oDoc.layers[x].document); }\n'+
			'return y; } }\n'+
			'if( document.getElementById ) { return oDoc.getElementById(divID); }\n'+
			'if( document.all ) { return oDoc.all[divID]; }\n'+
			'return document[divID];\n'+
		'}\n'+
		'function resizeWinTo() {\n'+
			'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
			'if( !document.images[0].height || window.doneAlready ) { return; }\n'+ //in case images are disabled
			'var oH = getRefToDivMod( \'myID\' ); if( !oH ) { return false; }\n'+
			'var oW = oH.clip ? oH.clip.width : oH.offsetWidth;\n'+
			'var oH = oH.clip ? oH.clip.height : oH.offsetHeight; if( !oH ) { return false; }\n'+
			'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
			'window.doneAlready = true;\n'+ //for Safari and Opera
			'if(document.getElementsByTagName) {\n'+
				'for( var l = document.getElementsByTagName(\'a\'), x = 0; l[x]; x++ ) {\n'+
					'if(l[x].className==\'makeright\'&&!l[x].style.position){\n'+
						'l[x].style.position=\'relative\';\n'+
						'l[x].style.left=(document.images[0].width-(l[x].offsetWidth+l[x].offsetLeft))+\'px\';\n'+
			'}}}\n'+
			'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
			'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
			'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
			'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
			'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
			'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
			'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
			'var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
			'var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
			'if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
			(oTimeClose?('window.setTimeout(\'window.close()\','+oTimeClose+');\n'):'')+
		'}\n'+
		'<\/script>'+
		'<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
		(document.layers?('<layer left="0" top="0" id="myID">'):('<div style="position:absolute;left:0px;top:0px;" id="myID">'))+
		'<img src="'+imageURL+'" alt="Loading image ..." title="" onload="resizeWinTo();">'+
		(extraHTML?extraHTML:'')+(document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
	imgWin.document.close();
	if( imgWin.focus ) { imgWin.focus(); }
	return false;
}

function verifyCreditCardStuff(form) {
      if ( form.creditCardType.value == "None" ) {
	if ( (form.creditCardNumber && (form.creditCardNumber.value.length > 0))
            || ( form.creditCardUserName && form.creditCardUserName.value.length > 0 )
             || (form.expireMonth && form.expireMonth.value.length > 0)
             || ( form.expireYear && form.expireYear.value.length > 0 ))
            {
            alert("If you enter any credit card info you must select a card type, not NONE."
            +"\nform.creditCardNumber.value.length =" + form.creditCardNumber.value.length
            +"\nform.creditCardUserName.value.length =" + form.creditCardUserName.value.length
            +"\nform.expireMonth.value.length =" + form.expireMonth.value.length
            +"\nform.expireYear.value.length =" + form.expireYear.value.length
            );
            form.creditCardType.focus();
            return false;
            }
      }

      if ( form.creditCardType.value != "None" ) {
          item = form.creditCardType.selectedIndex;
          if ( !validatecardfunc(form.creditCardNumber.value,form.creditCardType.options[item].text) ) {
             alert("Credit card number isn't valid.");
             form.creditCardNumber.focus();
             form.creditCardNumber.select();
             return false;
          }
          Num = stripNonNumbers(form.creditCardNumber.value);
          ret = cardcheck (Num)
                if (ret != "VALID") {
                   alert ("Credit card number checksum is no good!");
                   form.creditCardNumber.focus();
                   form.creditCardNumber.select();
                   return false;
                }
          if ( form.creditCardUserName.value.length < 1 ) {
             alert("A credit card user name is required.");
             form.creditCardUserName.focus();
             form.creditCardUserName.select();
             return false;
          }
          if ( form.creditCardValidationCode.value.length < 1 ) {
             alert("A credit card validation code is required. This is the 3 or 4 digit number on the back of the card.");
             form.creditCardValidationCode.focus();
             form.creditCardValidationCode.select();
             return false;
          }
          if ( !isNum(form.creditCardValidationCode.value) ) {
             alert("the credit card validation code must be a number.");
             form.creditCardValidationCode.focus();
             form.creditCardValidationCode.select();
             return false;
          }
          if( form.creditCardType.value == "American Express"  && form.creditCardValidationCode.value.length != 4 ) {
             alert("American Express security code must be 4 digits.");
             form.creditCardValidationCode.focus();
             form.creditCardValidationCode.select();
             return false;
          }
          if( (form.creditCardType.value == "Visa"  || form.creditCardType.value == "MasterCard" ) && form.creditCardValidationCode.value.length != 3 ){
             alert("Visa and MasterCard security codes must be 3 digits");
             form.creditCardValidationCode.focus();
             form.creditCardValidationCode.select();
             return false;
          }

          if ( !isNum(form.expireMonth.value) ) {
             alert("A credit card expire month number is required.");
             form.expireMonth.focus();
             form.expireMonth.select();
             return false;
          }
          if ( form.expireMonth.value < 1 || form.expireMonth.value > 12 ) {
             alert("Credit card expire month number must be 01 to 12");
             form.expireMonth.focus();
             form.expireMonth.select();
             return false;
          }
          if ( !isNum(form.expireYear.value) ) {
             alert("A credit card expire year number is required.");
             form.expireYear.focus();
             form.expireYear.select();
             return false;
          }
          var now = new Date();
          var fullYear = now.getFullYear() - 0;  // e.g. 2006 the -0 forces it to be numeric not string type
         if ( (Number(form.expireYear.value)  + 2000) < fullYear  ) {
             alert("Credit card expire year number is too old, must be this year or later.");
             form.expireYear.focus();
             form.expireYear.select();
             return false;
          }
      }
    return true;
}

var tempobj;   // in current page context global space, used by setTimeout function to reenable the form
// is there a thread problem here if someone else simultaneously submits a form?
// or is this  a particular page variable, I think so, and in different browsers it will be different
function validateCheckoutForm(form) {
  try {
    if (document.all||document.getElementById){  //if IE 4+ or NS 6+
      //screen thru every element in the form, and hunt down "submit" and "reset"
      for (i=0;i<form.length;i++){
        tempobj= form.elements[i]
        if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset") {
          setTimeout("tempobj.disabled=false;tempobj.value='resubmit';",2000);
        }
      }
    }
    if ( form.shipName == null || form.shipName.value.length < 1 ) {
        alert("A ship to name is required.");
            form.shipName.focus();
            form.shipName.select();
            return false;
    }
    if ( form.shipAddr1 == null || form.shipAddr1.value.length < 1 ) {
        alert("A shipping address is required.");
            form.shipAddr1.focus();
            form.shipAddr1.select();
            return false;
    }

    if ( form.shipZip1 == null || form.shipZip1.value.length < 1 ) {
        alert("A shipping postal code is required.");
            form.shipZip1.focus();
            form.shipZip1.select();
            return false;
    }
    var saddr = form.shipAddr1.value;
    var pattern = /(PO BOX)|(P.O. Box)|(\bbox\b)|(Box)|(PO Box)|(drawer)|(DRAWER)|(Drawer)/g;
    if (  pattern.test(saddr) ) {
            alert("Shipping address cannot be a PO Box or 'Drawer'.");
            form.shipAddr1.focus();
            form.shipAddr1.select();
            return false;
    }
    var saddr2 = form.shipAddr2.value;
    if (  pattern.test(saddr2) ) {
            alert("Shipping address cannot be a PO Box or 'Drawer'.");
            form.shipAddr2.focus();
            form.shipAddr2.select();
            return false;
    }
    if ( form.PaymentMethodType.value == "") {
        alert("Select either Credit Card or PO Number as payment method.");
        return false;
    }
    if ( form.PaymentMethodType.value == "Credit Card") {
       return verifyCreditCardStuff(form);
    }
     if ( form.PaymentMethodType.value == "Purchase Order Number") {
       if (  form.PONumber.value.length < 1 ) {
           alert("PO number value was not entered.");
           return false;
       }
     }
    return true;
}
catch (errorArg) {
    alert(errorArg)
}
}

// validateRegistrationForm is invoked by Register.jsp
var registertempobj;
function validateRegistrationForm(form) {
     if (document.all||document.getElementById){  //if IE 4+ or NS 6+
      //screen thru every element in the form, and hunt down "submit" and "reset"
      for (i=0;i<form.length;i++){
        registertempobj= form.elements[i]
        if(registertempobj.type.toLowerCase()=="submit"||registertempobj.type.toLowerCase()=="reset") {
          setTimeout("registertempobj.disabled=false;registertempobj.value='resubmit';",2000);
        }
      }
    }
    return true;
}

function validateDisplayCountForm(form) {
	if ( !isNum( form.itemsCount.value ) ) {
		alert("Invalid value, must be a positive number");
		form.itemsCount.focus();
		form.itemsCount.select();
		return false;
	}
	if ( form.itemsCount.value < 1 ) {
		alert("Invalid value, must be > 0");
		form.itemsCount.focus();
		form.itemsCount.select();
		return false;
	}
	return true;
}

function validateForm(form) {
	if ( !isNum( form.quantity.value ) ) {
		alert("Invalid quantity, must be a number");
		form.quantity.focus();
		form.quantity.select();
		return false;
	}
	if ( form.quantity.value < 1 ) {
		alert("Invalid quantity, must be 1 or greater");
		form.quantity.focus();
		form.quantity.select();
		return false;
	}
        if ( form.wants_embroidery != null && form.wants_embroidery.checked ) {
          // alert("wants_embroidery element is in form, and it is checked" );
          if ( form.embroidery != null  ) {
		e = form.embroidery.value;
		if ( e == "" ) {
			alert("specify embroidery text, 20 characters maximum");
			form.embroidery.focus();
			form.embroidery.select();
			return false;
		}
		if ( e.length > 20 ) {
			alert("embroidery text has to many characters, 20 characters maximum");
			form.embroidery.focus();
			form.embroidery.select();
			return false;
		}
	   }
        }

	if ( form.embroider != null && !(form.embroider.value == "None") ) {
		e = form.embroidery.value;
		if ( e == "" ) {
			alert("specify embroidery text, 20 characters maximum");
			form.embroidery.focus();
			form.embroidery.select();
			return false;
		}
		if ( e.length > 20 ) {
			alert("embroidery text has to many characters, 20 characters maximum");
			form.embroidery.focus();
			form.embroidery.select();
			return false;
		}
	}
	if ( form.selection != null ) {
		if ( form.selection.value == "choice" ) {
			alert("please make a selection from the drop down choices");
			form.selection.focus();
			return false;
		}
		if ( form.selection2 && form.selection2.value == "choice" ) {
					alert("please make a selection from the second drop down choice");
					form.selection.focus();
					return false;
		}
	}
	if ( form.initials != null ) {
	    if ( !form.initials.value.length > 0 ) {
	    	alert("specify some initials or number");
		form.initials.focus();
		return false;
	    }
	}

	if ( form.textField != null ) {  // a special encoded text field has a min and max length
            minLen = form.minTextLen.value;
            maxLen = form.maxTextLen.value;
            //alert("testing textField length = " + form.textField.value.length);
	    if ( form.textField.value.length < minLen || form.textField.value.length > maxLen) {
		if ( minLen != maxLen )
	    		alert("Please specify " + minLen + " to " + maxLen + " characters.");
		else {
			if ( minLen > 1 )
			   alert("Please specify " + minLen + " characters.");
                        else
			    alert("Please specify " + minLen + " character.");
		}
		form.textField.focus();
		return false;
	    }
	}
	return true;
}

function validateZipCodeForm(form) {
  if ( form.account_zipcode.value.length < 5 ) {
  	alert("zip code must be at least 5 characters long");
  	form.account_zipcode.focus();
  	form.account_zipcode.select();
  	return false;
  }
  return true;
}

// Added Mar 2 2006
function validateCatalogRequestForm(form) {
    if ( form.firstName.value.length < 1 ) {
		alert("A first name is required.");
		form.firstName.focus();
		form.firstName.select();
		return false;
	}
	if ( form.lastName && form.lastName.value.length < 1 ) {
		alert("A last name is required.");
		form.lastName.focus();
		form.lastName.select();
		return false;
	}
	if ( form.department && form.department.value.length < 1 ) {
		alert("A department or persons job title is required.");
		form.department.focus();
		form.department.select();
		return false;
	}
	if ( form.facility.value.length < 1 ) {
		alert("A facility or company or organization name is required.");
		form.facility.focus();
		form.facility.select();
		return false;
	}


	if ( form.Addr1.value.length < 1 ) {
		alert("An Address is required.");
		form.Addr1.focus();
		form.Addr1.select();
		return false;
	}
	if ( form.City.value.length < 1 ) {
		alert("A City or town name is required.");
		form.City.focus();
		form.City.select();
		return false;
	}
	if ( form.State.value.length < 1 ) {
		alert("A State is required.");
		form.State.focus();
		form.State.select();
		return false;
	}

	if ( !isNum( form.Zip1.value ) ) {
		alert("A numeric Zip code is required.");
		form.Zip1.focus();
		form.Zip1.select();
		return false;
	}
	return true;
}

function validEmail(email) {
	invalidChars = " /:,;"

	if (email == "") {						// cannot be empty
		return false
	}
	for (i=0; i<invalidChars.length; i++) {	// does it contain any invalid characters?
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1) {
			return false
		}
	}
	atPos = email.indexOf("@",1)			// there must be one "@" symbol
	if (atPos == -1) {
		return false
	}
	if (email.indexOf("@",atPos+1) != -1) {	// and only one "@" symbol
		return false
	}
	periodPos = email.indexOf(".",atPos)
	if (periodPos == -1) {					// and at least one "." after the "@"
		return false
	}
	if (periodPos+3 > email.length)	{		// must be at least 2 characters after the "."
		return false
	}
	return true
}

function isNum(passedVal) {					// Is this a number?
	if (passedVal == "") {
		return false
	}
	for (i=0; i<passedVal.length; i++) {
		if (passedVal.charAt(i) < "0") {
			return false
		}
		if (passedVal.charAt(i) > "9") {
			return false
		}
	}
	return true
}

function isNumWithSpaces(passedVal) {					// Is this a number?
	if (passedVal == "") {
		return false
	}
	for (i=0; i<passedVal.length; i++) {
                if ( passedVal.charAt(i) == " ") {
                   continue;
                }
		if (passedVal.charAt(i) < "0") {
			return false
		}
		if (passedVal.charAt(i) > "9") {
			return false
		}
	}
	return true
}

function validZip(inZip) {					// Is this a valid Zip code?
	if (inZip == "") {
		return true
	}
	if (isNum(inZip)) {						// Check if Zip is numeric
		return true
	}
	return false
}

// the following does a checksum
function cardcheck (Num) {
   CardType=""
mask = "2121212121212121"
if (Num=="")  {
   CardType="BLANK"
   return (CardType)
}
if ( Num.length == 13 )
   Num = "000" + Num;
else if ( Num.length == 14 )
   Num = "00" + Num;
else if (Num.length == 15 )
   Num = "0" + Num;
if (Num.length == 16)
   Num = Num;
else
   CardType="INVALID" ;

CheckSum = 0;
for (count = 1; count<= 16; count++) {
   ProdVal = Num.charAt(count-1) * mask.charAt(count-1)
   if (ProdVal > 9)
      ProdVal = ProdVal - 9
   CheckSum = CheckSum + ProdVal
}
CheckSum = CheckSum % 10
   if (CheckSum != 0)
     CardType="INVALID"
   else
      CardType="VALID"
   return (CardType)
}

function validatecardfunc (passedValue,cardBrand) {
   validcard = false;
   ret = stripNonNumbers (passedValue);
  // item = document.validate.cardtypelist.selectedIndex;
  // result = document.validate.cardtypelist.options[item].text;
   if (cardBrand == "Master Card") {
      if (ret.length == 16)
         validcard = true;
      if (validcard && (ret.substring (0, 2) >= "51") &&
          (ret.substring (0, 2) <= "55"))
         validcard = true;
      else
         validcard = false;
   }
   if (cardBrand == "Visa") {
      if ((ret.length == 16) || (ret.length == 13))
         validcard = true;
      if (ret.substring (0, 1) != "4")
         validcard = false;
   }
   if (cardBrand == "American Express") {
      if (ret.length == 15)
         validcard = true;
      if ((ret.substring (0, 2) != "34") &&
           (ret.substring (0, 2) != "37"))
         validcard = false;
   }
   if (cardBrand == "Discover") {
      if (ret.length == 16)
         validcard = true;
      if (ret.substring (0, 4) != "6011")
         validcard = false;
   }
   return (validcard);
}

function stripNonNumbers (InString)  {
   OutString="";
   for (Count=0; Count < InString.length; Count++)  {
      TempChar=InString.substring (Count, Count+1);
      Strip = false;
      CharString="0123456789";
      for (Countx = 0; Countx < CharString.length; Countx++) {
         StripThis = CharString.substring(Countx, Countx+1)
         if (TempChar == StripThis) {
            Strip = true;
            break;
         }
      }
      if (Strip)
      OutString=OutString+TempChar;
   }
    return (OutString);
}

// functions below show credit card or purchase order span on checkout.jsp and register.jsp
function Choose_PaymentMethodType(arg_index) {
    switch(arg_index) {
        case 0 : {
        Show_PaymentFields(''); break }
        case 1 : {
        Show_PaymentFields('Credit Card'); break }
        case 2 : {
        Show_PaymentFields('Purchase Order Number'); break }
    }
}

var previous_paymentfields_span = '';
function Show_PaymentFields(arg_PaymentMethodType) {
    arg_current_span = '';
    //find out which payment method is selected
    switch(arg_PaymentMethodType) {
        case 'Credit Card' : { arg_current_span = 'credit_card'; break }
        case 'Electronic Check' : { arg_current_span = 'electronic_check'; break }
        case 'Purchase Order Number' : { arg_current_span = 'purchase_order_number'; break }
        default : { break }
    }
    //change the viewable form fields on the page now...
    if (document.getElementById("span_paymentfields_" + previous_paymentfields_span)) { document.getElementById("span_paymentfields_" + previous_paymentfields_span).style.display = "none" }
    if (document.getElementById("span_paymentfields_" + arg_current_span))            { document.getElementById("span_paymentfields_" + arg_current_span).style.display = "block" }
    previous_paymentfields_span = arg_current_span;
}
// ---------------------------------------------- AJAX load a div block -----------


/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects="";
var rootdomain="http://"+window.location.hostname;
var bustcacheparameter="";

function ajaxpage(url, containerid) {

var page_request = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false;
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
    bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
return true;  // added by cdh
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}

//document.write("In JavaScript common.js");
