// Javascript Form Handling For Mail Form
// Author: Nirav Patel
// Company: EMI Music UK
// Date: 2006-10-31
// Version: 1.3
// Copyright:  2006 (c) EMI Music UK & Ireland        
//<!--
  // Browser Detection

        var wc = (document.getElementById);
        var ns = (document.layers);
        var ie = (document.all);
        
        var isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
        var NS4 = (document.layers) ? true : false;
        var IEmac = ((document.all)&&(isMac)) ? true : false; IE4plus = (document.all) ? true : false;
        var IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
        var IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
        var ver4 = (NS4 || IE4plus) ? true : false;
        var NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;                       
        
        // Handles multiple onload events
        var gSafeOnload = new Array(); 
        // Handles multiple onload events
        var gSafeOnSubmit = new Array();            
        

      function FetchElement(id) 
      {
          if (ie) 
          {
            return document.all[id];            
            
          } 
          else if (ns) 
          {
          
            return document.layers[id];
          } 
          else if (wc) 
          {
            return document.getElementById(id);           
          }
      }
         
      function getArgs()
      {
          var args = new Object();
          var query = location.search.substring(1);
          var pairs = query.split("&");
          
          for (var i = 0; i < pairs.length; i++)
          {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue;
            var argname = pairs[i].substring(0,pos);
            var value = pairs[i].substring(pos+1);
            args[argname] = unescape(value)
          }
          return args;
      }          



     function HideElement(id) 
     { 
        var Element = FetchElement(id);
      if (Element)
      {
          Element.style.display = "none";
       }
     }

     function ShowElement(id) 
     {
       var Element = FetchElement(id);
      if (Element)
      {
          Element.style.display = "";
       }
     }

     function FlipFlopElement(id,id2) 
     {
       var Element = FetchElement(id);
      var Element2 = FetchElement(id2);
      if (Element.style.display == "")
      {
           Element.style.display = "none";
         Element2.value = "";
       }
      else
      {
          Element.style.display = "";
         Element2.value = "on";
       }  
     }     


   function getCheckedValue(radioObj) 
   {
     if(!radioObj) return "";
     
     var radioLength = radioObj.length;
     if(radioLength == undefined)
       if(radioObj.checked) return radioObj.value;
     else
       return "";

     for(var i = 0; i < radioLength; i++) 
     {
       if(radioObj[i].checked) return radioObj[i].value;
     }
     return "";
   }
     
     
      var args = new Array();
      args = getArgs();
      

/* Hide SMS text boxes that are no valid */

    function DisplaySMSAlerts()
    {
      var smsid;
      var country = FetchElement("COUNTRY");       
      if (country[country.selectedIndex].value == "United Kingdom")
      {
        // Shows boxes
         for (var i = 0; i < list_cheetah_list_id.length; i++)
         {            
           smsid = FetchElement("sub"+list_cheetah_list_id[i]);
         //alert("smsid ("+ list_cheetah_list_id[i] +"):"+smsid );
          if (smsid)
           {         
             smsid.style.display = "";  
          }               
         }                    
      }      
      else
      {
        sub2 = FetchElement("sub2");
        sub2.disable = true;
          //alert("sub2"+sub2);
      
        // Hides Boxes
         for (var i = 0; i < list_cheetah_list_id.length; i++)
         {            
           smsid = FetchElement("sub"+list_cheetah_list_id[i]);
          if (smsid)
           {         
             smsid.style.display = "none"; 
            
          }              
         }      
      }
    }      
     
     
      function SafeOnload()
      {
       
       for (var i=0;i<gSafeOnload.length;i++)
         if (gSafeOnload[i]() == false)
         {
           return false;
         }
      }
     
      function SafeAddOnload(f) 
      {  
        // Call the following with your function as the argument SafeAddOnload(yourfunctioname);
        if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload  
        {
          window.onload = SafeOnload;
          gSafeOnload[gSafeOnload.length] = f;
        }
        else if  (window.onload)
        {
          if (window.onload != SafeOnload)
          {
            gSafeOnload[0] = window.onload;
            window.onload = SafeOnload;
          }
          gSafeOnload[gSafeOnload.length] = f;
        }
        else
          window.onload = f;
      }
  
  
      function SafeOnSubmit()
      {
       
       for (var i=0;i<gSafeOnSubmit.length;i++)
         if (gSafeOnSubmit[i]() == false)
         {
           return false;
         }
      }
     
      function SafeAddOnSubmit(f) 
      {  
        // Call the following with your function as the argument SafeAddOnload(yourfunctioname);
        if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload  
        {
          window.onsubmit = SafeOnSubmit;
          gSafeOnSubmit[gSafeOnSubmit.length] = f;
        }
        else if  (window.onsubmit)
        {
          if (window.onsubmit != SafeOnSubmit)
          {
            gSafeOnSubmit[0] = window.onsubmit;
            window.onsubmit = SafeOnSubmit;
          }        
          gSafeOnSubmit[gSafeOnSubmit.length] = f;
        }
        else
        { 
          window.onsubmit = f;
        }
      }
  
         
      // Hooks into the  onload        
      SafeAddOnload(AddCheetahValidation);              
      
      function AddCheetahValidation()
      {
       // Adds hook to form submission        
         if (!document.signupform)
         {
             return CheetahmailValidateSignup(document.forms[0]);
         }         
         else
         {
           return CheetahmailValidateSignup(document.signupform);
         }      
         return true;
      }                   

      
      // Edit this function to handle form validation
      function CheetahmailValidateSignup(form)
      {
        if (args.RCODE)
        {
          if (args.RCODE.length > 0)
           {
           form.RCODE.value = args.RCODE;
          }           
        }
        else if(args.rcode)
        {
          if (args.rcode.length > 0)
           {
           form.RCODE.value = args.rcode;
          }              
        }      
        
        // If no RCODE set default it to the url
        if (form.RCODE.value.length == 0)
        {             
          form.RCODE.value = document.location.href;          
          form.RCODE.value.toLowerCase().replace(/^http:\/\//,"").substr(0,21);      
        }

         
        // Extra Fly text bits
      //  if (form.COUNTRY.value == "United Kingdom" && form.MOBILE_NO.value.indexOf("447") == 0)  
                      
        if (form.COUNTRY[form.COUNTRY.selectedIndex].value == "United Kingdom" && form.MOBILE_NO.value.indexOf("447") == 0)  
        {          
          // Handle Flytext Paramters passing
          var seperator = "&";
          if (form.re.value.length > 0)
          {                 

            /*  GENDER  */
            var gender = "";
            for (var i=0;i<form.GENDER.length;i++)
            {
              if (form.GENDER[i].checked)
              {
                  gender = encodeURI(form.GENDER[i].value);
              }
            }
            
            /*  SUB  */
            var sub = "";
			
			/* Adds it for one single item sub2 */
			var lsub2 = FetchElement("sub2");
			if (lsub2 && lsub2!="")
			{
			  if (lsub2.checked)
			  {
                sub = "&sub20=" + encodeURI(lsub2.value);
			  }
			}
			
            var count = 0;
            for (var i=0;i<form.sub2.length;i++)
            {
			  if (i == 0 && sub.length > 0)
			  {
			    sub ="";
			  }
			  
              if (form.sub2[i].checked)
              {
                  sub += "&sub2"+count+"=" + encodeURI(form.sub2[i].value);
                  count++;
              }
            }
            
            if  (form.re.value.indexOf("?") == -1)
            { 
               seperator = "?";
            }
            else
            {
              // Just incase the form reposts and we dont want to double up on variables
              form.re.value = form.re.value.slice(0,form.re.value.indexOf("?"));
              seperator = "?";
            }                       
            // May need to encode this 
            
            form.re.value += seperator + "RCODE=" + encodeURI(form.RCODE.value) + "&FNAME=" + encodeURI(form.FNAME.value) + "&LNAME=" + encodeURI(form.LNAME.value) + "&GENDER=" + gender + "&MOBILE_NO=" + encodeURI(form.MOBILE_NO.value) + sub;              
            
            if (args.debug=="true")
            {
              alert("re:"+form.re.value);
            }            
          }
          else
          {
          // Just incase the form reposts and we dont want to double up on variables
              form.re.value = form.re.value.slice(0,form.re.value.indexOf("?")) +"?RCODE=" + form.RCODE.value;
          }          
        }     

        return true;
      }
     
  
   //<!--
  // Declaring required variables
  var digits = "0123456789";
  // non-digit characters which are allowed in phone numbers
  var phoneNumberDelimiters = "()- ";
  // characters which are allowed in international phone numbers
  // (a leading + is OK)
  var validWorldPhoneChars = phoneNumberDelimiters;
  // Minimum no of digits in an international phone no.
  var minDigitsInIPhoneNumber = 10;

  function checkEmail(emailAddr) 
  {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailAddr.value)){
    return (true)
    }
    //alert("Invalid E-mail Address! Please re-enter.")
    return (false)
  }
  
  function isInteger(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 stripCharsInBag(s, bag)
  {
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
  }

  function checkInternationalPhone(strPhone)
  {
    s=stripCharsInBag(strPhone,validWorldPhoneChars);
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
  }    
 
 
 function ValidateForm(){
   var errormessage = FetchElement("errormessage");
   errormessage.innerHTML = ""; // Clear old error messages
   var errors = 0;
   
   
   var FNAME = FetchElement("FNAME");
   var LNAME = FetchElement("LNAME");

   if (!FNAME || FNAME=="" || FNAME.value.length == 0)
   {
      errormessage.innerHTML += "<br/>" + "Please enter a first name";
     errors++;
   }
   
   if (!LNAME || LNAME=="" || LNAME.value.length == 0)
   {
     errormessage.innerHTML += "<br/>" + "Please enter a last name";
     errors++;
   }

   var GENDER = "";
//   var iGENDER = FetchElement("GENDER");
   //alert("iGENDER"+getCheckedValue(iGENDER));
  // if (!iGENDER)
   //{
     GENDER = getCheckedValue(document.forms[0].elements['GENDER']);
   //}
   //else
   //{
     
   //  GENDER = iGENDER.value;
   //}
 
  //if ((!GENDER || GENDER=="" || (GENDER[0].checked == false && GENDER[1].checked == false)))
   if (!GENDER || GENDER=="")
   {
     //alert("GENDER.value="+GENDER.value);
     errormessage.innerHTML += "<br/>" + "Please select your gender";
     errors++;
   }

   var POSTCODE = FetchElement("POSTCODE");
   
   if (!POSTCODE || POSTCODE=="" || POSTCODE.value.length == 0)
   {
      errormessage.innerHTML += "<br/>" + "Please enter your postcode/zipcode";
     errors++;
   }

   var BIRTH_DATE_0 = FetchElement("BIRTH_DATE.0");
   
   var BIRTH_DATE_1 = FetchElement("BIRTH_DATE.1");
   
   var BIRTH_DATE_2 = FetchElement("BIRTH_DATE.2");
   
   if (!BIRTH_DATE_1 || BIRTH_DATE_1=="" || BIRTH_DATE_1.value.length == 0 || 
       !BIRTH_DATE_2 || BIRTH_DATE_2=="" || BIRTH_DATE_2.value.length == 0 || 
       !BIRTH_DATE_0 || BIRTH_DATE_0=="" || BIRTH_DATE_0.value.length == 0 || 
       !isInteger(BIRTH_DATE_0.value) || !isInteger(BIRTH_DATE_1.value) || !isInteger(BIRTH_DATE_2.value)
   )
   {
      errormessage.innerHTML += "<br/>" + "Please enter your date of birth";
      errors++;
   }

   //var Phone=document.frmSurvey.MOBILE_NO;
   //var country =document.frmSurvey.COUNTRY;

   
   var country =FetchElement("COUNTRY");
   
   
   if (!country || country[country.selectedIndex].value=="" || country[country.selectedIndex].value.length == 0)
   {
     errormessage.innerHTML += "<br/>" + "Please enter your country";
     errors++;
   }
   
   
   var email = FetchElement("email");
   
   if (!email || email=="" || email.value.length == 0 || !checkEmail(email))
   {
     errormessage.innerHTML += "<br/>" + "Please a valid email address";
     errors++;
   }
   
   
  
   // Only validate uk numbers
   if (country[country.selectedIndex].value == "United Kingdom")
   {
  
     var Phone=FetchElement("MOBILE_NO");
     
     
/*
  // IF a required feild
   if ((Phone.value!=null) && (Phone.value=="")){
      alert("Please Enter your Phone Number")
      Phone.focus()
      return false
   }
   */
   
    if (Phone && Phone!="" && Phone.value!="" && Phone.value.length > 0)
    {
      // Removes anything that isn't a number before trying to validate it
      Phone.value = Phone.value.replace(/[^0-9]/g, "");
      
     if (checkInternationalPhone(Phone.value)==false){      
      //alert("Please Enter a Valid Mobile Number With International Prefix");    
      errormessage.innerHTML += "<br/>" + "Please enter a valid mobile number with an international prefix";
      errors++;      
      
      Phone.focus();
      return false;
     }
   
       if (Phone.value.substr(0,2) != "44")
     {
      // alert("Valid Mobile Numbers With International Prefix, For UK Prefix eg: 44");
       errormessage.innerHTML += "<br/>" + "Please enter a valid mobile number With International Prefix, For UK Prefix eg: 44";
       errors++;
       Phone.focus();
       return false;     
     }
     if (Phone.value.substr(2,1) != "7")
     {
       //alert("Valid UK Mobile Numbers start with a 7 after the International code eg: 447");
       errormessage.innerHTML += "<br/>" + "Please enter a valid mobile number.<br/>UK mobile numbers start with a 7 after the International code eg: 447";
       errors++;
       Phone.focus();
      return false;
     }
    }   
   }
     
 // If errors stop and say so
   if (errors > 0)
   {
     return false;
   } 
      
   
   AddCheetahValidation();
   return true
 }
 


  
 //alert("Finished Loading");  
//-->

