/**
 * This javascript is very important for those pages where we need form validation.
 * Especially where there we added custom fields such resume,contacts etc
 */

//Label>name pair
var field_pairs= new Array();
//how many pairs
var len=field_pairs.length;
//get the script name
var script = ""+window.location;

//this function count how many text is typed in field1 and shows how much is remaining on field2 with respect to maxlimit
function textCounter(field1, field2, maxlimit) {
	field=document.getElementsByName(field1);
	field = field[0];
	if (field.value.length > maxlimit){ // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		alert("You exceed the max limit of " + maxlimit + " characters");
	}
	else
		$("#"+field2).html("["+(maxlimit-field.value.length)+" characters remaining]");
}

// this function get the email-id entered in str by the user and check whether it is already exists in DB or not
// it use the php script ajax_validation.php by ajax call with requested variable email_id
function email_exist(str){
	var result;
	if(script.indexOf("resume_register",0)==-1) return false; //if it is not resume_register page i.e. if it is not new resume no need to check existance of email in DB
    jQuery.ajax({
         url:    '../ajax_validation.php' 
                  + '?email_id=' 
                  + str,
         success: function(data) {
			if (data=='yes') result=true;
			else result=false;
                  },
         async:   false /*must need synchronous*/
    }); 
    return result;
}

//email validation
function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	var exist = email_exist(str);
	if (exist){
	   alert("E-mail ID already exists. Please choose different E-mail ID");
	   return false
	}
	if (str.indexOf(at)==-1){
	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert("Invalid E-mail ID")
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    alert("Invalid E-mail ID")
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    alert("Invalid E-mail ID")
	    return false
	 }

	 return true					
}

//file extension check function. @param req=whether file upload is required or not.
//If required then dont allow empty. if not required but user upload then also check extension
function checkExtension(req)
{
//validation of file extension
  var file1=document.getElementsByName('f_resume_doc[]');

	var fileName = '';

	if (file1[0]) {

		fileName = file1[0].value; // current value
	}

  // for mac/linux, else assume windows
  if (navigator.appVersion.indexOf('Mac') != -1 || navigator.appVersion.indexOf('Linux') != -1)
	var fileSplit = '/';
  else
	var fileSplit = '\\';

  var fileTypes     = new Array('.doc', '.docx', '.pdf', '.txt', '.DOC', '.DOCX', '.PDF', '.TXT'); // valid filetypes
//  var fileName      = document.getElementById('myInput').value; // current value
//  var fileName      = obj.value; // current value
  var extension     = fileName.substr(fileName.lastIndexOf('.'), fileName.length);
  var valid = 0;
  
  for(var i in fileTypes)
  {
	if(fileTypes[i] == extension)
	{
	    valid = 1;
	    break;
	    
	}
  }
  
  if(req==0 && fileName=="")//if not required and empty then return true
  {
	  //if(!confirm("No files are attached. Sure to continue?")){
		  return true;
	  //}
  }
  else if(valid != 1 )
  {
	alert("We allow only .doc, .docx, .pdf and .txt files");
	return false;
  }
}

//convert string to javascript date object let dateString is 02-24-2008 and dateSeperator is - then this func will return a JS dateobject
function getDateObject(dateString,dateSeperator)
{
	//This function return a date object after accepting 
	//a date string ans dateseparator as arguments
	var dateObjs=dateString.split(dateSeperator);
      var day = dateObjs[1];

      // Attention! Javascript consider months in the range 0 - 11
      var month = dateObjs[0] - 1;
      var year = dateObjs[2];

      // This instruction will create a date object
       var source_date = new Date(year,month,day);

      if(month != source_date.getMonth())
      {
         alert('Month is not valid!');
         return false;
      }
	
      else if(day != source_date.getDate())
      {
         alert('Day is not valid!');
         return false;
      }
	
	else if(year != source_date.getFullYear())
      {
         alert('Year is not valid!');
         return false;
      }

	return source_date;
}

//validate the form. get the form variables from DB by ajax call
function validate_form(){

// alert('test'); return false;

var i=0;
while(i<len){
	var field_pair=field_pairs[i].split(">");//get fields  names
	var obj=document.getElementsByName(""+field_pair[1]);
	if(obj[0].value==null || obj[0].value==""|| obj[0].value==0){
		if(field_pair[1]!="resume_New_Password_" && field_pair[1]!="resume_Confirm_New_Password_")
		{//password has some sepcial case so we are checking for password later and so no need to check here
			alert(field_pair[0]+" is required");
			obj[0].focus();
			return false;
		}
	}
	if(field_pair[1]=="resume_Email_"){
		if(!echeck(obj[0].value)){
			obj[0].focus();
			return false;
		}
	}
	if(field_pair[1]=="resume_New_Password_"){
		if(script.indexOf("resume_register",0)==-1){//if we are editing mode
			if(obj[0].value==null || obj[0].value==""|| obj[0].value==0);//if null then we are not willing to change pass
			else {//we are trying to change pass
				if(obj[0].value.length < 6){
					alert("Password fields must be atleast 6 charecter long");
					obj[0].focus();
					return false;
				}
			}
		}
		else
		{
			if(obj[0].value.length < 6){//we are addning new resume and new pass
				alert("Password fields must be atleast 6 charecter long");
				obj[0].focus();
				return false;
			}
		}
	}
	if(field_pair[1]=="resume_Confirm_New_Password_"){
		var field_pair1=field_pairs[i-1].split(">");//get fields  names
		var obj1=document.getElementsByName(""+field_pair1[1]);

		if(script.indexOf("resume_register",0)==-1){//if we are editing mode
			if(obj1[0].value==null || obj1[0].value==""|| obj1[0].value==0);//if null then we are not willing to change pass
			else {//we are trying to change pass
				if(obj[0].value !== obj1[0].value){
					alert(field_pair[0]+" dont match with "+field_pair1[0]);
					obj[0].focus();
					return false;
				}
			}
		}
		else{
			if(obj[0].value !== obj1[0].value){//we are not in editing mode but new resume is being inserted
				alert(field_pair[0]+" dont match with "+field_pair1[0]);
				obj[0].focus();
				return false;
			}
		}
	}
	if(field_pair[1]=="resume_Willing_to_Relocate_"){
		// place any other field validations that you require here
		// validate myradiobuttons
		var myOption = -1;
		for (k=obj.length-1; k > -1; k--) {
			if (obj[k].checked) {
				myOption = k; k = -1;
			}
		}
		if (myOption == -1) {
			alert("Are you willing to relocate? Please answer.");
			obj[0].focus();
			return false;
		}
	}
	
	i++;
}//end of while

//validation of employment history. at least one history is required
var i=1;
while(true){//first let us it is an infinite loop, as we dont know prior how many histories are entered by the user
	var company1=document.getElementsByName('h_company['+i+']');
	var title1=document.getElementsByName('h_title['+i+']');
	var st_date1=document.getElementsByName('h_start_date'+i);
	var end_date1=document.getElementsByName('h_end_date'+i);
	var resp1=document.getElementsByName('h_resp['+i+']');
	//var desc1=document.getElementsByName('h_desc['+i+']');
	
	if(title1[0]==null) {//we choose title as title is common for both employment,education and certification history
		// if we get any blank title then now further history is remaining. so we can break infinite loop.
		//alert(i+" "+st_date1[0]);
		break;
	}
	i++;
	if(i==20) break;//we cannot allow more than 20 histories so break inifite loop
	
	if(company1[0].value==null || company1[0].value==""){
		alert("You need enter at least one work history.\nIf you already Entered atleast one Company, Please remove blank Histories");
		company1[0].focus();
		return false;
	}
	else if(st_date1[0].value=="Date Format mm/dd/yyyy" || st_date1[0].value==null || st_date1[0].value==""){//from 14th march 2009 date format is not mandatory
		alert("Start Date cannot be empty when you select a company");
		st_date1[0].focus();
		return false;
	}
	else if(end_date1[0].value=="Date Format mm/dd/yyyy" || end_date1[0].value==null || end_date1[0].value==""){
		if(!confirm("Leaving the End Date blank means you are still employed.  Do you still want to leave the End Date empty?")){
			end_date1[0].focus();
			return false;
		}
	}

//changed by zahid 0n 14th march 2009. as now date validation is not required
/*	if(getDateObject(st_date1[0].value,"/") == false){
		alert("Date format not valid");
		st_date1[0].focus();
		return false;
	}
	if(end_date1[0].value!="Date Format mm/dd/yyyy" && getDateObject(end_date1[0].value,"/") == false){
		alert("Date format not valid");
		end_date1[0].focus();
		return false;
	}
	if(end_date1[0].value!="Date Format mm/dd/yyyy" && getDateObject(st_date1[0].value,"/") > getDateObject(end_date1[0].value,"/")){
		alert("Start Date must be less then End Date");
		st_date1[0].focus();
		return false;
	}
*/
	if(title1[0].value==null || title1[0].value==""){
		alert("Title cannot be empty when you select a company");
		title1[0].focus();
		return false;
	}
	else if(resp1[0].value==null || resp1[0].value==""){
		alert("Responsibilities cannot be empty when you select a company");
		resp1[0].focus();
		return false;
	}
//changed by  Zahid on 22th Feb 2009 as description is now not required
/*	else if(desc1[0].value==null || desc1[0].value==""){
		alert("Description cannot be empty when you select a company");
		desc1[0].focus();
		return false;
	}
	*/
}
//validation of education history. at least one history is required
i=1;
while(true){
	var inst1=document.getElementsByName('e_institute['+i+']');
	var title1=document.getElementsByName('e_title['+i+']');
	var type1=document.getElementsByName('e_type['+i+']');
	var year1=document.getElementsByName('e_year['+i+']');
	
	if(title1[0]==null) {
		//alert("education "+i+" "+title1[0]);
		break;
	}
	i++;
	if(i==20) break;
	
	if(inst1[0].value==null || inst1[0].value==""){
		alert("You need enter at least one education history.\nIf you already Entered atleast one, Please remove blank Histories");
		inst1[0].focus();
		return false;
	}
	else if(title1[0].value==null || title1[0].value==""){
		alert("Title cannot be empty when you select a Institute");
		title1[0].focus();
		return false;
	}
	else if(type1[0].value==null || type1[0].value==""|| type1[0].value=="0"){
		alert("Please select a degree type");
		type1[0].focus();
		return false;
	}
	else if(year1[0].value==null || year1[0].value==""){
		alert("Please select a year");
		year1[0].focus();
		return false;
	}
}
//validation of certification history this not mandatory
i=1;
while(true){
	var title1=document.getElementsByName('c_title['+i+']');
	var year1=document.getElementsByName('c_year['+i+']');
	if(title1[0]==null) {
		//alert(i+" "+title1[0]);
		break;
	}
	i++;
	if(i==20) break;
	
	else if(title1[0].value==null || title1[0].value==""){
		if(!confirm("Title is empty, sure to leave it empty")){
		title1[0].focus();
		return false;
		}
	}
	else if(year1[0].value==null || year1[0].value==""){
		if(!confirm("Award Year is empty, sure to leave it empty")){
		year1[0].focus();
		return false;
		}
	}
}
	return true;
}//end of function validate_form

/*********************************   Resume Form Validation ***************************************/
function validate_resume(){

	var formName = 'resume_form';

	for (var i = 0; i < document.forms[formName].length; i++) {

		var element = document.forms[formName].elements[i];

		if (!element.value) continue;

		var validationType = element.getAttribute('validationType');

		if (validationType == 'date') {

			if (element.value == 'Date Format mm/dd/yyyy') {

				// ok
			}
			else if (!isDate(element.value)) {
			
				// alert("Incorrect date format!");
				element.focus();
				return false;
			}
		}
	}

	//general form validation

	$("#msg").bind("ajaxSend", function(){
	   $(this).html('<b>Please wait while validating the form</b>');
	 }).bind("ajaxComplete", function(){
	   $(this).html('<b>Validation complete</b>');
	 });
	
	var value=false;

	if(len==0)	{
/*	$.get("../ajax_validation.php", { table: "resume" },
	function(data){
		field_pairs=data.split("~");//get fields  names
		len=field_pairs.length-1;
//alert(data+"\n"+"total="+len);
	validate_form();
	});
*/
	    jQuery.ajax({
		   url:    '../ajax_validation.php' 
				+ '?table=resume',/*get all the fields from resume table*/
		   success: function(data) {
					field_pairs=data.split("~");//get fields  names /*Fields are taken in pair. pair are in form Label>name and pair are in pair1~pair2 etc*/
					len=field_pairs.length-1;
					var value=validate_form();
				},
		   async:   false//dont need asynchronus
	    }); 
	}//end of if
	else {
		value=validate_form();
	}
	 return value;

}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

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
}

function elementIsDate (element, isRequired) {

	// var element = document.getElementById('elementId');
	var elementValue = element.value;

	if (!elementValue) {

		if (isRequired) {

			element.focus();
			return false;
		}
	}
	else {

		if (isDate(elementValue) == false) {
			element.focus()
			return false;
		}
	}

	return true;
}
