// Validate saleslead 
// Created on: 05-06-2009

   function checkallfields()
   {
      var why = "";

      why += checkquestions();
      why += checklastname();
      why += CheckNRIC();
      why += checkmaritalstatus();
      why += checkgender();
      why += checkbuildingno();
      why += checkstreetname();
      why += checkpostalcode();
      why += checkphoneno();
      why += checkincomepermonth();
      why += checkoccupation()
      why += checkemail();
      why += ValidateForm();

      if (why != "")
      {  
        alert(why);
        return false;
      }
      formatfieldsbeforesubmit();
      document.frmsaleslead.submit();
      return true;
   }


   function formatfieldsbeforesubmit()
   {
    /*
       Description:
       Preload all the needed hidden fields before submit to server

    */
      var outputMessage="";
 
      document.frmsaleslead.lead_source.value="Campaigns"
      document.frmsaleslead.contestresults.value= getquestions();
      outputmessage = padZeros(document.frmsaleslead.ddlDD.value,2) + "/" + padZeros(document.frmsaleslead.ddlMM.value,2) + "/" + padZeros(document.frmsaleslead.ddlYY.value,4);
      document.frmsaleslead.dateofbirth.value = outputmessage;
      document.frmsaleslead.description.value= outputmessage;
      //alert (document.frmsaleslead.contestresults.value);
   }

   function checklastname()
   {
    /*
       Description:
       Last name must be mandatory

    */

      var error = "";
      if (frmsaleslead.last_name.value == "")
      {
         error = "Please enter name\n";
      }
      return error;
   }

   function CheckNRIC()
   {
    /*
       Description:
       NRIC is mandatory and must follow the format

    */
      var error = "";
      var y=document.frmsaleslead.nricno.value;
      if (!(y.length==9))
      {
         error = "Invalid NRIC No\n"
      }
      else if (!(y.charAt(0)>="a" && y.charAt(0)<="z"||y.charAt(0)>="A" && y.charAt(0)<="Z"))
      {
         error= "Invalid NRIC No\n"
       }
      else if (!(y.charAt(8)>="a" && y.charAt(8)<="z"||y.charAt(8)>="A" && y.charAt(8)<="Z"))
      {
         error= "Invalid NRIC No\n"
      }
      else
      {
         error=""
      }
      return error;
   }

   function checkmaritalstatus()
   {
    /*
       Description:
       Marital Status must be selected

    */
      var error = "";
      var y=document.frmsaleslead.maritalstatus.value;
     if (y == "--None--"||y == "")
      {
         error = "Please select Marital Status\n";
      }
      return error;
   }

   function checkgender()
   {
    /*
       Description:
       Gender must be selected

    */
      var error = "";
      var y=document.frmsaleslead.gender.value;
     if (y == "--None--"||y == "")
      {
         error = "Please select Gender\n";
      }
      return error;
   }

   function checkbuildingno()
   {
    /*
       Description:
       Building No / House No must be input

    */
      var error = "";
      var y=frmsaleslead.buildingno.value;
      if (y == "")
      {
         error = "Please enter Building / House No\n";
      }
      return error;
   }

   function checkstreetname()
   {
    /*
       Description:
       Street Name must be input

    */
      var error = "";
      var y=frmsaleslead.streetname.value;
      if (y == "")
      {
         error = "Please enter Street Name\n";
      }
      return error;
   }

   function checkpostalcode()
   {
    /*
       Description:
       a. Postal Code must be input
       b. Postal Code must be 6 digit-numeric field

    */
      var error = "";
      var y=frmsaleslead.postalcode.value;
      if (y == "")
      {
         error = "Please enter Postal Code\n";
      }

      else if (!(y.length == 6))
      {
         error = "Invalid Postal Code\n";
      }

      else if ((isNaN(y)))
      {
         error = "Invalid Postal Code\n";
      }

      return error;
   }

   function checkphoneno()
   {
    /*
       Description:
       a. Either Mobile or Phone No must be input
       b. Input must be numeric and length must not be less then 8 digit long

    */
      var error = "";
      var y=frmsaleslead.mobile.value;
      var z=frmsaleslead.phone.value;
      
      if (y=="" && z=="")
      {
         error = "Please enter Mobile or Home No\n";
      }

      if ((error==""))
      {
         if (y.length > 0)
         {
            if (y.length < 8)
               error = "Invalid Mobile No\n";
         }
         else if ((isNaN(y)))
         {
             error = "Invalid Mobile No\n";
         }
      }

      if ((error==""))
      {
         if (z.length > 0)
         {
            if (z.length < 8)
               error = "Invalid Home No\n";
         }
         else if ((isNaN(z)))
         {
             error = "Invalid Home No\n";
         }
      }

      return error;
   }

   function checkincomepermonth()
   {
    /*
       Description:
       Income per month must be selected

    */

      var error = "";
      var y=document.frmsaleslead.incomepermonth.value;
     if (y == "--None--"||y == "")
      {
         error = "Please select Income Per Month\n";
      }
      return error;
   }

   function checkoccupation()
   {
    /*
       Description:
       Occupation must be selected

    */
      var error = "";
      var y=document.frmsaleslead.occupation.value;
     if (y == "--None--"||y == "")
      {
         error = "Please select Occupation\n";
      }
      return error;
   }



   function checkemail()
   {
    /*
       Description:
       a. Email is an optional field
       b. If email is input, must follow email format

    */
      var error = "";
      var y=document.frmsaleslead.email;
      if (y.value.length>0)
      {
         error = validateemail(y);
      }
      return error;
   }


   function getQuerystring(key, default_)
   {
     if (default_==null) default_=""; 
     key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
     var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
     var qs = regex.exec(window.location.href);
     if(qs == null)
       return default_;
     else
       return qs[1];
    }


//The following functions validate phone no

function validatephone()
{
   var Phone=document.frmsaleslead.phone
   if (checkInternationalPhone(Phone.value)==false)
   {
      return "please enter a valid phone no.\n"
   }
   return ""
}
 

// 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 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 trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
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){
var bracket=3
strPhone=trim(strPhone)
if(strPhone.indexOf("+")>1) return false
if(strPhone.indexOf("-")!=-1)bracket=bracket+1
if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
var brchr=strPhone.indexOf("(")
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

// -- End of the phone no validation


// -- Start of Email validation

function validateemail(email){
	var emailID=email
	
	if ((emailID.value==null)||(emailID.value=="")){
		return "please enter email id\n"
	}
	if (echeck(emailID.value)==false){
		return "please enter valid email id\n"
	}
	return ""
 }

function echeck(str) {

   var at="@"
   var dot="."
   var lat=str.indexOf(at)
   var lstr=str.length
   var ldot=str.indexOf(dot)
   if (str.indexOf(at)==-1){
      return false
   }

   if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
      return false
   }

   if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
      return false
   }

   if (str.indexOf(at,(lat+1))!=-1){
      return false
   }

   if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
      return false
   }

   if (str.indexOf(dot,(lat+2))==-1){
     return false
   }
		
   if (str.indexOf(" ")!=-1){
     return false
   }

   return true					
}

// -- End of Email validation


   function clearallfields()
   {
      document.frmsaleslead.last_name.value="";
      document.frmsaleslead.title.value="";
      document.frmsaleslead.company.value="";
      document.frmsaleslead.email.value="";
      document.frmsaleslead.phone.value="";
      document.frmsaleslead.country.value="";
      document.frmsaleslead.state.value="";
      document.frmsaleslead.city.value="";
      document.frmsaleslead.description.value="";

   }

   function checkquestions()
   {
    /*
       Description:
       Concatinate all the answer into string
       For each question, the answer check boxes are assign with number, 
       first check box assign to 1, second check box assign 2, third check box assign 4, etc.
       there are five answers to 5 question, so all the answer are concatinate into one field.
       E.g If user answers all the questions with all the first check boxes, the result will be '11111'.
       E.g. If user answers all the questions with all the second check boxes, the result will be '22222'

    */
    
      var q1=0,q2=0,q3=0,q4=0,q5=0;
      var error = "";
      var i=0;
      var finalAnswer="";

      //Handle Question 1
      for (i=0;i<document.frmsaleslead.Q1.length;i++){
         if (document.frmsaleslead.Q1[i].checked==true){
            q1=i+1;
         }
      }

      if (!(parseInt(q1)>0)){
         error = "Question 1 must be answered\n";
         return error;
      }

      //Handle Question 2
      for (i=0;i<document.frmsaleslead.Q2.length;i++){
         if (document.frmsaleslead.Q2[i].checked==true){
            q2=i+1;
         }
      }

      if (!(parseInt(q2)>0)){
         error = "Question 2 must be answered\n";
         return error;
      }

      //Handle Question 3
      for (i=0;i<document.frmsaleslead.Q3.length;i++){
         if (document.frmsaleslead.Q3[i].checked==true){
            q3=i+1;
         }
      }

      if (!(parseInt(q3)>0)){
         error = "Question 3 must be answered\n";
         return error;
      }


      //Handle Question 4
      for (i=0;i<document.frmsaleslead.Q4.length;i++){
         if (document.frmsaleslead.Q4[i].checked==true){
            q4=i+1;
         }
      }

      if (!(parseInt(q4)>0)){
         error = "Question 4 must be answered\n";
         return error;
      }

      //Handle Question 5
      for (i=0;i<document.frmsaleslead.Q5.length;i++){
         if (document.frmsaleslead.Q5[i].checked==true){
            q5=i+1;
         }
      }

      if (!(parseInt(q5)>0)){
         error = "Question 5 must be answered\n";
         return error;
      }

      //finalAnswer = q1.toString()+q2.toString()+q3.toString()+q4.toString()+q5.toString();
      //document.frmsaleslead.contestResults.value= finalAnswer;
      return error;
   }

   function getquestions()
   {
    /*
       Description:
       Update the answer field before submit to server

    */
    
      var q1=0,q2=0,q3=0,q4=0,q5=0;
      var error = "";
      var i=0;
      var finalAnswer="";

      //Handle Question 1
      for (i=0;i<document.frmsaleslead.Q1.length;i++){
         if (document.frmsaleslead.Q1[i].checked==true){
            q1=i+1;
         }
      }

      //Handle Question 2
      for (i=0;i<document.frmsaleslead.Q2.length;i++){
         if (document.frmsaleslead.Q2[i].checked==true){
            q2=i+1;
         }
      }

      //Handle Question 3
      for (i=0;i<document.frmsaleslead.Q3.length;i++){
         if (document.frmsaleslead.Q3[i].checked==true){
            q3=i+1;
         }
      }


      //Handle Question 4
      for (i=0;i<document.frmsaleslead.Q4.length;i++){
         if (document.frmsaleslead.Q4[i].checked==true){
            q4=i+1;
         }
      }

      //Handle Question 5
      for (i=0;i<document.frmsaleslead.Q5.length;i++){
         if (document.frmsaleslead.Q5[i].checked==true){
            q5=i+1;
         }
      }


      finalAnswer = q1.toString()+q2.toString()+q3.toString()+q4.toString()+q5.toString();
      return finalAnswer;
   }


// The following codes will validate the date of input


var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function ValidateForm(){
    /*
       Description:
       a. Must be an valid date format in MM/DD/YYYY

    */
        var error ="";
	var dt="01/01/1800";

        if (!((isNaN(document.frmsaleslead.ddlDD.value)) && (isNaN(document.frmsaleslead.ddlMM.value)) && (isNaN(document.frmsaleslead.ddlYY.value))))
        {
           if (document.frmsaleslead.ddlDD.value>0 && document.frmsaleslead.ddlMM.value>0 && document.frmsaleslead.ddlYY.value>0)
           { 
              dt = padZeros(document.frmsaleslead.ddlMM.value,2) + "/" 
                   + padZeros(document.frmsaleslead.ddlDD.value,2) + "/" 
                   + padZeros(document.frmsaleslead.ddlYY.value,4)
           }
        }


	if (isDate(dt)==false){
		error = "Invalid Date Selected"
		return error
	}

    return error;
 }


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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

//-- End of Date Validation

function padZeros(theNumber, max) {
    /*
       Description:
       Pad leading zero to the field

    */

    var numStr = String(theNumber);

    while ( numStr.length < max) {
        numStr = '0' + numStr;
    }

    return numStr;
}


