/**
  *Filename  :validate.js
  *Purpose :This page holds commonly used javascript validations in the application.
  *Tables:none  
**/


/**checks for valid email address**/ 
 
function CheckEmail(stremail)
{ 
  var err;
  var str=stremail;
  var ValidChars = "0123456789-_.";
  var validdom   = "0123456789";
  var illegalchars="#$!%^&*();:<>+/\?|";
  var i;
  var c;
  var l;
  var n;
  var at="@";
  var dot=".";
  var lat=str.indexOf(at);
  var lstr=str.length;
  var ldot=str.indexOf(dot);
  
    i=0;
   c = str.charAt(i); 
  
   if (ValidChars.indexOf(c) !=-1) 
   { return false; }
 
    //commented on 29 08 09
    // l=str.indexOf(dot)+1;  
    // n=str.charAt(l);
  
   if(n=="")
   { return false; }
   
   for(i=l;i<lstr;i++)
   {
     l=str.charAt(i); 
		 
	 if (validdom.indexOf(l)!=-1) 
	 { return false; }
   }
   
   	clen=illegalchars.length;
 	for(j=0;j<clen;j++)
	{
		c=illegalchars.charAt(j);
		if(str.indexOf(c)>0)
		{
		 return false;	
		}
	}
   
  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 ;        
}



//----------------------------------Start AJAX code-----------------------------
/******************************************************************************/
//function name :createRequestObject
/******************************************************************************/    
   function createRequestObject(){//function start 
      var xmlhttp=false;      
      try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");  }
      catch(e){//first catch start brace
          try{
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }catch(e){//start sec catch
              xmlhttp=false;
          }    //end sec catch                    
      }//first catch end brace  
      if(!xmlhttp && typeof XMLHttpRequest !='undefined'){
        xmlhttp=new XMLHttpRequest();      
      }return xmlhttp;  
    }//function end 
//----------------------------------End AJAX code-----------------------------




/**clears the values in combo box**/ 
function clearCombo(cmbid){
	   
      var x=document.getElementById(cmbid);
      var i;
      for (i=x.length;i>0;i--){
        x.remove(i);
      }
  }
 
/**initialises a combo box to index position 0 **/   
function initCombo(incmb)
{
  document.getElementById(incmb).selectedIndex=0;
}


/** used to trim spaces**/ 
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}


//ajax function to obtain all the states based on the chosen country      
  function getStates(cmbcountry,cmbstate)
  {
    var xmlHttp; 
    var j = document.getElementById(cmbcountry).selectedIndex;
    var sel_country = document.getElementById(cmbcountry).options[j].value;
    var cmbstate=document.getElementById(cmbstate).id;
    
    if(sel_country > 0)
    {
      var strUrl= "cmblocation_code.php?country_id="+sel_country;
      
       xmlHttp=createRequestObject();   
       xmlHttp.open("GET",strUrl,true);       
       xmlHttp.onreadystatechange=function() {
              if(xmlHttp.readyState==4) {         
                      if(xmlHttp.status==200)
                      {
                          clearCombo(cmbstate);   
                          //alert(xmlHttp.responseText);                    
                          eval("var response=("+xmlHttp.responseText+")"); 
                           for(i=0;i < response.states.list.length; i++) {
                                var y=document.createElement('option');
                                y.text=response.states.list[i].state;
                                y.value=response.states.list[i].id; 
                                var x=document.getElementById(cmbstate);
                                if(y.value>0)       
                                    try{
                                     x.add(y,null); // standards compliant                                            
                                     } catch(ex){ x.add(y); // IE only
                                     } 
                            }
                            clearCombo('cmbsuburb');       
                                       
                      }
              }
      }
      xmlHttp.send(null); 
    }
  }
  
  //ajax function to obtain all the suburbs based on the chosen state   
  function getSubUrb(cmbstate,cmbsuburb)
  {
    var xmlHttp; 
    var j = document.getElementById(cmbstate).selectedIndex;
    var sel_state = document.getElementById(cmbstate).options[j].value;
    var cmbsuburb=document.getElementById(cmbsuburb).id;
    clearCombo(cmbsuburb);   
    if(sel_state > 0)
    {
       var strUrl= "cmblocation_code.php?sub_sid="+sel_state;
       xmlHttp=createRequestObject();    
       xmlHttp.open("GET",strUrl,true);       
       xmlHttp.onreadystatechange=function() {
              if(xmlHttp.readyState==4) {         
                      if(xmlHttp.status==200)
                      {
                          //alert(xmlHttp.responseText);                    
                          eval("var response=("+xmlHttp.responseText+")"); 
                           for(var i=0;i < response.SubUrb.list.length; i++)
                            {
                                //create a combo box for suburbs
                                var y=document.createElement('option');
                                y.text=response.SubUrb.list[i].suburb;
                                y.value=response.SubUrb.list[i].subid; 
                                var a=document.getElementById(cmbsuburb);
                                if(y.value>0)   //for suburbs    
                                    try{
                                     a.add(y,null); // standards compliant                                            
                                     } catch(ex){ a.add(y); // IE only
                                     } 
                            }
                      }
                   }
                }
      xmlHttp.send(null); 
    }
  }
 
 
//ajax function to obtain all the postcodes based on the chosen state   
   function getPostcode(cmbsuburb,cmbpostcode)
   {
      var xmlHttp; 
      var j = document.getElementById(cmbsuburb).selectedIndex;
      var sel_suburb = document.getElementById(cmbsuburb).options[j].value;
      var cmbpostcode=document.getElementById(cmbpostcode).id;
      clearCombo(cmbpostcode);
      if(sel_suburb > 0)
      {
         var strUrl= "cmblocation_code.php?post_subid="+sel_suburb;
         xmlHttp=createRequestObject();    
         xmlHttp.open("GET",strUrl,true);       
         xmlHttp.onreadystatechange=function() {
                if(xmlHttp.readyState==4) {         
                        if(xmlHttp.status==200)
                        {
                            //alert(xmlHttp.responseText);                    
                            eval("var response=("+xmlHttp.responseText+")"); 
                             for(var k=0;k < response.Postcode.list.length; k++) 
                             {
                                  //create a combo box for postcodes
                                var z=document.createElement('option');
                                z.text=response.Postcode.list[k].postcode;
                                z.value=response.Postcode.list[k].postid; 
                                var b=document.getElementById(cmbpostcode);
                                if(z.value>0)       //for postcodes
                                    try{
                                     b.add(z,null); // standards compliant                                            
                                     } catch(ex){ b.add(z); // IE only
                                     }     
                            }   
                         }
                      }
                  }
        xmlHttp.send(null); 
    }
  }
  
 //ajax function to obtain all the services based on the chosen industry    
  function getServices(cmbindustry,cmbservices,num)
  {
    var xmlHttp; 
    var objflg;
    var j = document.getElementById(cmbindustry).selectedIndex;
    var sel_industry = document.getElementById(cmbindustry).options[j].value;
    var cmbservice=document.getElementById(cmbservices).id;
    clearCombo(cmbservice);
    if(num==1){  objflg=1; }  //service 
    else { objflg=0; }    //job
    if(sel_industry > 0)
    {
      var strUrl= "cmblocation_code.php?industry_id="+sel_industry+"&objflg="+objflg;
       xmlHttp=createRequestObject();    
       xmlHttp.open("GET",strUrl,true);       
       xmlHttp.onreadystatechange=function() {
              if(xmlHttp.readyState==4) {         
                      if(xmlHttp.status==200)
                      {
                          //alert(xmlHttp.responseText);                    
                          eval("var response=("+xmlHttp.responseText+")"); 
                           for(i=0;i < response.services.list.length; i++) {
                                var y=document.createElement('option');
                                y.text=response.services.list[i].service;
                                y.value=response.services.list[i].id; 
                                var x=document.getElementById(cmbservices);
                                if(y.value>=0)       
                                    try{
                                     x.add(y,null); // standards compliant                                            
                                     } catch(ex){ x.add(y); // IE only
                                     } 
                            }       
                                       
                      }
              }
      }
      xmlHttp.send(null); 
    }
  }
  
   
  
  
  
/********File validation********/
function FileValidation(Id)
{
    var msg="";
    var strFile;
    strFile=document.getElementById(Id).value; 
    var sss=new Array();
    sss=strFile.split(".");
    l=sss.length;
    strS = sss[l-1];
    if(!(strS.toLowerCase()=="doc" || strS.toLowerCase()=="pdf"))
    {    
        msg=file_type_errmsg;
    }
  return msg;
}
 
  
//Function to compare if given two dates are valid  
function compareDates(date1,date2,seperator){
  var arrD1= new Array();
  arrD1=date1.split(seperator); //will be split as day, month ,year
  var arrD2= new Array();
  arrD2=date2.split(seperator);
  
  //Set the two dates
  var startingDate=new Date(arrD1[2], arrD1[1]-1, arrD1[0]); //Month is 0-11 in JavaScript
  var endingDate=new Date(arrD2[2], arrD2[1]-1, arrD2[0]);
  //alert(startingDate+" ---- "+endingDate);
  //Set 1 day in milliseconds
  var one_day=1000*60*60*24

//Calculate difference btw the two dates, and convert to days
 var diff=(endingDate.getTime()-startingDate.getTime())/(one_day);
 if(diff<0){
  return 0; //dates are invalid, if negative diff
 }else{
  return 1; //dates are valid
 }

}


//Function to compare start date with current date(start date cannot be less than current date)
function CmpStartCurrentDate(date1,date2,seperator){
  //alert(date1+"    ********    "+date2);
  var arrD1= new Array();
  arrD1=date1.split(seperator); //will be split as day, month ,year
  var arrD2= new Array();
  arrD2=date2.split(seperator);
  //Set the two dates
  var startingDate=new Date(arrD1[2], arrD1[1]-1, arrD1[0]); //Month is 0-11 in JavaScript
  var currDate=new Date(arrD2[2], arrD2[1]-1, arrD2[0]);
  //Set 1 day in milliseconds
  var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
 var diff=(currDate.getTime()-startingDate.getTime())/(one_day);
 if(diff<=0){
  return 0; 
 }else{
  return 1; 
 }

}




//Function to toggle the divs (display block/none)
function 	toggleSection(id) {
			var ni = document.getElementById(id);
			if (ni.style.display === 'none'){
				ni.style.display = 'block';
			}	else{
				ni.style.display = 'none';
			}
} // end toggleSection


//function to check if days are selected
function chkDays(id){
     var objDM=document.getElementsByName(id);
     var len=objDM.length;
     for(var i=0; i < len; i++){
        if(objDM[i].checked==true)
        {
            return true;
        }
     }
     return false;
}


//Function to check for valid phone number 
function PhoneValidation(field)
{
var valid = "1234567890+()/- "
var flag=true;
var field=document.getElementById(field);

if(field.value!="")
{
		var len=field.value.length;
		var chk=field.value;
		for(i=0;i<len;i++)
		{
			x = chk.charAt(i);
			if(valid.indexOf(x) == -1)
			{
       window.scroll(0,0);
       field.focus();
			 flag= false;
			 break;
			}
		}
		if(!flag)
		return false;
}
} 

//Function to check for special characters 
function chkSpecial(ctrlname)
{  
  var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'"
  field=document.getElementById(ctrlname);
  var chk=trim(field.value);
  var len=chk.length;
  for(i=0;i<len;i++)
  {
    x = chk.charAt(i)
    if(valid.indexOf(x) == -1)
    {  
      field.focus();
      return false;
    }
  }
  return true;
}

//Function to check for special characters in password
function chkSpclPassword(ctrlname)
{  
  var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  field=document.getElementById(ctrlname);
  var chk=trim(field.value);
  var len=chk.length;
  for(i=0;i<len;i++)
  {
    x = chk.charAt(i)
    if(valid.indexOf(x) == -1)
    {  
      field.focus();
      return false;
    }
  }
  return true;
}

//This function is called to increase the height of the div with id maincontainer defined in userHeader.php
function IncDivHeight()
{
   document.getElementById("maincontainer").style.height='auto';
}


//This function allows only numbers to be allowed for the event onkeypress 
function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}

//This function allows to strip commas from a given number
function stripCommas(numString) {
    var re = /,/g;
    return numString.replace(re,"");
}

//This function allows to get the required number format
function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
 f[0] = '0';
 }
 if (!f[1]) {
 f[1] = '';
 }
 if (f[1].length < b) {
 g = f[1];
 for (i=f[1].length + 1; i <= b; i++) {
 g += '0';
 }
 f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
 h = f[0];
 f[0] = '';
 for(j = 3; j < h.length; j+=3) {
 i = h.slice(h.length - j, h.length - j + 3);
 f[0] = d + i + f[0] + '';
 }
 j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
 f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 f[0] + c + f[1];
 
 return f[0] + c + f[1];
}
 

