/*

function list
1.  isEmailValid(email)
2.  isEmailInDB(email,userid,subdir,user) //if for new login, pass userid=0, otherwise passuserid to filter out,
    (both uer and haulier)           //if in subdirectory, pass subdir=1, otherwise in root, pass subdir=0
                                     //if user==1, this is to check user, 0, check haulier
3.  isNameInDB(name,userid,subdir,user)   //check if userName already in DB

4. isNum(val)

5.addCommas(nStr) //add comma to the number string

6. updateStateForDifferentCountry(country,stateControlName,timeDifControlName)    Can increase this function, but the value name must be the same as that in DB

7. checkPostCodeValidity(postcode,countryName)   

*/

 function checkCanadaPartPostCodeValidity(postcode)  
 {
            var regPatern=/^\D{1}\d{1}\D{1}$/;
            if(regPatern.test(postcode))
            {      
                    return postcode.toUpperCase();
            }else
            {
                    return false;
            }
 
 }
 
 
 function checkPostCodeValidity(postcode,countryName)
  {   
        if(countryName=="CA")
        {
            postcode=postcode.replace(" ","");
            var regPatern=/^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
            if(regPatern.test(postcode))
            {                
                    postcode=postcode.substr(0,3)+" "+postcode.substr(3,3);
                    return postcode.toUpperCase();
            }else
            {
                    return false;
            }
        }
        
        if(countryName=="US")
        {
            var regPatern=/(^\d{5,5}$)|(^\d{5}-\d{4}$)/;
            if(regPatern.test(postcode))
            {     
                     return postcode.toUpperCase();   
            }else
            {
                    return false;
            }
        }
        
         if(countryName=="AU")
        {
            var regPatern=/(^\d{3,4}$)/;
            if(regPatern.test(postcode))
            {     
                     return postcode.toUpperCase();   
            }else
            {
                    return false;
            }
        }
        
        if(countryName=="UK")
        {
                
                 // Permitted letters depend upon their position in the postcode.
                  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
                  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
                  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
                  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
                  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5


                  // Array holds the regular expressions for the valid postcodes
                  var pcexp = new Array ();

                  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
                  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

                  // Expression for postcodes: ANA NAA
                  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

                  // Expression for postcodes: AANA  NAA
                  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

                  // Exception for the special postcode GIR 0AA
                  pcexp.push (/^(GIR)(\s*)(0AA)$/i);

                  // Standard BFPO numbers
                  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);

                  // c/o BFPO numbers
                  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

                  // Load up the string to check
                  var postCode = postcode;

                  // Assume we're not going to find a valid postcode
                  var valid = false;

                      // Check the string against the types of post codes
                      for ( var i=0; i<pcexp.length; i++) {
                        if (pcexp[i].test(postCode)) {

                          // The post code is valid - split the post code into component parts
                          pcexp[i].exec(postCode);

                          // Copy it back into the original string, converting it to uppercase and
                          // inserting a space between the inward and outward codes
                          postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();

                          // If it is a BFPO c/o type postcode, tidy up the "c/o" part
                          postCode = postCode.replace (/C\/O\s*/,"c/o ");

                          // Load new postcode back into the form element
                          valid = true;

                          // Remember that we have found that the code is valid and break from loop
                          break;
                        }
                      }

                      // Return with either the reformatted valid postcode or the original invalid
                      // postcode
                      if (valid) {return postCode;} else return false;
                 
        }
       
        return true;
  }
              

 function addOption(selectbox,text,value )
 {
        var optn = document.createElement("OPTION");
        optn.text = text;
        optn.value = value;
        selectbox.options.add(optn);
 }

function updateStateForDifferentCountry(country,stateControlName,timeDifControlName)
{                                   
        len2 = document.getElementById(stateControlName).options.length;
                for (var i = len2; i > 0; i = i - 1) {
                    document.getElementById(stateControlName).remove(i-1);
                }
             //   document.getElementById(stateControlName).options.length=0;
                
        if(country=="UK")
        {             
                addOption(document.getElementById(stateControlName), "England", "EN");
                addOption(document.getElementById(stateControlName), "Scotland", "ST"); 
                addOption(document.getElementById(stateControlName), "Wales", "WL"); 
                addOption(document.getElementById(stateControlName), "N.A", "NA"); 
                addOption(document.getElementById(stateControlName), "Northern Ireland", "NI");
                
                if(timeDifControlName!="")
                {
                    document.getElementById(timeDifControlName).value="0" 
                }
        }
        if(country=="US")
        {
                addOption(document.getElementById(stateControlName), "Alabama", "AL"); 
                addOption(document.getElementById(stateControlName), "Alaska", "AK"); 
                addOption(document.getElementById(stateControlName), "Arizona", "AZ"); 
                addOption(document.getElementById(stateControlName), "Arkansas", "AR"); 
                addOption(document.getElementById(stateControlName), "California", "CA"); 
                addOption(document.getElementById(stateControlName), "Colorado", "CO"); 
                addOption(document.getElementById(stateControlName), "Connecticut", "CT"); 
                addOption(document.getElementById(stateControlName), "Delaware", "DE"); 
                addOption(document.getElementById(stateControlName), "District of Columbia", "DC"); 
                addOption(document.getElementById(stateControlName), "Florida", "FL"); 
            
           
         
                addOption(document.getElementById(stateControlName), "Georgia", "GA"); 
                addOption(document.getElementById(stateControlName), "Hawaii", "HI"); 
                addOption(document.getElementById(stateControlName), "Idaho", "ID"); 
                addOption(document.getElementById(stateControlName), "Illinois", "IL"); 
                addOption(document.getElementById(stateControlName), "Indiana", "IN"); 
                addOption(document.getElementById(stateControlName), "Iowa", "IA"); 
                addOption(document.getElementById(stateControlName), "Kansas", "KS"); 
                addOption(document.getElementById(stateControlName), "Kentucky", "KY"); 
                addOption(document.getElementById(stateControlName), "Louisiana", "LA"); 
                addOption(document.getElementById(stateControlName), "Maine", "MaineME"); 
            
                addOption(document.getElementById(stateControlName), "Maryland", "MD"); 
                addOption(document.getElementById(stateControlName), "Massachusetts", "MA"); 
                addOption(document.getElementById(stateControlName), "Michigan", "MI"); 
                addOption(document.getElementById(stateControlName), "Minnesota", "MN"); 
                addOption(document.getElementById(stateControlName), "Mississippi", "MS"); 
                addOption(document.getElementById(stateControlName), "Missouri", "MO"); 
                addOption(document.getElementById(stateControlName), "Montana", "MT"); 
                addOption(document.getElementById(stateControlName), "Nebraska", "NE"); 
                addOption(document.getElementById(stateControlName), "Nevada", "NV"); 
                addOption(document.getElementById(stateControlName), "New Hampshire", "NH"); 
           
                addOption(document.getElementById(stateControlName), "New Jersey", "NJ"); 
                addOption(document.getElementById(stateControlName), "New Mexico", "NM"); 
                addOption(document.getElementById(stateControlName), "New York", "NY"); 
                addOption(document.getElementById(stateControlName), "North Carolina", "NC"); 
                addOption(document.getElementById(stateControlName), "North Dakota", "ND"); 
                addOption(document.getElementById(stateControlName), "Ohio", "OH"); 
                addOption(document.getElementById(stateControlName), "Oklahoma", "OK"); 
                addOption(document.getElementById(stateControlName), "Oregon", "OR"); 
                addOption(document.getElementById(stateControlName), "Pennsylvania", "PA"); 
                addOption(document.getElementById(stateControlName), "Puerto Rico", "PR"); 
                
                addOption(document.getElementById(stateControlName), "Rhode Island", "RI"); 
                
                addOption(document.getElementById(stateControlName), "South Carolina", "SC"); 
                addOption(document.getElementById(stateControlName), "South Dakota", "SD"); 
                addOption(document.getElementById(stateControlName), "Tennessee", "TN"); 
                addOption(document.getElementById(stateControlName), "Texas", "TX"); 
                addOption(document.getElementById(stateControlName), "Utah", "UT"); 
                addOption(document.getElementById(stateControlName), "Vermont", "VT"); 
                addOption(document.getElementById(stateControlName), "Virginia", "VA"); 
                addOption(document.getElementById(stateControlName), "Washington", "WA"); 
                addOption(document.getElementById(stateControlName), "West Virginia", "WV"); 
                addOption(document.getElementById(stateControlName), "Wisconsin", "WI"); 
                
                addOption(document.getElementById(stateControlName), "Wyoming", "WY"); 
                
               
                
                if(timeDifControlName!="")
                {
                  document.getElementById(timeDifControlName).value="-5" 
                }
                
        }
        
        if(country=="CA")
        {
                addOption(document.getElementById(stateControlName), "Alberta", "AB"); 
                addOption(document.getElementById(stateControlName), "British Columbia", "BC"); 
                addOption(document.getElementById(stateControlName), "Manitoba", "MB"); 
                addOption(document.getElementById(stateControlName), "New Brunswich", "NB"); 
                addOption(document.getElementById(stateControlName), "Newfoundland and Labrador", "NF"); 
                addOption(document.getElementById(stateControlName), "Northwest Territories", "NT"); 
                addOption(document.getElementById(stateControlName), "Nova Scotia", "NS"); 
                addOption(document.getElementById(stateControlName), "Nunavut", "NU"); 
                addOption(document.getElementById(stateControlName), "Ontario", "ON"); 
                addOption(document.getElementById(stateControlName), "Prince Edward Island", "PE"); 
                addOption(document.getElementById(stateControlName), "Quebec", "QC"); 
                addOption(document.getElementById(stateControlName), "Saskatchewan", "SK"); 
                addOption(document.getElementById(stateControlName), "Yukon Territory", "YT");   
                
                if(timeDifControlName!="")
                {
                   document.getElementById(timeDifControlName).value="-5" 
                }
                
        }
        
         if(country=="AU")
        {
                addOption(document.getElementById(stateControlName), "ACT", "ACT"); 
                addOption(document.getElementById(stateControlName), "Northern Territory", "NT"); 
                addOption(document.getElementById(stateControlName), "Queensland", "QLD"); 
                addOption(document.getElementById(stateControlName), "New South Wales", "NSW"); 
                addOption(document.getElementById(stateControlName), "Western Australia", "WA"); 
                addOption(document.getElementById(stateControlName), "Victoria", "VIC"); 
                addOption(document.getElementById(stateControlName), "Tasmania", "TAS"); 
                addOption(document.getElementById(stateControlName), "South Australia", "SA"); 
                
                if(timeDifControlName!="")
                {                                     
                  document.getElementById(timeDifControlName).value="10" 
                }                              
        }
        
         if(country=="CN")
        {              
              //  addOption(document.getElementById(stateControlName), "BEIJING", "BEIJING"); 
              //  addOption(document.getElementById(stateControlName), "TIANJIN", "TIANJIAN"); 
              //  addOption(document.getElementById(stateControlName), "SHANGHAI", "SHANGHAI"); 
              //  addOption(document.getElementById(stateControlName), "CHONGQING", "CHONGQING"); 
               
                
                addOption(document.getElementById(stateControlName), "ANHUI", "ANHUI"); 
                addOption(document.getElementById(stateControlName), "FUJIAN", "FUJIAN"); 
                addOption(document.getElementById(stateControlName), "GANSU", "GANSU"); 
                addOption(document.getElementById(stateControlName), "GUANGDONG", "GUANGDONG"); 
                addOption(document.getElementById(stateControlName), "GUANGXI", "GUANGXI"); 
                addOption(document.getElementById(stateControlName), "GUIZHOU", "GUIZHOU"); 
                addOption(document.getElementById(stateControlName), "HAINAN", "HAINAN"); 
                addOption(document.getElementById(stateControlName), "HEILONGJIANG", "HEILONGJIANG"); 
               
                addOption(document.getElementById(stateControlName), "HEBEI", "HEBEI"); 
                addOption(document.getElementById(stateControlName), "HENAN", "HENAN"); 
                addOption(document.getElementById(stateControlName), "HUBEI", "HUBEI"); 
                addOption(document.getElementById(stateControlName), "HUNAN", "HUNAN"); 
                addOption(document.getElementById(stateControlName), "JIANGSU", "JIANGSU"); 
                addOption(document.getElementById(stateControlName), "JIANGXI", "JIANGXI"); 
                addOption(document.getElementById(stateControlName), "JILIN", "JILIN"); 
                addOption(document.getElementById(stateControlName), "LIAONING", "LIAONING"); 
                   
                addOption(document.getElementById(stateControlName), "NEIMONGGU", "NEIMONGGU"); 
                addOption(document.getElementById(stateControlName), "QINGHAI", "QINGHAI"); 
                addOption(document.getElementById(stateControlName), "SHAANXI", "SHAANXI"); 
                addOption(document.getElementById(stateControlName), "SHANDONG", "SHANDONG"); 
                addOption(document.getElementById(stateControlName), "SHANXI", "SHANXI"); 
                addOption(document.getElementById(stateControlName), "SICHUAN", "SICHUAN"); 
                addOption(document.getElementById(stateControlName), "XINJIANG", "XINJIANG"); 
                addOption(document.getElementById(stateControlName), "YUNNAN", "YUNNAN"); 
                addOption(document.getElementById(stateControlName), "ZHEJIANG", "ZHEJIANG"); 
                addOption(document.getElementById(stateControlName), "XIZANG", "XIZANG"); 
                
                if(timeDifControlName!="")
                {                                     
                  document.getElementById(timeDifControlName).value="8" 
                }                              
        }
         if(country=="HK")
        {
             if(timeDifControlName!="")
                {                                     
                  document.getElementById(timeDifControlName).value="8" 
                } 
        }
        
        
        addOption(document.getElementById(stateControlName), "Other", "other"); 
        
        
        document.getElementById(stateControlName).selectedIndex=0;
}

function updateStateForDifferentCountryWithAll(country,stateControlName,timeDifControlName)
{                                   
        len2 = document.getElementById(stateControlName).options.length;
                for (var i = len2; i > 0; i = i - 1) {
                    document.getElementById(stateControlName).remove(i-1);
                }
             //   document.getElementById(stateControlName).options.length=0;
        addOption(document.getElementById(stateControlName), "All the states/provinces", "ALL");         
        if(country=="UK")
        {             
                addOption(document.getElementById(stateControlName), "England", "EN");
                addOption(document.getElementById(stateControlName), "Scotland", "ST"); 
                addOption(document.getElementById(stateControlName), "Wales", "WL"); 
                addOption(document.getElementById(stateControlName), "N.A", "NA"); 
                addOption(document.getElementById(stateControlName), "Northern Ireland", "NI");
                
                if(timeDifControlName!="")
                {
                    document.getElementById(timeDifControlName).value="0" 
                }
        }
        if(country=="US")
        {
                addOption(document.getElementById(stateControlName), "Alabama", "AL"); 
                addOption(document.getElementById(stateControlName), "Alaska", "AK"); 
                addOption(document.getElementById(stateControlName), "Arizona", "AZ"); 
                addOption(document.getElementById(stateControlName), "Arkansas", "AR"); 
                addOption(document.getElementById(stateControlName), "California", "CA"); 
                addOption(document.getElementById(stateControlName), "Colorado", "CO"); 
                addOption(document.getElementById(stateControlName), "Connecticut", "CT"); 
                addOption(document.getElementById(stateControlName), "Delaware", "DE"); 
                addOption(document.getElementById(stateControlName), "District of Columbia", "DC"); 
                addOption(document.getElementById(stateControlName), "Florida", "FL"); 
            
           
         
                addOption(document.getElementById(stateControlName), "Georgia", "GA"); 
                addOption(document.getElementById(stateControlName), "Hawaii", "HI"); 
                addOption(document.getElementById(stateControlName), "Idaho", "ID"); 
                addOption(document.getElementById(stateControlName), "Illinois", "IL"); 
                addOption(document.getElementById(stateControlName), "Indiana", "IN"); 
                addOption(document.getElementById(stateControlName), "Iowa", "IA"); 
                addOption(document.getElementById(stateControlName), "Kansas", "KS"); 
                addOption(document.getElementById(stateControlName), "Kentucky", "KY"); 
                addOption(document.getElementById(stateControlName), "Louisiana", "LA"); 
                addOption(document.getElementById(stateControlName), "Maine", "ME"); 
            
                addOption(document.getElementById(stateControlName), "Maryland", "MD"); 
                addOption(document.getElementById(stateControlName), "Massachusetts", "MA"); 
                addOption(document.getElementById(stateControlName), "Michigan", "MI"); 
                addOption(document.getElementById(stateControlName), "Minnesota", "MN"); 
                addOption(document.getElementById(stateControlName), "Mississippi", "MS"); 
                addOption(document.getElementById(stateControlName), "Missouri", "MO"); 
                addOption(document.getElementById(stateControlName), "Montana", "MT"); 
                addOption(document.getElementById(stateControlName), "Nebraska", "NE"); 
                addOption(document.getElementById(stateControlName), "Nevada", "NV"); 
                addOption(document.getElementById(stateControlName), "New Hampshire", "NH"); 
           
                addOption(document.getElementById(stateControlName), "New Jersey", "NJ"); 
                addOption(document.getElementById(stateControlName), "New Mexico", "NM"); 
                addOption(document.getElementById(stateControlName), "New York", "NY"); 
                addOption(document.getElementById(stateControlName), "North Carolina", "NC"); 
                addOption(document.getElementById(stateControlName), "North Dakota", "ND"); 
                addOption(document.getElementById(stateControlName), "Ohio", "OH"); 
                addOption(document.getElementById(stateControlName), "Oklahoma", "OK"); 
                addOption(document.getElementById(stateControlName), "Oregon", "OR"); 
                addOption(document.getElementById(stateControlName), "Pennsylvania", "PA"); 
                addOption(document.getElementById(stateControlName), "Puerto Rico", "PR"); 
                
                addOption(document.getElementById(stateControlName), "Rhode Island", "RI"); 
                
                addOption(document.getElementById(stateControlName), "South Carolina", "SC"); 
                addOption(document.getElementById(stateControlName), "South Dakota", "SD"); 
                addOption(document.getElementById(stateControlName), "Tennessee", "TN"); 
                addOption(document.getElementById(stateControlName), "Texas", "TX"); 
                addOption(document.getElementById(stateControlName), "Utah", "UT"); 
                addOption(document.getElementById(stateControlName), "Vermont", "VT"); 
                addOption(document.getElementById(stateControlName), "Virginia", "VA"); 
                addOption(document.getElementById(stateControlName), "Washington", "WA"); 
                addOption(document.getElementById(stateControlName), "West Virginia", "WV"); 
                addOption(document.getElementById(stateControlName), "Wisconsin", "WI"); 
                
                addOption(document.getElementById(stateControlName), "Wyoming", "WY"); 
                
               
                
                if(timeDifControlName!="")
                {
                  document.getElementById(timeDifControlName).value="-5" 
                }
                
        }
        
        if(country=="CA")
        {
                addOption(document.getElementById(stateControlName), "Alberta", "AB"); 
                addOption(document.getElementById(stateControlName), "British Columbia", "BC"); 
                addOption(document.getElementById(stateControlName), "Manitoba", "MB"); 
                addOption(document.getElementById(stateControlName), "New Brunswick", "NB"); 
                addOption(document.getElementById(stateControlName), "Newfoundland and Labrador", "NF"); 
                addOption(document.getElementById(stateControlName), "Northwest Territories", "NT"); 
                addOption(document.getElementById(stateControlName), "Nova Scotia", "NS"); 
                addOption(document.getElementById(stateControlName), "Nunavut", "NU"); 
                addOption(document.getElementById(stateControlName), "Ontario", "ON"); 
                addOption(document.getElementById(stateControlName), "Prince Edward Island", "PE"); 
                addOption(document.getElementById(stateControlName), "Quebec", "QC"); 
                addOption(document.getElementById(stateControlName), "Saskatchewan", "SK"); 
                addOption(document.getElementById(stateControlName), "Yukon Territory", "YT");   
                
                if(timeDifControlName!="")
                {
                   document.getElementById(timeDifControlName).value="-5" 
                }
                
        }
        
         if(country=="AU")
        {
                addOption(document.getElementById(stateControlName), "ACT", "ACT"); 
                addOption(document.getElementById(stateControlName), "Northern Territory", "NT"); 
                addOption(document.getElementById(stateControlName), "Queensland", "QLD"); 
                addOption(document.getElementById(stateControlName), "New South Wales", "NSW"); 
                addOption(document.getElementById(stateControlName), "Western Australia", "WA"); 
                addOption(document.getElementById(stateControlName), "Victoria", "VIC"); 
                addOption(document.getElementById(stateControlName), "Tasmania", "TAS"); 
                addOption(document.getElementById(stateControlName), "South Australia", "SA"); 
                
                if(timeDifControlName!="")
                {                                     
                  document.getElementById(timeDifControlName).value="10" 
                }                              
        }
        
         if(country=="CN")
        {              
              //  addOption(document.getElementById(stateControlName), "BEIJING", "BEIJING"); 
              //  addOption(document.getElementById(stateControlName), "TIANJIN", "TIANJIAN"); 
              //  addOption(document.getElementById(stateControlName), "SHANGHAI", "SHANGHAI"); 
              //  addOption(document.getElementById(stateControlName), "CHONGQING", "CHONGQING"); 
               
                
                addOption(document.getElementById(stateControlName), "ANHUI", "ANHUI"); 
                addOption(document.getElementById(stateControlName), "FUJIAN", "FUJIAN"); 
                addOption(document.getElementById(stateControlName), "GANSU", "GANSU"); 
                addOption(document.getElementById(stateControlName), "GUANGDONG", "GUANGDONG"); 
                addOption(document.getElementById(stateControlName), "GUANGXI", "GUANGXI"); 
                addOption(document.getElementById(stateControlName), "GUIZHOU", "GUIZHOU"); 
                addOption(document.getElementById(stateControlName), "HAINAN", "HAINAN"); 
                addOption(document.getElementById(stateControlName), "HEILONGJIANG", "HEILONGJIANG"); 
               
                addOption(document.getElementById(stateControlName), "HEBEI", "HEBEI"); 
                addOption(document.getElementById(stateControlName), "HENAN", "HENAN"); 
                addOption(document.getElementById(stateControlName), "HUBEI", "HUBEI"); 
                addOption(document.getElementById(stateControlName), "HUNAN", "HUNAN"); 
                addOption(document.getElementById(stateControlName), "JIANGSU", "JIANGSU"); 
                addOption(document.getElementById(stateControlName), "JIANGXI", "JIANGXI"); 
                addOption(document.getElementById(stateControlName), "JILIN", "JILIN"); 
                addOption(document.getElementById(stateControlName), "LIAONING", "LIAONING"); 
                   
                addOption(document.getElementById(stateControlName), "NEIMONGGU", "NEIMONGGU"); 
                addOption(document.getElementById(stateControlName), "QINGHAI", "QINGHAI"); 
                addOption(document.getElementById(stateControlName), "SHAANXI", "SHAANXI"); 
                addOption(document.getElementById(stateControlName), "SHANDONG", "SHANDONG"); 
                addOption(document.getElementById(stateControlName), "SHANXI", "SHANXI"); 
                addOption(document.getElementById(stateControlName), "SICHUAN", "SICHUAN"); 
                addOption(document.getElementById(stateControlName), "XINJIANG", "XINJIANG"); 
                addOption(document.getElementById(stateControlName), "YUNNAN", "YUNNAN"); 
                addOption(document.getElementById(stateControlName), "ZHEJIANG", "ZHEJIANG"); 
                addOption(document.getElementById(stateControlName), "XIZANG", "XIZANG"); 
                
                if(timeDifControlName!="")
                {                                     
                  document.getElementById(timeDifControlName).value="8" 
                }                              
        }
         if(country=="HK")
        {
             if(timeDifControlName!="")
                {                                     
                  document.getElementById(timeDifControlName).value="8" 
                } 
        }
        
        
        addOption(document.getElementById(stateControlName), "Other", "other"); 
        
        
        document.getElementById(stateControlName).selectedIndex=0;
}




function getexpirydate(nodays){
         var UTCstring;
         Today = new Date();
         nomilli=Date.parse(Today);
         Today.setTime(nomilli+nodays*24*60*60*1000);
         UTCstring = Today.toUTCString();
         return UTCstring;
}
function getcookie(cookiename) {
         var cookiestring=""+document.cookie;
         var index1=cookiestring.indexOf(cookiename);
         if (index1==-1 || cookiename=="") return "";
         var index2=cookiestring.indexOf(';',index1);
         if (index2==-1) index2=cookiestring.length;
             return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}
function setcookie(name,value,duration){

        cookiestring=name+"="+escape(value)+";EXPIRES="+getexpirydate(duration);
        document.cookie=cookiestring;

         if(!getcookie(name)){
             return false;
             }
             else{
             return true;
             }

}


function isEmailValid(email)
{
     if(email.indexOf(".")< 0 || email.indexOf("@")< 0)
     {
      return false;
     }else
     {
      return true;
     }

}

function isHEX(val)
{
        val=val.toString();
        if(val=="") return true;
        if(val.length==0)
        return false;
        for(var n=1;n<val.length;n++)
        {
                if(! ( (val.substring(n,n+1)>="0" && val.substring(n,n+1)<="9")
                     || (val.substring(n,n+1)=="a")
                     || (val.substring(n,n+1)=="b")
                     || (val.substring(n,n+1)=="c")
                     || (val.substring(n,n+1)=="d")
                     || (val.substring(n,n+1)=="e")
                     || (val.substring(n,n+1)=="f")
                     || (val.substring(n,n+1)=="A")
                     || (val.substring(n,n+1)=="B")
                     || (val.substring(n,n+1)=="C")
                     || (val.substring(n,n+1)=="D")
                     || (val.substring(n,n+1)=="E")
                     || (val.substring(n,n+1)=="F")
                     )
                )
                {
                 return false;
                }
        }
        return true;
}

function isNum(val){

        val=val.toString();
        if(val=="") return true;
        if(val.length==0)
        return false;
        for(var n=0;n<val.length;n++)
        {
              if((val.substring(n,n+1)<"0" || val.substring(n,n+1) >"9")
               && !(val.substring(n,n+1)==",")  && !(val.substring(n,n+1)=="."))
               {
                 return false;
               }

        }
        return true;
}

function isPureNum(val){

        val=val.toString();
        if(val=="") return true;
        if(val.length==0)
        return false;
        for(var n=0;n<val.length;n++)
        {
              if((val.substring(n,n+1)<"0" || val.substring(n,n+1) >"9"))
               {
                 return false;
               }

        }
        return true;
}


             function GetXmlHttpObject()
             {
                  var objXMLHttp=null
                  if (window.XMLHttpRequest)
                  {
                  objXMLHttp=new XMLHttpRequest()
                  }
                  else if (window.ActiveXObject)
                  {
                  objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
                  }
                  return objXMLHttp
             }

             var xmlHttpEmail
             function isEmailInDB(email,userid,subdir,user)      //used to check email in time
             {
                  xmlHttpEmail=GetXmlHttpObject();
                  if (xmlHttpEmail==null)
                  {
                  alert ("Browser does not support HTTP Request")
                  return
                  }

                  if(subdir>0)
                  {
                    var url="../chkEmailInDB.php"
                  }else
                  {
                    var url="chkEmailInDB.php"
                  }

                  url=url+"?q="+email
                  if(userid>0)
                  {
                   url=url+"&userid="+userid;
                  }

                  if(user==1)
                  {
                   url=url+"&role=users";
                  }else
                  {
                   url=url+"&role=hauliers";
                  }


                  url=url+"&sid="+Math.random()
                  xmlHttpEmail.onreadystatechange=stateChangedForEmail
                  xmlHttpEmail.open("GET",url,true)
                  xmlHttpEmail.send(null)
             }


             function stateChangedForEmail()
             {

                    if (xmlHttpEmail.readyState==4 || xmlHttpEmail.readyState=="complete")
                    {
                        str=xmlHttpEmail.responseText;
                        if(str>0)
                        {
                           alert ("Email already existed in our system, you can not use this email again again!\nPlease login with your email and password or register with another email!\nThanks");
                           return;
                        }
                    }
             }

             var xmlHttpName
             function isNameInDB(name,userid,subdir,user)
             {
                  xmlHttpName=GetXmlHttpObject();
                  if (xmlHttpName==null)
                  {
                  alert ("Browser does not support HTTP Request")
                  return
                  }

                  if(subdir>0)
                  {
                   var url="../chkNameInDB.php"
                  }else
                  {
                   var url="chkNameInDB.php"
                  }

                  url=url+"?q="+name
                  if(userid>0)
                  {
                   url=url+"&userid="+userid;
                  }

                  if(user==1)
                  {
                   url=url+"&role=users";
                  }else
                  {
                   url=url+"&role=hauliers";
                  }


                  url=url+"&sid="+Math.random()
                  xmlHttpName.onreadystatechange=stateChangedForName
                  xmlHttpName.open("GET",url,true)
                  xmlHttpName.send(null)
             }

             function stateChangedForName()
             {
                    if (xmlHttpName.readyState==4 || xmlHttpName.readyState=="complete")
                    {
                        str=xmlHttpName.responseText;
                        if(str>0)
                        {
                           alert ("User name already existed in our system, please register with another name!\nThanks");
                           return;
                        }
                    }
             }

             function getFutureDate(days)
             {
                      var myDate=new Date()
                      myDate.setDate(myDate.getDate()+ parseInt(days))                     
                      return myDate;
             }

             function setCertainDate(year,month,day)
             {
                      var myDate=new Date()
                      myDate.setFullYear(parseInt(year),parseInt(strip0(month))-1,parseInt(strip0(day)))
                      return myDate;
             }                     

              function setCertainDateNew(year,month,day)
             {
                       var myDate=new Date()
                      myDate.setFullYear(parseInt(year),parseInt(strip0(month))-1,parseInt(strip0(day)))
                      return myDate;
             } 
             
             function getFutureDateFromCertainDate(certainDT,days)
             {     
                     certainDT.setDate(certainDT.getDate()+ parseInt(days))                    
                     return certainDT;
             }
             
             function strip0(str)
             {
                      if(str.substr(0,1)=="0")
                      {
                         return str.substr(1,1);
                      }else
                      {
                       return str;
                      }
             }
                       

             function addCommas(nStr)
{
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
}

function removeCommas(aNum) {

//remove any commas

aNum=aNum.replace(/,/g,"");

//remove any spaces

aNum=aNum.replace(/\s/g,"");

return aNum;

}//end of removeCommas(aNum)




/*******************************************************************/
/***                                                             ***/
/***   Tokenizer.js - JavaScript String Tokenizer Function       ***/
/***                                                             ***/
/***   Version   : 0.2                                           ***/
/***   Date      : 01.05.2005                                    ***/
/***   Copyright : 2005 Adrian Zentner                           ***/
/***   Website   : http://www.adrian.zentner.name/               ***/
/***                                                             ***/
/***   This library is free software. It can be freely used as   ***/
/***   long as this this copyright notice is not removed.        ***/
/***
/***var myString = "These, are, comma, separated, tokens, and,   ***/
/***  whitespaces, will, be, omitted";                           ***/

/***var tokens = myString.tokenize(",", " ", true);              ***/

/***for(var i=0; i<tokens.length; i++)                           ***/
/***  window.alert(i + ". token: " + tokens[i]);                 ***/
/*******************************************************************/

String.prototype.tokenize = tokenize;

function tokenize()
  {
     var input             = "";
     var separator         = " ";
     var trim              = "";
     var ignoreEmptyTokens = true;

     try {
       String(this.toLowerCase());
     }
     catch(e) {
       window.alert("Tokenizer Usage: string myTokens[] = myString.tokenize(string separator, string trim, boolean ignoreEmptyTokens);");
       return;
     }

     if(typeof(this) != "undefined")
       {
          input = String(this);
       }

     if(typeof(tokenize.arguments[0]) != "undefined")
       {
          separator = String(tokenize.arguments[0]);
       }

     if(typeof(tokenize.arguments[1]) != "undefined")
       {
          trim = String(tokenize.arguments[1]);
       }

     if(typeof(tokenize.arguments[2]) != "undefined")
       {
          if(!tokenize.arguments[2])
            ignoreEmptyTokens = false;
       }

     var array = input.split(separator);

     if(trim)
       for(var i=0; i<array.length; i++)
         {
           while(array[i].slice(0, trim.length) == trim)
             array[i] = array[i].slice(trim.length);
           while(array[i].slice(array[i].length-trim.length) == trim)
             array[i] = array[i].slice(0, array[i].length-trim.length);
         }

     var token = new Array();
     if(ignoreEmptyTokens)
       {
          for(var i=0; i<array.length; i++)
            if(array[i] != "")
              token.push(array[i]);
       }
     else
       {
          token = array;
       }

     return token;
  }

  function popup(mylink, windowname)
{
         if (! window.focus)return true;
         var href;
         if (typeof(mylink) == 'string')
            href=mylink;
         else
            href=mylink.href;
         window.open(href, windowname, 'width=400,height=400,scrollbars=yes');
         return false;
}

function newpopup(mylink, windowname,width,height)
{
         if (! window.focus)return true;
         var href;
         if (typeof(mylink) == 'string')
            href=mylink;
         else
            href=mylink.href;
         window.open(href, windowname, "width="+width+",height="+height+",scrollbars=yes");
         return false;
}


function replaceAll( str, from, to ) {
    var idx = str.indexOf( from );


    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }

    return str;
}

/*****below start javascript dealing function for displaying the route table ****/

function chkRoute(tagName)
{
    //this is the checking of the whole checkbox to control the display of whole table
    chkControl="chkDsp_"+tagName;
    tableName="tblWholeTable_"+tagName;
    if(document.getElementById(chkControl).checked)
    {
      document.getElementById(tableName).style.display="";  
    }else
    {
      document.getElementById(tableName).style.display="none";  
    }
}




function sel_routeType(TagName,From)
{   
    //control of display type of route
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
    tblName=From==1?"Frm":"To";
  
    tblRegion="tblrouteRegion"+tblName+"_"+TagName;
    tblCountry="tblrouteCountry"+tblName+"_"+TagName;
    tblState="tblrouteState"+tblName+"_"+TagName;
    tblCity="tblrouteCity"+tblName+"_"+TagName;
    tblPostCodes="tblroutePostCodes"+tblName+"_"+TagName;
    tblPostCode="tblroutePostCode"+tblName+"_"+TagName;
  
    selTagName="routeType"+tblName+"_"+TagName; 
    selType=document.getElementById(selTagName).value;
    if(selType==0)    //Anywhere in the world
    {
       document.getElementById(tblRegion).style.display="none";
       document.getElementById(tblCountry).style.display="none";
       document.getElementById(tblState).style.display="none";
       document.getElementById(tblCity).style.display="none";
       document.getElementById(tblPostCodes).style.display="none";
       document.getElementById(tblPostCode).style.display="none";
    }
      if(selType==1)    //Region 
    {
       document.getElementById(tblRegion).style.display="";
       document.getElementById(tblCountry).style.display="none";
       document.getElementById(tblState).style.display="none";
       document.getElementById(tblCity).style.display="none";
       document.getElementById(tblPostCodes).style.display="none";
       document.getElementById(tblPostCode).style.display="none";
    }
    if(selType==2)    //Country 
    {
       document.getElementById(tblRegion).style.display="none";
       document.getElementById(tblCountry).style.display="";
       document.getElementById(tblState).style.display="none";
       document.getElementById(tblCity).style.display="none";
       document.getElementById(tblPostCodes).style.display="none";
       document.getElementById(tblPostCode).style.display="none";
    }
     if(selType==3)    //Country + State/Province
    {
       document.getElementById(tblRegion).style.display="none";
       document.getElementById(tblCountry).style.display="";
       document.getElementById(tblState).style.display="";
       document.getElementById(tblCity).style.display="none";
       document.getElementById(tblPostCodes).style.display="none";
       document.getElementById(tblPostCode).style.display="none";
    }
      if(selType==4)    //Country + State + City
    {
       document.getElementById(tblRegion).style.display="none";
       document.getElementById(tblCountry).style.display="";
       document.getElementById(tblState).style.display="";
       document.getElementById(tblCity).style.display="";
       document.getElementById(tblPostCodes).style.display="none";
       document.getElementById(tblPostCode).style.display="none";
    }
     if(selType==5)    //Country + PostCode(s)  
    {
       document.getElementById(tblRegion).style.display="none";
       document.getElementById(tblCountry).style.display="";
       document.getElementById(tblState).style.display="none";
       document.getElementById(tblCity).style.display="none";
       document.getElementById(tblPostCodes).style.display="";
       document.getElementById(tblPostCode).style.display="none";
    }
     if(selType==6)    //Country + PostCode + Radius (US/UK/CA) 
    {
       document.getElementById(tblRegion).style.display="none";
       document.getElementById(tblCountry).style.display="";
       document.getElementById(tblState).style.display="none";
       document.getElementById(tblCity).style.display="none";
       document.getElementById(tblPostCodes).style.display="none";
       document.getElementById(tblPostCode).style.display="";
    }  
}


function finalSubmitCheck(numOfTotalRoutes,RouteGeneralName) //value passed for the total number of 
{
      for(k=1;k<=numOfTotalRoutes;k++)
      {
                tagName=RouteGeneralName+k;
                //this is the checking of the whole checkbox to control the display of whole table
                chkControl="chkDsp_"+tagName;
                if(document.getElementById(chkControl).checked)
                {
                    //selected the first box, so we need to check validity of data entrance under that box
                    for(i=0;i<=1;i++)
                    {
                        //loop two times in order to confirm From to To location
                        tblName=i==0?"Frm":"To"; 
                        selTagName="routeType"+tblName+"_"+tagName; 
                        selType=document.getElementById(selTagName).value;
                        
                        tagCountry="routeCountry"+tblName+"_"+tagName; 
                        tagCity="routeCity"+tblName+"_"+tagName;
                        tagStateOther="routeOtherState"+tblName+"_"+tagName;
                        tagPostCodes="routePostCodes"+tblName+"_"+tagName;
                        tagPostCode="routePostCode"+tblName+"_"+tagName;
                        tagPostCodeDistance="routePostCodeDistance"+tblName+"_"+tagName;
                        tagState="routeState"+tblName+"_"+tagName;
                        
                        tagPostCodesRst="routePostCodesRst"+tblName+"_"+tagName;
                        tagPostCodeRst= "routePostCodeRst"+tblName+"_"+tagName; 
                        
                        country=document.getElementById(tagCountry).value;
                        state= document.getElementById(tagState).value;
                        stateOther= document.getElementById(tagStateOther).value;
                        city= document.getElementById(tagCity).value; 
                        
                        errorLoc=(i==0?"From":"To")+" location of "+RouteGeneralName+k;
                        
                        
                        if(selType>1 && country ==0)    //Country must have a valid selection not "-----------"
                        {
                            alert ("Please make selection of the country for "+errorLoc);
                            document.getElementById(tagCountry).focus(); 
                            return false;
                        }
     
                        if(selType==3)       //Country + State/Province
                        {   
                           if(state=="other" && stateOther=="")
                           {
                                
                               str="You have selected Other State option for "+errorLoc+", but you did not enter Other State name.\n If you are sure it is unnecessary, please click OK and proceed, \notherwise, please click Cancel and fill the Other State name.\n\nAre you sure the Other State name is empty?"
                               if(!confirm(str))
                               {
                                    document.getElementById(tagStateOther).focus();  
                                    return false;
                               }
                           } 
                        }
     
                         if(selType==4)    //Country + State + City 
                         {
                           if(state=="other" && stateOther=="")
                           {
                                
                               str="You have selected Other State option for "+errorLoc+", but you did not enter Other State name.\n If you are sure it is unnecessary, please click OK and proceed, \notherwise, please click Cancel and fill the Other State name.\n\nAre you sure the Other State name is empty?"
                               if(!confirm(str))
                               {
                                    document.getElementById(tagStateOther).focus();  
                                    return false;
                               }
                           } 
                           
                           if(city=="")
                           {
                               alert ("You have selected City option for "+errorLoc+", but you did not enter city name.\nPlease enter city name or make other Search Type selection.")
                               document.getElementById(tagCity).focus();
                               return false;
                           }
                         }
                         
                         if(selType==5)    //Country + PostCode(s) 
                         {
                            
                             if(document.getElementById(tagPostCodes).value==0) 
                             {
                                 alert ("You have selected country + postcodes option, but you did not enter postcodes, please enter postcodes and submit the form again.");
                                 document.getElementById(tagPostCodes).focus();
                                 return false;
                             }
                            
                            if(document.getElementById(tagPostCodesRst).innerHTML==0)
                            {
                                if(!sel_route_postcodes(tagName,i==0?1:0))
                                {
                                    document.getElementById(tagPostCodesRst).innerHTML=1; //check just once, and they submit again, no use to recheck.
                                    alert ("If you are sure the postcodes is REALLY in good format, you don't need to make change and submit the form again.")
                                    return false;
                                }
                            } 
                             
                         }
                         
                         if(selType==6)    //Country + PostCode + distance 
                         {  
                            if(document.getElementById(tagPostCodeRst).innerHTML==0)
                            {
                                if(!sel_route_postcode(tagName,i==0?1:0)  || !chk_route_distance(tagName,i==0?1:0) )
                                {
                                    document.getElementById(tagPostCodeRst).innerHTML=1; //check just once, and they submit again, no use to recheck.
                                    alert ("If you are sure the postcode is REALLY in good format, you don't need to make change and submit the form again.")
                                    return false;
                                }
                            } 
                             
                         }
                         
                    }
                } 
      }    
      
      return true;
    
}



function sel_route_country(tagName,From)
{
     //control of display type of route
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
  
    //We need to do If country + state, then populate states automatically
  
     tblName=From==1?"Frm":"To";      
     
     tagCity="routeCity"+tblName+"_"+tagName;
     tagStateOther="routeOtherState"+tblName+"_"+tagName;
     tagPostCodes="routePostCodes"+tblName+"_"+tagName;
     tagPostCode="routePostCode"+tblName+"_"+tagName;
     tagPostCodeDistance="routePostCodeDistance"+tblName+"_"+tagName;
     
     document.getElementById(tagCity).value="";
     document.getElementById(tagStateOther).value="";  
     document.getElementById(tagPostCodes).value="";  
     document.getElementById(tagPostCode).value="";  
     document.getElementById(tagPostCodeDistance).value="0"; 
     
     tagCountry="routeCountry"+tblName+"_"+tagName; 
     country=document.getElementById(tagCountry).value;
     
     selTagName="routeType"+tblName+"_"+tagName; 
     selType=document.getElementById(selTagName).value;
     
     if(selType==6 && country !="US" && country !="CA" && country !="UK")    //Anywhere in the world
     {
        alert ("We are sorry that the searching method (postcode + distance to this location)\n is only available to United States, Canada and United Kingdom at present. \nWe will add this functionality to more countries shortly. Please use other searching method.\nSorry for any inconvenience.");
        document.getElementById(tagCountry).value="US"; 
        document.getElementById(selTagName).focus(); 
        return false;
     }
    
    tagState="routeState"+tblName+"_"+tagName;
    updateStateForDifferentCountry(country,tagState,""); 
      
}

function sel_route_otherstate(tagName,From)
{
    //control of display type of route
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
  
    //We need to do is update the state selection to "other"
    
    tblName=From==1?"Frm":"To";
    tagNameState="routeState"+tblName+"_"+tagName;
    document.getElementById(tagNameState).value="other";
  
}

function sel_route_state(tagName,From)
{
    //control of display type of route
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
  
    //We need to do is update the state selection to "other"
    
    tblName=From==1?"Frm":"To";
    tagNameState="routeOtherState"+tblName+"_"+tagName;
    document.getElementById(tagNameState).value="";
}

function sel_route_postcodes(tagName,From)
{
    //control of display type of route
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
  
    //We need to do 1. check is seperated by ","; 
    //2) If the postcode format is valid
    //Added new, for each token, if US, check "-",  1) Must have only two tokens, Tok1 & Tok must be digits, and each one is valid PostCode (5 digits, so for US, no use to input xxxxx-xxxx format);
    //if UK/CA, chk each tokens, CA -> len>3, check whole ZIP, use regEx; UK-> len>4, use RegEx, finally use upper to fill;
    //If others, letters-> can not use "-" 
   
    tblName=From==1?"Frm":"To";
       
    tagCountry="routeCountry"+tblName+"_"+tagName;
    countryName=document.getElementById(tagCountry).value;
    tagPostCodes="routePostCodes"+tblName+"_"+tagName;
    postcodes=document.getElementById(tagPostCodes).value;
   
    
    tokens = postcodes.tokenize(",", " ", true);
    strPostCode="";
    strErrorPostCode="";
    for(var i=0; i<tokens.length; i++)
    {
      element=tokens[i];
      //now we need to check each token based on three possibilties
      if(countryName=="US")
      {
        //if a range, seperate by token, and check each
        subtokens=element.tokenize("-"," ",true);
        if(subtokens.length>2) //if ther are more than two "-", wrong
        {
            alert ("You have entered a wrong format of the post code ranges, please use format as xxxxx-xxxxx,\n and also please only use first part of your post code. For example, \nif your post code is 12345-1234, then please ONLY use 12345 as your postcode.");
            document.getElementById(tagPostCodes).focus();
            return false;
        }else
        {
            for(j=0;j<subtokens.length;j++)   //each token must be a valid US post
            {
                subElement=subtokens[j];
                if(!checkPostCodeValidity(subElement,"US"))
                {
                    alert ("The following US post code your entered is in wrong format. Please use valid US postcode format.\nWrong PostCode:"+subElement); 
                    document.getElementById(tagPostCodes).focus();
                    return false;
                }
            }
        }
      }else      
      if(countryName=="AU")
      {
        //if a range, seperate by token, and check each
        subtokens=element.tokenize("-"," ",true);
        if(subtokens.length>2) //if ther are more than two "-", wrong
        {
            alert ("You have entered a wrong format of the post code ranges, please use format as xxxxx-xxxxx.");
            document.getElementById(tagPostCodes).focus();
            return false;
        }else
        {
            for(j=0;j<subtokens.length;j++)   //each token must be a valid US post
            {
                subElement=subtokens[j];
                if(!checkPostCodeValidity(subElement,"AU"))
                {
                    alert ("The following Australia post code your entered is in wrong format. Please use valid Australia postcode format.\nWrong PostCode:"+subElement); 
                    document.getElementById(tagPostCodes).focus();
                    return false;
                }
            }
        }
      }else
      if(countryName=="CA")
      {
        //if canadian, then check the post Code
        if(element.indexOf("-")>0)
        {
            alert ("You can not enter a range for Canadian PostCode. If you want to save effort, please only enter outer postcode, first 3 letters, of the Canadian Postcode.");
            document.getElementById(tagPostCodes).focus();
            return false;
        }
        if(element.length>3)
        {
            //check its validity
            if(!checkPostCodeValidity(element,"CA"))
            {
               alert ("You have error entrance for Canadian PostCodes. The wrong post code entered is "+element);
               document.getElementById(tagPostCodes).focus();
               return false;
            }else
            {
                strPostCode+=(strPostCode.length>0?", ":"")+checkPostCodeValidity(element,"CA");      
            }
        }else
        {
            //check its validity
            if(!checkCanadaPartPostCodeValidity(element))
            {
               alert ("You have error entrance for part of Canadian PostCodes. The wrong partial post code entered is "+element);
               document.getElementById(tagPostCodes).focus();
               return false;
            }else
            {
                strPostCode+=(strPostCode.length>0?", ":"")+checkCanadaPartPostCodeValidity(element);      
            }
        } 
      }else
      if(countryName=="UK")
      {
          //if UK, then check the post Code
        if(element.indexOf("-")>0)
        {
            alert ("You can not enter a range for UK PostCode. If you want to save effort, please only enter outer postcode, parts before the space of the UK Postcode.");
            document.getElementById(tagPostCodes).focus();
            return false;
        }
        if(element.length>4)
        {
            //check its validity
            if(!checkPostCodeValidity(element,"UK"))
            {
               alert ("You have error entrance for UK PostCodes. The wrong post code entered is "+element);
               document.getElementById(tagPostCodes).focus();
               return false;
            }else
            {
                strPostCode+=(strPostCode.length>0?", ":"")+checkPostCodeValidity(element,"UK");      
            }
        }else
        {  
            //right now can not check validity of first part
            strPostCode+=(strPostCode.length>0?", ":"")+element;      
        }   
      }else
      {
          //for all the other countries, only need to check if range is valid
          //if a range, seperate by token, and check each
            subtokens=element.tokenize("-"," ",true);
            if(subtokens.length>2) //if ther are more than two "-", wrong
            {
                alert ("You have entered a wrong format of the post code ranges, please use format as xxxxx-xxxxx.");
                document.getElementById(tagPostCodes).focus();
                return false;
            }else
            {
                for(j=0;j<subtokens.length;j++)   //each token must be a valid US post
                {
                    subElement=subtokens[j]; 
                    if(!isPureNum(subElement) && subtokens.length>1)
                    {
                        alert ("The range setting with '-' is only valid for pure number format postcode, but one of the postcodes you just entered - "+subElement+" - is not a digital post code. \nIf your postcode are formed by characters and consists space,you can just enter outer postcode,\n part before the space, so as to save your effort in entering the post codes,\n otherwise, you have to enter postcode one by one."); 
                        document.getElementById(tagPostCodes).focus();
                        return false;
                    }
                }
            }
      }           
    }
    
    if(countryName=="CA" || countryName=="UK")
    {
        document.getElementById(tagPostCodes).value=strPostCode.toUpperCase(); 
    }
        
    return true;
}


function sel_route_postcode(tagName,From)
{
    //control of display type of route
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
  
    //We need to do If the postcode format is valid
    //Newly modified: if US -> use RegEx;
    //If UK, Len>4, user RegEx; CA, Len >3, use RegEx
    //Finally, use upper case
   
   
    tblName=From==1?"Frm":"To";
       
    tagCountry="routeCountry"+tblName+"_"+tagName;
    countryName=document.getElementById(tagCountry).value;
    tagPostCode="routePostCode"+tblName+"_"+tagName;
    postcode=document.getElementById(tagPostCode).value; 
    
    if(countryName=="US" && !checkPostCodeValidity(postcode,countryName))
    {
        alert ("The US postcode you just entered is not in good format,\n please check it again to confirm the valid US postcode format (5 digits). \nNote: Valid postcode is essential for accurate research result.");
        document.getElementById(tagPostCode).focus();
        return false; 
    }
    
    if(countryName=="UK")
    {
          if(postcode.length>4 && !checkPostCodeValidity(postcode,countryName))
        {
            alert ("The UK postcode you just entered is not in good format, \nplease check it again to confirm the valid postcode format.\nNote: Good format postcode is essential for accurate research result.");
            document.getElementById(tagPostCode).focus();
            return false; 
        }else
        {
            if(postcode.length>4)
            {                       
                document.getElementById(tagPostCode).value=checkPostCodeValidity(postcode,countryName);  
            }else
            {   
                document.getElementById(tagPostCode).value=document.getElementById(tagPostCode).value.toUpperCase();
            }
            
        }
    }
    
    if(countryName=="CA")
    {   
            if(postcode.length>3 && !checkPostCodeValidity(postcode,countryName))
            {
                alert ("The Canadian postcode you just entered is not in good format, \nplease check it again to confirm the valid postcode format.\nNote: Good format postcode is essential for accurate research result.");
                document.getElementById(tagPostCode).focus();
                return false; 
            }else
            {
                if(postcode.length>3)
                {
                    document.getElementById(tagPostCode).value=checkPostCodeValidity(postcode,countryName);  
                }else
                {
                    document.getElementById(tagPostCode).value=document.getElementById(tagPostCode).value.toUpperCase();
                }
            }     
    }
     
    return true; 
}

function chk_route_distance(tagName,From)
{
    //control of distance must be digits
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
  
    //We need to do If the number format is valid
    tblName=From==1?"Frm":"To";
    tagDistance="routePostCodeDistance"+tblName+"_"+tagName;
    distance=document.getElementById(tagDistance).value;
    if(!isNum(distance))
    {
        alert ("Please input valid distance to the center point of your entered postcode.");
        document.getElementById(tagDistance).value="";
        document.getElementById(tagDistance).focus();        
    }else
    {
        document.getElementById(tagDistance).value=removeCommas(distance);
    }
    if(distance>100)
    {
        alert ("The distance to the center point should be smaller than 100 km/mi so as to increase calculation speed. \nPlease reduce distance or use other selection options.")
        document.getElementById(tagDistance).focus();  
        return false;
    }
    return true;
}

function chkDistanceUnitKM(tagName,From)
{
    //control of dispaly of KM or MI
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
    tblName=From==1?"Frm":"To";  
    tagKM="chkrouteKM"+tblName+"_"+tagName;
    tagMI="chkrouteMI"+tblName+"_"+tagName;   
    if(document.getElementById(tagKM).checked)
    {
       document.getElementById(tagMI).checked=false; 
    }else
    {
       document.getElementById(tagMI).checked=true; 
    }
}

  function chkDistanceUnitMI(tagName,From)
{
    //control of dispaly of KM or MI
    //If From==1, this is From location, if 0, To location
    //TagName is the whole name passed to the displayRoute() function in fns_sort.php
    tblName=From==1?"Frm":"To";  
    tagKM="chkrouteKM"+tblName+"_"+tagName;
    tagMI="chkrouteMI"+tblName+"_"+tagName;   
    if(document.getElementById(tagMI).checked)
    {
       document.getElementById(tagKM).checked=false; 
    }else
    {
       document.getElementById(tagKM).checked=true; 
    }
}

   

    function  checkRouteValidityPart(tagName,From) 
    {
            tblName=From==1?"Frm":"To";
            tagRegion="routeRegion"+tblName+"_"+TagName;
            tagCountry="routeCountry"+tblName+"_"+TagName;
            tagState="routeState"+tblName+"_"+TagName;
            tagStateOther="routeOtherState"+tblName+"_"+TagName;
            tagCity="routeCity"+tblName+"_"+TagName;
            tagPostCodes="routePostCodes"+tblName+"_"+TagName;
            tagPostCodesChecked="routePostCodesRst"+tblName+"_"+TagName;
            tagPostCode="routePostCode"+tblName+"_"+TagName; 
            tagPostCodeChecked="routePostCodeRst"+tblName+"_"+TagName; 
            tagDistance="routePostCodeDistance"+tblName+"_"+TagName;
            tagKM="chkrouteKM"+tblName+"_"+TagName;  
            tagMI="chkrouteMI"+tblName+"_"+TagName;
          
            selTagName="routeType"+tblName+"_"+TagName; 
            selType=document.getElementById(selTagName).value;
   
            country=document.getElementById(tagCountry).value;
            
            if(selType==2)   //Country
            {
                 if(country=="0" || country=="")
                 {
                    alert ("You selected to search by Country, but you did not select anyone. Please make country selection.");
                    document.getElementById(tagCountry).focus();
                    return false;
                 }  
            }
   
            if(selType==3)   //Country + State/Province
            {
                 if(country=="0" || country=="")
                 {
                    alert ("You selected to search by Country, but you did not select anyone. Please make country selection.");
                    document.getElementById(tagCountry).focus();
                    return false;
                 }  
            }
            return true;
    }
    

  var xmlHttpPostCode;
  function chkRoutePostCodeInDB(tagName,From,postcode)
  {
                  tblName=From==1?"Frm":"To";
                  tagCountry="routeCountry"+tblName+"_"+tagName;
                  countryName=document.getElementById(tagCountry).value;
                  xmlHttpPostCode=GetXmlHttpObject()
                  if (xmlHttpPostCode==null)
                  {
                  alert ("Browser does not support HTTP Request")
                  return
                  }
                  if(countryName!="AU")
                  {
                      var url="/inc/ajax.php"
                      url=url+"?type=getLocStateFromZip&country="+countryName+"&postCode="+postcode;  
                      url=url+"&sid="+Math.random()
                      url=(url)   
                      xmlHttpPostCode.onreadystatechange=stateChanged
                      xmlHttpPostCode.open("GET",url,true)
                      xmlHttpPostCode.send(null)  
                  }      
          }
          
            
          function stateChanged()
          {
              if (xmlHttpPostCode.readyState==4 || xmlHttpPostCode.readyState=="complete")
              {
                  var str=xmlHttpPostCode.responseText;
                  if (str=="wrong")
                  { 
                        alert ("Sorry, we can not find the postcode your just entered in the database, if you confirm that you entered a valid postcode, you can proceed, otherwise, please enter your valid postcode again.")
                  }
              }
          }
       //-------end of Ajax PostCode
       
 
        function addCountryToSelControl(fromControl,toControl)
        {
               selectedIndex=document.getElementById(fromControl).selectedIndex;
               value=document.getElementById(fromControl).options[selectedIndex].value;
               text= document.getElementById(fromControl).options[selectedIndex].text;  
               
               len2 = document.getElementById(toControl).options.length;
               if(value=="ALL")
               {
                        for (var i = len2; i > 0; i = i - 1) {
                            document.getElementById(toControl).remove(i-1);
                        }   
               }                 
               if(value!="0")
               {
                   addOption(document.getElementById(toControl),text, value); 
               }
               
        }
        
        function  removeCountryFromSelControl(toControl)    
        {    
             selectedIndex=document.getElementById(toControl).selectedIndex; 
             if(selectedIndex>=0)
             {
                 document.getElementById(toControl).remove(selectedIndex);
             }  
        }
        
         function  removeAllCountryFromSelControl(toControl)    
        {    
             len2 = document.getElementById(toControl).options.length;
             for (var i = len2; i > 0; i = i - 1) {
                            document.getElementById(toControl).remove(i-1);
             }   
              
        }
        
        function getMultiSelValue(toControl)
        {
                    strval="";
                    for(i=0;i<document.getElementById(toControl).length;i++)
                    {
                        if(document.getElementById(toControl).options[i].value=="ALL")
                        {
                            return "ALL";
                        }else
                        {
                            if(strval.indexOf(document.getElementById(toControl).options[i].value)<0)
                            {
                                strval+=(strval.length>0?",":"")+document.getElementById(toControl).options[i].value; 
                            }
                        }   
                    }
                    return strval;   
        }
        
        function getMultiSelText(toControl)
        {
                    strval="";
                    for(i=0;i<document.getElementById(toControl).length;i++)
                    {
                        if(document.getElementById(toControl).options[i].text=="All the countries")
                        {
                            return "All the countries";
                        }else
                        {
                            if(strval.indexOf(document.getElementById(toControl).options[i].text)<0)
                            {
                              strval+=(strval.length>0?",":"")+document.getElementById(toControl).options[i].text;
                            }
                        }
                    }
                    return strval;
        }
           
            function trim(s)
            {
                return rtrim(ltrim(s));
            }

            function ltrim(s)
            {
                var l=0;
                while(l < s.length && s[l] == ' ')
                {    l++; }
                return s.substring(l, s.length);
            }

            function rtrim(s)
            {
                var r=s.length -1;
                while(r > 0 && s[r] == ' ')
                {    r-=1;    }
                return s.substring(0, r+1);
            }

 