
function hideProd(which){
  if (document.all){
    eval("document.all." + which + ".style.visibility = 'hidden'");
  } else {
      eval("document." + which + ".visibility = 'hidden'");
    }
}

function showProd(which){
  if (document.all){
    eval("document.all." + which + ".style.visibility = 'visible'");
  } else {
      eval("document." + which + ".visibility = 'visible'");
    }
}

  function validate(){
    var str = document.SearchForm.skuSearchParam.value;
    var firstChar = str.substring(0,1);
    if (isWhitespace(str) || !(isInt(firstChar) || isChar(firstChar))){
      alert("Please enter a valid search term.");
      document.SearchForm.skuSearchParam.focus();
      return false;
    } 
    document.SearchForm.submit();
  }
  function validate2(){
    if (!(document.OrderItemAddForm.quantity.value > 0) || !isInt(document.OrderItemAddForm.quantity.value)){
      alert("Please enter a valid quantity.");
      document.OrderItemAddForm.quantity.focus();
      return false;
    } 
    document.OrderItemAddForm.submit()
  }
  function validateQty(thisForm){
    if (!(thisForm.quantity.value > 0) || !isInt(thisForm.quantity.value)){
      alert("Please enter a valid quantity.");
      thisForm.quantity.focus();
      return false;
    } 
    thisForm.submit()
  }
  function validate3(){
    for (j=0; j < document.ShopCartForm.elements.length; j++){
      if (document.ShopCartForm.elements[j].name.indexOf("quantity_") != -1){
        if (!(document.ShopCartForm.elements[j].value > 0) || !isInt(document.ShopCartForm.elements[j].value)){
          alert("Please enter a valid quantity.");
          document.ShopCartForm.elements[j].focus();
          return false;
        } 
      }
    }
    return true;
  }

  function validate4(){
    // check last name
    if (document.AddressForm.lastName.value == ""){
      document.AddressForm.lastName.focus();
      alert("Please enter a last name");
      return false;
    }
    if (document.AddressForm.email1.value == ""){
      document.AddressForm.email1.focus();
      alert("Please enter an email address");
      return false;
    }
    if (document.AddressForm.email2.value.length > 254){
      document.AddressForm.email2.focus();
      alert("Your message is limited to 254 characters.");
      return false;
    }
    return true;
  }

// whitespace characters
  var whitespace = " \t\n\r";
  
  function isEmpty(s){   
    return ((s == null) || (s.length == 0))
  }

  // Returns true if string s is empty or 
  // whitespace characters only.

  function isWhitespace (s){   
    var i;
    // Is s empty?
    if (isEmpty(s)) return true;
    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++){   
      // Check that current character isn't whitespace.
      var c = s.charAt(i);
      if (whitespace.indexOf(c) == -1) return false;
    }
    // All characters are whitespace.
    return true;
  }
  
 function stripChars(str, chars) {
	var i
	var newstring = ""
	for (i = 0;  i < str.length; i++) {
		mychar = str.charAt(i)
		if (chars.indexOf(mychar) == -1)
			newstring += mychar
	}
	return newstring
}

function notNull(str) {
	if (str.length == 0 )
		return false
	else 
		return true
}

function isInt(str) {
	numdecs = 0
	for (i = 0; i < str.length; i++) {
		mychar = str.charAt(i)
		if (!(mychar >= "0" && mychar <= "9")) {
			return false
		}
	}
  return true;
}

function isChar(str) {
	numdecs = 0
	for (i = 0; i < str.length; i++) {
		mychar = str.charAt(i)
		if (!(mychar >= "A" && mychar <= "z")) {
			return false
		}
	}
  return true;
}

function shippingSelect(form){
        if (form.country[form.country.selectedIndex].value == "U.S.A." && 
            form.state[form.state.selectedIndex].value != "AK" && form.state[form.state.selectedIndex].value != "HI"){
    alert("Default US shipping");
  }else if ((form.country[form.country.selectedIndex].value == "U.S.A."  && 
            (form.state[form.state.selectedIndex].value == "AK" || 
             form.state[form.state.selectedIndex].value == "HI")) || 
            form.country[form.country.selectedIndex].value == "Puerto Rico"){
    alert("Default non48 shipping");
  }else if (form.country[form.country.selectedIndex].value == "Canada" || form.country[form.country.selectedIndex].value == "Mexico"){
    alert("Default NA shipping");
  }else{
    alert("Default World Shipping");
  }
}

function validateBillingAddress(form){
  // Check billing info
  form.b_firstName.value = Trim(form.b_firstName.value);
  if (form.b_firstName.value == ""){
    form.b_firstName.focus();
    alert("Please enter your first name");
    return false;
  }

  form.b_lastName.value = Trim(form.b_lastName.value);
  if (form.b_lastName.value == ""){
    form.b_lastName.focus();
    alert("Please enter your last name");
    return false;
  }

  form.b_addr1.value = Trim(form.b_addr1.value);
  if (form.b_addr1.value == ""){
    form.b_addr1.focus();
    alert("Please enter a billing address");
    return false;
  }
  form.b_city.value = Trim(form.b_city.value);
  if (form.b_city.value == ""){
    form.b_city.focus();
    alert("Please enter a billing city");
    return false;
  }

  form.b_zip.value = Trim(form.b_zip.value);
  if (form.b_zip.value == ""){
    form.b_zip.focus();
    alert("Please enter a billing zip code");
    return false;
  }

  if (form.b_country.selectedIndex == 0){
    form.b_country.focus();
    alert("Please enter a billing country");
    return false;
  }

  if (form.b_state.selectedIndex == 0 && (form.b_country[form.b_country.selectedIndex].value == "U.S.A." || form.b_country[form.b_country.selectedIndex].value == "Canada") ){
    form.b_state.focus();
    alert("Please enter a billing state");
    return false;
  }

  if (checkForAPOState(form.b_city, form.b_state))
  {
    form.b_state.focus();
    alert("For APO/FPO address, please choose the appropriate 'Armed Forces...' selection in the State/Prov/Terr.");
    return false;
  }

  if (checkForAPOCity(form.b_state, form.b_city))
  {
    form.b_city.focus();
    alert("For APO/FPO address, please enter either APO or FPO in the City");
    return false;
  }

  if (checkForAPOCountry(form.b_state, form.b_country))
  {
    form.b_country.focus();
    alert("For APO/FPO address, please choose U.S.A. as the Country.");
    return false;
  }

  form.phone1.value = Trim(form.phone1.value);
  if (form.phone1.value == ""){
    form.phone1.focus();
    alert("Please enter your daytime phone number");
    return false;
  }

  form.phone2.value = Trim(form.phone2.value);
  if (form.phone2.value == ""){
    form.phone2.focus();
    alert("Please enter your evening phone number");
    return false;
  }

  form.email1.value = Trim(form.email1.value);
  if (form.email1.value == ""){
    form.email1.focus();
    alert("Please enter your E-mail address");
    return false;
  }

  return true;
	
}

function validateShippingAddress(form){
  // check shipping info
  form.firstName.value = Trim(form.firstName.value);
  if (form.firstName.value == ""){
    form.firstName.focus();
    alert("Please enter a first name");
    return false;
  }

  form.lastName.value = Trim(form.lastName.value);
  if (form.lastName.value == ""){
    form.lastName.focus();
    alert("Please enter a last name");
    return false;
  }

  form.address1.value = Trim(form.address1.value);
  if (form.address1.value == ""){
    form.address1.focus();
    alert("Please enter a shipping address");
    return false;
  }

  form.city.value = Trim(form.city.value);
  if (form.city.value == ""){
    form.city.focus();
    alert("Please enter a shipping city");
    return false;
  }

  form.zipCode.value = Trim(form.zipCode.value);
  if (form.zipCode.value == ""){
    form.zipCode.focus();
    alert("Please enter a shipping zip code");
    return false;
  }

  if (form.country.selectedIndex == 0){
    form.country.focus();
    alert("Please enter a shipping country");
    return false;
  }

  if (form.state.selectedIndex == 0 && (form.country[form.country.selectedIndex].value == "U.S.A." || form.country[form.country.selectedIndex].value == "Canada") ){
    form.state.focus();
    alert("Please enter a shipping state");
    return false;
  }

  if (checkForPOBox(form.address1))
  {
    form.address1.focus();
    alert("Sorry, we are unable to deliver to PO Boxes");
    return false;
  }

  if (checkForPOBox(form.address2))
  {
    form.address2.focus();
    alert("Sorry, we are unable to deliver to PO Boxes");
    return false;
  }

  if (checkForAPOState(form.city, form.state))
  {
    form.state.focus();
    alert("For APO/FPO address, please choose the appropriate 'Armed Forces...' selection in the State/Prov/Terr.");
    return false;
  }

  if (checkForAPOCity(form.state, form.city))
  {
    form.city.focus();
    alert("For APO/FPO address, please enter either APO or FPO in the City");
    return false;
  }

  if (checkForAPOCountry(form.state, form.country))
  {
    form.country.focus();
    alert("For APO/FPO address, please choose U.S.A. as the Country.");
    return false;
  }

  return true;
}


function validateAddress(form)
{
    if (validateBillingAddress(form) == false)
    {
    	return false;
    }
    if (validateShippingAddress(form) == false)
    {	
    	return false;
    }

//  if (!emailCheck(form.email1.value)){
//    form.email1.focus();
//    return false;
//  }


  // set the shipping info
  // shippingSelect(form);
  return true;
}


function validateDiscount(form)
{
   var membershipID = Trim(form.addressField1.value).toString();
   var coupon = Trim(form.addressField2.value).toString();
   var giftCertificate = Trim(form.addressField3.value).toString();

   form.addressField1.value = membershipID;
   form.addressField2.value = coupon;
   form.addressField3.value = giftCertificate;
   
   if (!isEmpty(membershipID) && !isEmpty(coupon))
   {
      if (membershipID == coupon)
      {
         alert ("The same discount code may not be used in more than one field. Please correct your information.");
         form.addressField1.focus();
         return false;
      }
   }
   
   if (!isEmpty(membershipID) && !isEmpty(giftCertificate))
   {
      if (membershipID == giftCertificate)
      {
         alert ("The same discount code may not be used in more than one field. Please correct your information.");
         form.addressField1.focus();
         return false;
      }
   }
   
   if (!isEmpty(coupon) && !isEmpty(giftCertificate))
   {
      if (coupon == giftCertificate)
      {
         alert ("The same discount code may not be used in more than one field. Please correct your information.");
         form.addressField2.focus();
         return false;
      }
   }
   
   return true;
}

function checkForPOBox(txtField)
{
   var poBoxStrs  = new Array();
   poBoxStrs [0]  = "PO BOX";
   poBoxStrs [1]  = "PO. BOX";
   poBoxStrs [2]  = "P.O BOX";
   poBoxStrs [3]  = "P.O. BOX";
   poBoxStrs [4]  = "POBOX";
   poBoxStrs [5]  = "PO.BOX";
   poBoxStrs [6]  = "P.OBOX";
   poBoxStrs [7]  = "P.O.BOX";
   poBoxStrs [8]  = "POST OFFICE BOX";
   poBoxStrs [9]  = "POSTOFFICE BOX";
   poBoxStrs [10] = "POSTOFFICEBOX";
   poBoxStrs [11] = "P.O.B.";
   poBoxStrs [12] = "POB.";
   poBoxStrs [13] = "P.OB";
   poBoxStrs [14] = "PO.B";

   for (i = 0; i < poBoxStrs.length; i++)
   {
      if (txtField.value.length > 0)
         if (txtField.value.toUpperCase().indexOf(poBoxStrs[i]) != -1)
            return true;   
   }
   return false;
}

function checkForAPOState(city, state)
{
   var apoStrs  = new Array();
   apoStrs [0]  = "APO";
   apoStrs [1]  = "FPO";

   for (j = 0; j < apoStrs.length; j++)
   {
      if (city.value.length > 0)
      {
         if (city.value.toUpperCase() == apoStrs[j])
         {
            if (state[state.selectedIndex].value != "AA"
            &&  state[state.selectedIndex].value != "AE"
            &&  state[state.selectedIndex].value != "AP")

               return true;   		// APO or FPO in City but State not one of the "Armed Forces..." choices
         }
      }
   }
   return false;
}

function checkForAPOCountry(state, country)
{
   if (state[state.selectedIndex].value == "AA"
   ||  state[state.selectedIndex].value == "AE"
   ||  state[state.selectedIndex].value == "AP")
   {
      if (country[country.selectedIndex].value != "U.S.A.")
         return true;   // APO State... must choose USA as Country
   }
   return false;
}

function checkForAPOCity(state, city)
{
   if (state[state.selectedIndex].value == "AA"
   ||  state[state.selectedIndex].value == "AE"
   ||  state[state.selectedIndex].value == "AP")
   {
      if (city.value.toUpperCase() != "APO"
      &&  city.value.toUpperCase() != "FPO")
         return true;   // APO State... must have APO or FPO in Shipping City
   }
   return false;
}

//function duplicateShipping(form){
//  if(!form.publishPhone2.checked){
//    form.b_addr1.value =  "";
//    form.b_addr2.value = "";
//    form.b_city.value =    "";
//    form.b_zip.value =    "";
//    form.b_state[0].selected =  true;
//    form.b_country[1].selected = true;
//  }else{
//    form.b_addr1.value =  form.address1.value;
//    form.b_addr2.value = form.address2.value;
//    form.b_city.value =    form.city.value;
//    form.b_zip.value =    form.zipCode.value;
//    form.b_state[form.state.selectedIndex].selected =  true;
//    form.b_country[form.country.selectedIndex].selected = true;
//  } 
//
//}


function duplicateShipping(form){
  if(!form.publishPhone2.checked){
    form.personTitle[0].selected = true;
    form.firstName.value = "";
    form.lastName.value = "";
    form.address1.value = "";
    form.address2.value = "";
    form.city.value     = "";
    form.state[0].selected =  true;
    form.zipCode.value  = "";
    form.country[1].selected = true;
  }else{
    form.personTitle[form.b_personTitle.selectedIndex].selected = true;
    form.firstName.value = form.b_firstName.value;
    form.lastName.value = form.b_lastName.value;
    form.address1.value = form.b_addr1.value;
    form.address2.value = form.b_addr2.value;
    form.city.value     = form.b_city.value;
    form.state[form.b_state.selectedIndex].selected =  true;
    form.zipCode.value  =    form.b_zip.value;
    form.country[form.b_country.selectedIndex].selected = true;
  } 

}


// Utility Functions
//==================================================================
//LTrim(string) : Returns a copy of a string without leading spaces.
//==================================================================
function LTrim(str)
/*
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim
*/
{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}

//==================================================================
//RTrim(string) : Returns a copy of a string without trailing spaces.
//==================================================================
function RTrim(str)
/*
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

*/
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}


//=============================================================
//Trim(string) : Returns a copy of a string without leading or trailing spaces
//=============================================================
function Trim(str)
/*
        PURPOSE: Remove trailing and leading blanks from our string.
        IN: str - the string we want to Trim

        RETVAL: A Trimmed string!
*/
{
        return RTrim(LTrim(str));
}

//=============================================================
//emailCheck(string) : Returns true if email is valid syntax, false otherwise
//=============================================================
function emailCheck (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("The username contains invalid characters in the email address.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters in the email address.");
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 in the email address.");
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 in the email address.");
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 in the email address.");
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 email 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("The email address is missing a hostname");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}
