String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

var accountId=Get_Cookie("accountId");

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					
	}

function validate_required(field, alerttxt)
{
   with (field)
	{
		var val = value.trim();
		var flag = false
		if (field == document.form1.password)
		{
			var len = val.length 
			for (var i = 0; i < len; i++)
			{
				var res = val.charAt(i);
				if (res == parseFloat(res))
					flag = true
			}
			if (len < 8 || flag == false){
				alert('password must be of minimum 8 characters and must be contain atleast one numeric value !')
				document.form1.password.value = ""
				field.focus();
				return false;
			}			
		}		
		if (val == null || val == "")
	    {
	    	alert(alerttxt);  
	    	field.focus();
	    	return false;
	    }
	   	return true
   }
}

//validate the email for not providing the public email
function checkEmailforPrivate(str)
{	
	var company = str.substring(str.indexOf('@')+1, str.lastIndexOf('.'))
	var domain = company.split(".")[0];
		switch (domain)	
		{
	/*		case 'gmail':
				return false
				break
			
			case 'yahoo':
				return false
				break
			
			case 'msn':
				return false
				break
			
			case 'indiatimes':
				return false
				break
			
			case 'in':
				return false
				break
			
			case 'live':
				return false
				break
			
			case 'rediff':
				return false
				break
				
			case 'hotmail':
				return false
				break		
			
			case 'zapak':
				return false
				break			*/
		} 
	return true;
}
//validate the confirm password that match the password
function validate_pass ()
{
	if(document.form1.password.value != document.form1.c_password.value)
	{
		alert("The two entered passwords do not match!");
		document.form1.password.value = "";
		document.form1.c_password.value = "";
		document.form1.password.focus();
		return false;
	}
}

function ValidateEmail(){
	var emailID=document.form1.email
	var str = emailID.value
	if ((emailID.value==null)||(emailID.value=="")){
		document.getElementById("results1").innerHTML = '<font color="#990000">Please enter valid email !</font>';
		return false
	}
	if (echeck(emailID.value)==false){
		document.getElementById("results1").innerHTML = '<font color="#990000">Invalid E-mail Address</font>';
		return false
	}else{
	if (checkEmailforPrivate(str) == false)
	{
		document.getElementById("results1").innerHTML = '<font color="#990000">We do not accept email addresses in the public domain !</font>';
		return false	
	}	
	else{
			document.getElementById("results1").innerHTML = ""
			CheckForEmailAvailability(str);
		}
	}
	return true
 }


//validate_form  function
function validate_form(frm)
{
	with (frm)
	{
		if(!document.form1.accept.checked){
				alert("Please read the Terms & Conditions and check the Accept checkbox");
				return false; 
		}
		
		if (validate_required(email, "Email must be filled out!")==false)
		{
		   email.focus();return false;
  		}
		if (validate_required(username, "User Name must be filled out!")==false)
		{
		   username.focus();return false;
  		}
  		if (validate_required(password,"password must be filled out and must be of minimum 8 character and contain at least one numeric value!")==false)
		{
			password.focus();return false;
		}
		if (validate_required(c_password,"Confirm Password must be filled out!")==false)
		{
			c_password.focus();return false;
		}
		
		var str = component
		var len = str.options.length
		var comp = ""
		for (i = 0; i < len;i++)
		{
			if (str.options[i].selected)
			{
				text = str.options[i].value
				comp = comp+"<component name = '"+text+"'  />"
			}
		}
		 
		 var xmlbody = "<?xml version='1.0' ?>"+
	    			"<employer xmlns='urn:mobibiz:tc:api:v1' login='"+
	    			username.value+"' password ='"+password.value+"'"+ 
	    			" companyName=' "+c_name.value+"' website='"+website.value+
	    			"' >"+
	    			"<address>"+
	    				"<addressLine1>"+addressline1.value+"</addressLine1>"+
	    				"<addressLine2>"+addressline2.value+"</addressLine2>"+
	    				"<city>"+city.value+"</city>"+
	    				"<postcode>"+postcode.value+"</postcode>"+
	    				"<country>"+country.value+"</country>"+
	    				"<state>"+state.value+"</state>"+
	    				"<timeZone>"+tz.value+"</timeZone>"+
	    			"</address>"+
	    			"<primaryContact name ='"+f_name.value.trim()+" "+m_name.value.trim()+" "+l_name.value.trim()+
	    			"' phone = '"+
	    			phone.value+"' email='"+email.value+"'/>"+
	    			comp+"</employer>"
			
		var posturl = "/tc/APIFS/V1/employers?";
    	var ajaxPost=new CoreAjax(posturl,'POST',true,null,'True');
    	if(ajaxPost.doReq("request="+xmlbody)){
        	kz_alert("updated successfully!");
			var date = new Date();
		
			date.setTime(date.getTime()+(365*24*60*60*1000));
			var expires = "; expires="+date.toGMTString(); 
			document.cookie = "username="+username.value+"; path=/" +expires;
			document.cookie = "password="+password.value+"; path=/" +expires;
			document.cookie = "newemp=1; path=/" +expires;	


			setcurrentpage("control/create_updateEmployee.php");
			
			var myNumber=0			
			setTimeout('function () { myNumber++;}',1000);
			
			location.replace("main.php");
			location.href="main.php";
			//		/console/main.php
			
		}else{
         	alert("update failed");
        	var date = new Date();
			date.setTime(date.getTime());
			var expires = "; expires="+date.toGMTString(); 
			document.cookie = "username=; path=/" +expires;
			document.cookie = "password=; path=/" +expires;
		}
        return true;				
	}
}


// the following are used to check the valid phone no.
// 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);
}


//this function is used to validate the valid phone number
function ValidatePhone(){
	var Phone=document.form1.phone
	
	if ((Phone.value==null)||(Phone.value=="")){
		document.getElementById("resultspn").innerHTML = '<font color="#990000">Contact number cannot be empty !</font>';
		return false
	}
	if (checkInternationalPhone(Phone.value)==false){
		document.getElementById("resultspn").innerHTML = '<font color="#990000">Invalid phone number !</font>';
		Phone.value=""
		return false
	}
	document.getElementById("resultspn").innerHTML = ""
	return true
 }


function hello()
{
	var str = document.form1.component
	var len = str.options.length
	for (i = 0; i < len;i++)
	{
		if (str.options[i].selected)
		{
			text = str.options[i].value
			alert(text)
		}
	}
}

function validate_username(){
	
	var str = document.form1.username.value
	str.trim()
	if (str == null || str == "")
	{
		document.getElementById("results").innerHTML = '<font color="#990000">Username cannot be empty !</font>';
		return false
	}else{
		document.getElementById("results").innerHTML = ""
		CheckForUsernameAvailability(str)
		//return false		
		}
}

function ValidateFirstName(){
	
	var str = document.form1.f_name.value
	str.trim()
	if (str == null || str == "")
	{
		document.getElementById("resultsfn").innerHTML = '<font color="#990000">First Name cannot be empty !</font>';
		return false
	}else{
		document.getElementById("resultsfn").innerHTML = ""
	}
}

function ValidateLastName(){
	
	var str = document.form1.l_name.value
	str.trim()
	if (str == null || str == "")
	{
		document.getElementById("resultsln").innerHTML = '<font color="#990000">Last Name cannot be empty !</font>';
		return false
	}else{
		document.getElementById("resultsln").innerHTML = ""
	}
}

function ValidateCompanyName(){
	
	var str = document.form1.c_name.value
	str.trim()
	if (str == null || str == "")
	{
		document.getElementById("resultscn").innerHTML = '<font color="#990000">Company Name cannot be empty !</font>';
		return false
	}else{
		document.getElementById("resultscn").innerHTML = ""
	}
}

function ValidateCountry(){
	
	var str = document.form1.country.value
	str.trim()
	if (str == null || str == "")
	{
		document.getElementById("resultscc").innerHTML = '<font color="#990000">Country cannot be empty !</font>';
		return false
	}else{
		document.getElementById("resultscc").innerHTML = ""
	}
}

function checkEmpPhone1(){
	var Phone1=document.form1.isdcodes;
	var Phone2 = document.form1.phone;	
	
	if ((Phone1.value==null)||(Phone1.value=="")||(Phone2.value==null)||(Phone2.value=="")){
		document.getElementById("results").innerHTML = '<font color="#990000">Contact number cannot be empty !</font>';
		return false
	}	
	
	//check for valid numeric strings
	var valphone = IsNumeric(Phone2.value)
	if(valphone==false){
		document.getElementById("results").innerHTML = '<font color="#990000">Invalid phone number !</font>';
		
		return false	
	}
	
	var Phone = Phone1.value + Phone2.value;
	if (checkInternationalPhone(Phone)==false){
		document.getElementById("results").innerHTML = '<font color="#990000">Invalid phone number !</font>';
		Phone2=""
		return false
	}	
	document.getElementById("results").innerHTML = ""
	CheckForExistingPhone(Phone)
	//return true
}
function checkEmpPhone(){
	var Phone=document.form1.m_phone			
	if ((Phone.value==null)||(Phone.value=="")){
		document.getElementById("results").innerHTML = '<font color="#990000">Contact number cannot be empty !</font>';
		return false
	}
	
	//check for valid numeric strings
	var valphone = IsNumeric(Phone)
	if(valphone==false){
		document.getElementById("results").innerHTML = '<font color="#990000">Invalid phone number !</font>';
		return false	
	}
	
	
	if (checkInternationalPhone(Phone.value)==false){
		document.getElementById("results").innerHTML = '<font color="#990000">Invalid phone number !</font>';
		Phone.value=""
		return false
	}
	document.getElementById("results").innerHTML = ""
	CheckForExistingPhone(Phone.value)
	//return true
}

//  check for valid numeric strings
function IsNumeric(strString){
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

function checkEmpUsername(){
	
	var str = document.form1.username.value
	str.trim()
	if (str == null || str == "")
	{
		document.getElementById("results1").innerHTML = '<font color="#990000">Username cannot be empty !</font>';
		document.form1.username.focus()
		return false
	}else{
		document.getElementById("results1").innerHTML = ""
		CheckForEmpUsernameAvailability(str)
		//return false		
		}
}
// the following function is used to update employee   
function updateEmployee(frm)
{
	with(frm)
	{
		if (validate_required(m_phone, "Phone must be filled out!")==false)
		{
		   m_phone.focus();return false;
  		}
  		var state = 'DEACTIVATED'
  		if (empState.value == 'ACTIVATED')
  			state = 'ACTIVATED'
  		var val = phoneModel.value
  		var dev_make = ''
  		var dev_model = '' 
  		if(val != ''){
  			var n = val.split(':');
  			dev_make = n[0].trim()
  			dev_model = n[1].trim()	
  		}
  		
  		var xmlbody= "<?xml version='1.0' ?>"+
  					"<employee xmlns='urn:mobibiz:tc:api:v1' employerId='"+employerId.value+"' "+
  					" firstName='"+f_name.value+"' lastName='"+l_name.value+"' state='"+state+"' "+
  					" optIn='"+optIn.checked+"' mobilePhone='"+m_phone.value+"' operator='"+operator.value+"' "+
  					" isSupervisor='"+supervisor.checked+"' payrollNumber='"+badgenumber.value+"' "+
 					" deviceMake='"+dev_make+"' deviceModel='"+dev_model+
 					"' includeHomeTravel='"+includeHomeTravel.checked+"'  />";
//  		alert("hi")
  		if(document.form1.edit.value.trim() == 'Edit'){
  			var posturl = "/tc/APIFS/GetUpdateSpecificEmployee?";
    		var ajaxPost=new CoreAjax(posturl,'POST',true,null);
//    		alert(xmlbody)
    		if(ajaxPost.doReq("request="+xmlbody+"&employeeId="+document.form2.id.value)){
        		kz_alert("updated successfully!");       
    		}else{
         		alert("update failed");
        	}
        	return true;					
		}
		if(document.form1.edit.value.trim() == 'Add'){
			//alert("hello")
			var posturl = "/tc/APIFS/V1/employee?";
    		var ajaxPost=new CoreAjax(posturl,'POST',true,null);
    		if(ajaxPost.doReq("request="+xmlbody)){
        		kz_alert("updated sucessfully!");       
    		}else{
         		alert("update failed");
        	}
        	return true;
		}	
	}
}

//this method is invoked after clicking the add employeelink 
function setToAdd()
{
	accountId=Get_Cookie("accountId");
	document.form1.edit.value="      Add      "
	alert("Complete form below and click Add");
	document.form2.id.value = ""
	document.form1.reset();
	document.form1.employerId.value = accountId;
	
	document.getElementById("f2").style.display="block";
	
}

//this function is used to validate the forget passwod page 
function validate_forget_password(frm)
{
	with(frm)
	{
		if (validate_required(password,"Password must be filled out!")==false)
		{
			password.focus();return false;
		}
		if (validate_required(c_password,"Confirm Password must be filled out!")==false)
		{
			c_password.focus();return false;
		}
		var xmlbody = '<?xml version="1.0" ?>'+
	    			'<employer xmlns="urn:mobibiz:tc:api:v1" password ="'+password.value+'" >'+
	    			'</employer>';
		
		var posturl = "/tc/APIFS/ForgetPasswordServlet?";
		
		var srchString = unescape(location.search.substring(1, location.search.length));		
		if (srchString.length > 0) {
			posturl = "/tc/APIFS/SetResetPasswordServlet?"+srchString;		
		} else{		
			accountId=Get_Cookie("accountId");		
		}
		var ajaxPost=new CoreAjax(posturl,'POST',true,null,'True');
		if(ajaxPost.doReq("request="+xmlbody+"&employerId="+accountId)){
			kz_alert("updated sucessfully!"); 
			alert("Thank you. Password was updated sucessfully!");
			setTimeout('window.location = "../login.php"',1);
			location.replace("../login.php");
			location.href="../login.php";	
		}else
			alert("update failed");
        return true;
		
	}
}

//this function is used to validate the set/reset password page
function validate_setRest_password(frm)
{
	with(frm)
	{
		if (validate_required(previous_password, "Old password must be filled out") == false)
		{
			previous_password.focus();return false;
		}
		if (validate_required(password,"New password must be filled out!")==false)
		{
			password.focus();return false;
		}
		if (validate_required(c_password,"Confirm New Password must be filled out!")==false)
		{
			c_password.focus();return false;
		}
		
		var xmlbody = "<?xml version='1.0' ?>"+
	    			"<employer xmlns='urn:mobibiz:tc:api:v1' password ='"+password.value+"' >"+
	    			"</employer>"
			
		var posturl = "/tc/APIFS/SetResetPasswordServlet?";
		//var posturl = "/tc/TimeCollection/servlet/VerifyAccount?";
		
    	var ajaxPost=new CoreAjax(posturl,'POST',true,null);
		accountId=Get_Cookie("accountId");
		if(ajaxPost.doReq("request="+xmlbody+"&employerId="+accountId))
        	kz_alert("updated sucessfully!");       
    	else
         	alert("update failed");
        
        return true;	
			
	}
}

