 function validateFormOnSubmit(theForm) {

       var reason = "";
       reason += validateEmail(theForm.email);
       reason += validateEmpty(theForm.personal_id, "Signature");
       reason += validateEmpty(theForm.firstname, "First Name");  
       reason += validateEmpty(theForm.lastname, "Last Name");    
       reason += validateEmpty(theForm.title, "Title");
       reason += validateEmpty(theForm.company, "Company Name");
       reason += validateEmpty(theForm.business_address1, "Business Address");
       reason += validateEmpty(theForm.business_city, "City");
       reason += validateStateZip(theForm.business_state, theForm.business_zip, theForm.business_country,"business");
       reason += validatePhone(theForm);
       reason += validatePassword(theForm.textfield3);
       reason += validateDeliveryAddress(theForm);
       reason += validateFax(theForm);
       if (reason != "") {
          // alert("Some fields need correction:\n" + reason);
          displayText("formerror");
          window.scrollTo(0,0);
           return false;
       }

       hideText("formerror");
       SubmitFlag = true; 
       return true;

      }


function validateEmpty(fld, name) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "You didn't fill "+name+" field.\n"
    } else {
        if(name='Last Name' && fld.value.length<2){
          fld.style.background = 'Yellow'; 
          error = "You didn't fill "+name+" field.\n"
        }  
        else{
         fld.style.background = 'White';
        }
    }
    return error;   
}

function validatePassword(fld) {

    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    }else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        fld.style.background = 'Yellow';
    }else {
        fld.style.background = 'White';
    }
   return error;
}   

function validatePhone(myForm) {
    var myPhone=myForm.PhoneArea.value+myForm.PhoneExch.value+myForm.PhoneEnd.value;
    var myExtension = myForm.phone_extn.value;
    var error = "";
    var stripped = trim(myPhone);     
    var reservedNumber = ['211','311','411','511','611','711','811','911','900','5551212','1111111111','2222222222','3333333333','4444444444','5555555555','6666666666','7777777777','8888888888','9999999999','0000000000'];;
   if (myExtension != "" && !isNumber(myExtension)){
      error = "The Phone Extension may contains illegal characters.\n";
      myForm.phone_extn.style.background = 'Yellow';
   }
   else
      myForm.phone_extn.style.background = 'White';
          
    if (myPhone == "") {
        error = "You didn't enter a Phone Number.\n";
        myForm.PhoneArea.style.background = 'Yellow';
        myForm.PhoneExch.style.background = 'Yellow';
        myForm.PhoneEnd.style.background = 'Yellow';
    } else if (!isNumber(stripped) || stripped.length != 10) {
        error = "The Phone Number is the wrong length or may contains illegal characters.\n";
        myForm.PhoneArea.style.background = 'Yellow';
        myForm.PhoneExch.style.background = 'Yellow';
        myForm.PhoneEnd.style.background = 'Yellow';
    } else {
        for(var n=0;n<reservedNumber.length; n++){
          if(stripped.indexOf(reservedNumber[n]) ==0){
             error = "It isn't a valid phone number.\n";
             myForm.PhoneArea.style.background = 'Yellow';
             myForm.PhoneExch.style.background = 'Yellow';
             myForm.PhoneEnd.style.background = 'Yellow';
             return error;
           }
         }
        myForm.PhoneArea.style.background = 'White';
        myForm.PhoneExch.style.background = 'White';
        myForm.PhoneEnd.style.background = 'White';
    } 

    return error;
}


function validateFax(myForm) {
    var myFax=myForm.FaxArea.value+myForm.FaxExch.value+myForm.FaxEnd.value;
    var error = "";
    var stripped = trim(myFax);     
    var reservedNumber = ['211','311','411','511','611','711','811','911','900','5551212','1111111111','2222222222','3333333333','4444444444','5555555555','6666666666','7777777777','8888888888','9999999999','0000000000'];;
  
     myForm.FaxArea.style.background = 'White';
     myForm.FaxExch.style.background = 'White';
     myForm.FaxEnd.style.background = 'White';
      
    if (myFax!="" && (!isNumber(stripped) || stripped.length != 10)) {
        error = "The Fax Number is the wrong length or may contains illegal characters.\n";
        myForm.FaxArea.style.background = 'Yellow';
        myForm.FaxExch.style.background = 'Yellow';
        myForm.FaxEnd.style.background = 'Yellow';
    } 
    else if(myFax!=""){
        for(var n=0;n<reservedNumber.length; n++){
          if(stripped.indexOf(reservedNumber[n]) ==0){
             error = "It isn't a valid Fax number.\n";
             myForm.FaxArea.style.background = 'Yellow';
             myForm.FaxExch.style.background = 'Yellow';
             myForm.FaxEnd.style.background = 'Yellow';
           }
         }
    }

    return error;
}

 function validateEmail (fld) {
   
  var error=validateEmpty(fld, "Email");
  if (error != "")
     return error;

  var emailStr = fld.value;
  
/* 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. */

error="Email address seems incorrect (check @ and .'s).\n";
fld.style.background = 'Yellow';
return error;
}
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) {
error = "The Email address contains invalid characters.\n";
fld.style.background = 'Yellow';
return error;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
error = "The Email domain name contains invalid characters.\n";
fld.style.background = 'Yellow';
return error;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

error="The Email address doesn't seem to be valid.\n";
fld.style.background = 'Yellow';
return error;
}

/* 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) {
error="Destination IP address is invalid!\n";
fld.style.background = 'Yellow';
return error;
   }
}
return error;
}

// 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) {
error="The Email domain name does not seem to be valid.\n";
fld.style.background = 'Yellow';
return error;
   }
}

/* 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) {
error="The Email address must end in a well-known domain or two letter " + "country.\n";
fld.style.background = 'Yellow';
return error;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
error="This Email address is missing a hostname!\n";
fld.style.background = 'Yellow';
return error;
}

// If we've gotten this far, everything's valid!
return error;
}

function isNumber(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function trim(str)
{
  return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function trimFrontZeros(str){
  while(str.charAt(0) == "0")
     str=str.substring(1,str.length);

  return str;
     
}

function isUSState(state){

  var usStates = "|AL|AK|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AS|GU|PR|OL|AA|AP|NL|MH|MP|FM|PW|AE|";
  if (usStates.indexOf(state)>0)
     return true;
  else 
     return false;
}

function isCAState(state){

   var caStates = "|AB|BC|MB|NB|NF|NT|NS|NU|ON|PE|QC|SK|UT|OS|";
   if (caStates.indexOf(state)>0)
     return true;
   else
     return false;
}

function validateStateZip(myState, myZip, myCountry, sectionName){
   var error="";
   error += validateEmpty(myState,sectionName+" State");
   error += validateEmpty(myZip,sectionName+" Zip Code");
   if(error != "")
     return error;
   
   var StateZipMap = new Array();
   StateZipMap['AL']=[['350','369']];
   StateZipMap['AK']=[['995','999']];
   StateZipMap['AZ']=[['850','865']];
   StateZipMap['AR']=[['716','729']];   
   StateZipMap['CA']=[['900','961']];
   StateZipMap['CO']=[['800','816']];
   StateZipMap['CT']=[['060','096']];
   StateZipMap['DE']=[['197','199']];
   StateZipMap['DC']=[['200','200'],['202','205'],['569','569']];
   StateZipMap['FL']=[['320','349']];
   StateZipMap['GA']=[['300','319'],['399','399']];
   StateZipMap['HI']=[['967','968']];   
   StateZipMap['ID']=[['832','838']];
   StateZipMap['IL']=[['600','629']];
   StateZipMap['IN']=[['460','479']];
   StateZipMap['IA']=[['500','528']];
   StateZipMap['KS']=[['660','679']];
   StateZipMap['KY']=[['400','427']];
   StateZipMap['LA']=[['700','714']];
   StateZipMap['ME']=[['039','049']];   
   StateZipMap['MD']=[['206','219']];
   StateZipMap['MA']=[['010','027'],['055','055']];
   StateZipMap['MI']=[['480','499']];
   StateZipMap['MN']=[['550','567']];
   StateZipMap['MS']=[['386','397']];
   StateZipMap['MO']=[['630','658']];
   StateZipMap['MT']=[['590','599']];
   StateZipMap['NE']=[['680','693']];   
   StateZipMap['NV']=[['889','898']];
   StateZipMap['NH']=[['030','038']];
   StateZipMap['NJ']=[['070','089']];
   StateZipMap['NM']=[['870','884']];
   StateZipMap['NY']=[['100','149'],['004','004']];
   StateZipMap['NC']=[['270','289']];
   StateZipMap['ND']=[['580','588']];
   StateZipMap['OH']=[['430','459']];   
   StateZipMap['OK']=[['730','749']];
   StateZipMap['OR']=[['970','979']];
   StateZipMap['PA']=[['150','196']];
   StateZipMap['RI']=[['028','029']];
   StateZipMap['SC']=[['290','299']];
   StateZipMap['SD']=[['570','577']];
   StateZipMap['TN']=[['370','385']];
   StateZipMap['TX']=[['750','799'],['885','885']];   
   StateZipMap['UT']=[['840','847']];
   StateZipMap['VT']=[['050','059']];
   StateZipMap['VI']=[['008','008']];
   StateZipMap['VA']=[['201','201'],['220','246']];
   StateZipMap['WA']=[['980','994']];
   StateZipMap['WV']=[['247','268']];
   StateZipMap['WI']=[['530','549']];
   StateZipMap['WY']=[['820','831']];   
   StateZipMap['AA']=[['969','969']];
   StateZipMap['GU']=[['969','969']];
   StateZipMap['PR']=[['006','007'],['009','009']];
   StateZipMap['MH']=[['969','969']];
   StateZipMap['MP']=[['969','969']];
   StateZipMap['FM']=[['969','969']];
   StateZipMap['PW']=[['969','969']];

   var StateZipException = new Array();
   StateZipException['CT']='06390';

   var StateZipSingles = new Array();
   StateZipSingles['NY'] =['06390','00501','00544'];
   StateZipSingles['AA'] =['96799'];
   StateZipSingles['GU'] =['96799'];
   StateZipSingles['MH'] =['96799'];
   StateZipSingles['MP'] =['96799'];
   StateZipSingles['FM'] =['96799'];
   StateZipSingles['PW'] =['96799'];

   var CaStateZipMap = new Array();
   CaStateZipMap['AB']=['T'];
   CaStateZipMap['NS']=['B'];
   CaStateZipMap['BC']=['V'];
   CaStateZipMap['ON']=['K','L','M','N','P'];
   CaStateZipMap['MB']=['R'];
   CaStateZipMap['PE']=['C'];
   CaStateZipMap['NB']=['E'];
   CaStateZipMap['QC']=['K','G','H','J'];
   CaStateZipMap['NF']=['A'];
   CaStateZipMap['SK']=['S'];
   CaStateZipMap['NT']=['X'];
   CaStateZipMap['NU']=['X'];
   CaStateZipMap['UT']=['Y'];
   
   var zip=myZip.value;
   var state = myState.value;
   var  trimmedZip =  trim(zip);

   // US states
   if(myCountry.value =="US" && isUSState(state)){
     myCountry.style.background="White";
     // check format
     if( !isNumber(trimmedZip) || (trimmedZip.length != 5 && trimmedZip.length != 9)){
         myZip.style.background="Yellow";
         error=sectionName+" Zip code must be 5 or 9 digits number.\n";
         return error;
     }  
     var zipRoot = trimmedZip.substring(0,3);
     var zipRanges = StateZipMap[state];
     var zipSingles = StateZipSingles[state];
     var zipExceptions = StateZipException[state];
     //check zip exceptions
     if(zipExceptions != null && zipExceptions == trimmedZip){
        myZip.style.background="Yellow";
        myState.style.background="Yellow";
        error=sectionName+" state and zip code do not match.\n";
        return error;

     }
     
      //not in Map return ""
     if(zipRanges == null && zipSingles == null){
        myZip.style.background="White";
        myState.style.background="White";
        return "";
     }

     //check single list
   if(zipSingles != null){
     for(var i=0;i<zipSingles.length;i++){
         if(zipSingles[i] == trimmedZip){
            myZip.style.background="White";
            mystate.style.background="White";
            return "";
         }
     }
   }
   //check range
   if(zipRanges!= null){
           var intZipRoot=parseInt(trimFrontZeros(zipRoot));
           for( var i=0;i<zipRanges.length; i++){
               var intStart = parseInt(trimFrontZeros(zipRanges[i][0]));
               var intEnd = parseInt(trimFrontZeros(zipRanges[i][1]));
               if(intZipRoot>=intStart && intZipRoot<=intEnd){
                       myZip.style.background="White";
                       myState.style.background="White";
                       return "";
               }
            }

                     myZip.style.background="Yellow";
                     myState.style.background="Yellow";
                     error=sectionName+" state and zip code do not match.\n";
                     return error;
                
        
     }
           

   }
   else if (myCountry.value =="US"){
        myCountry.style.background="Yellow";
        myState.style.background="Yellow";
        error=sectionName+" state and country do not match.\n";
        return error;
   }

   if(myCountry.value =="CA" && isCAState(state) ){
      myCountry.style.background="White";

     // check format
     if( !((trimmedZip.indexOf(" ")==3 && trimmedZip.length == 7) || trimmedZip.length == 6)){
         myZip.style.background="Yellow";
         error=sectionName+" Zip code format incorrect.\n";
         return error;
     }  

     var zipPrefix = CaStateZipMap[state];
     if(zipPrefix == null){
        myZip.style.background="White";
        myState.style.background="White";
        return "";
     }
     else{
        inZipStart=trimmedZip.substring(0,1).toUpperCase();

        for(var j=0; j<zipPrefix.length; j++){    
           if(inZipStart == zipPrefix[j]){
              myZip.style.background="White";
              myState.style.background="White";
              return "";
           }
        }

        myZip.style.background="Yellow";
        myState.style.background="Yellow";
        error=sectionName+" state and zip code do not match.\n";
        return error;
           
     }
     
    }
    else if(myCountry.value =="CA"){
        myCountry.style.background="Yellow";
        myState.style.background="Yellow";
        error=sectionName+" state and country do not match.\n";
        return error;
   }
return error;

}

function validateDeliveryAddress(myForm){
  var error="";
  if(myForm.alternate_address1.value.length ==0 && myForm.alternate_city.value.length ==0 && myForm.alternate_state.value.length ==0 && myForm.alternate_zip_code.value.length ==0)
  {
    myForm.alternate_address1.style.background="White";
    myForm.alternate_city.style.background="White";
    myForm.alternate_state.style.background="White";
    myForm.alternate_zip_code.style.background="White";
    return error;
  } 
   error += validateEmpty(myForm.alternate_address1, "Delivery Street Address");
   error += validateEmpty(myForm.alternate_city, "Delivery City");
   error += validateStateZip(myForm.alternate_state, myForm.alternate_zip_code, myForm.business_country,"delivery");
     
   return error;
}
function copyDeliveryState(selectedState)
{
document.page1form.dStateDel.value = selectedState;
}

function copyBizState(selectedState)
{
document.page1form.dStateBiz.value = selectedState;
}

function displayText(class1) {


      var classTemp=class1

      

      divCols = document.getElementsByTagName("div");



      for (i=0; i<divCols.length; i++) {

 

            if (divCols[i].className == classTemp) {

                  

            //in this version of the function it will show and leave the row there 

            //even if the same event is triggered again

            

                  divCols[i].style.display = (divCols[i].style.display == "none" ) ? "" : "";

                  

            }

 

      }

 

}

 

function hideText(class1) {

      var classTemp=class1

      divCols = document.getElementsByTagName("div");

            

            for (i=0; i<divCols.length; i++) {

 

                  if (divCols[i].className == classTemp) {

                  

                  //in this version of the function it will hide the row for each event

                  divCols[i].style.display = (divCols[i].style.display == "none" ) ? "none" : "none";

                  

            }

 

      }

 

}


     function FreeOnClickNo(){
        var q1value = getRadioValue(document.page1form.answerid1);
        if(q1value == '50000669'){
         var url = 'unsub.jhtml';
         window.open(url,'optimize','height=210,width=510,left=80,top=80')
        }
     }


     function popup(path){
         SubmitFlag = true;
         window.open(path,'optimize','height=700,width=650,left=80,top=80');
         SubmitFlag = false;
      }


function autoTab(value, maxLen, next){

  if (value.length == maxLen)
     next.focus();
}
