String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function populateISDcodes(){

	//document.getElementById('appTypeLabel').style.display = 'none'; //hiding the application type selction from user at the start 
	//document.getElementById('appType').style.display = 'none';
	
	//create bst country codes
	bstcodes();
	
	if(Get_Cookie("currentpage")!="dayview.php"){
 		var compUrl="/tc/APIFS/GetComponentServlet?employerId=" + accountId;
    	var ajaxCore=new CoreAjax(compUrl, 'GET', true, handleStateChange, 'True');
    	ajaxCore.doReq(null);
       

		var compUrl="/tc/APIFS/GetPhoneModelServlet?employerId=" + accountId;
    	new Ajax.Autocompleter("phoneModel", "phone_choices", compUrl,{minChars: '0', afterUpdateElement: showAppType});
	}
    
	 
}


function handleStateChange(resp)
{
	var component = resp.getElementsByTagName('component');
    var len = component.length;
    var i = 0;
    while(i<len)
    {
    	var str = component[i].firstChild.nodeValue;
        document.form1.component.options[i+1] = new Option (str, str);
        i++;
	}
	
}

//var tempresp='<response>  <application name="Mobile Timesheeting" path="/devices/mobibizgps.jad" />  <application name="Continuous Tracking" path="/devices/tcstorm.jad" /></response>';

function handleSubmitResponse(resp)
{
	var downlink="";
	var respxml = resp.getElementsByTagName('application');
	for (var iNode = 0; iNode < respxml.length; iNode++) {
		var application = respxml.item(iNode);	
		var name=application.attributes.getNamedItem('name').value;
		var path=application.attributes.getNamedItem('path').value;
		var currenturl="http://"+location.host;
		path = currenturl+path;
		downlink = downlink + name+': '+ path+"<br/>";
	}
	
	//alert(path);
	
 if(resp != null) {
		var str = '<h3 ><font color="#990000"><strong>Thank You for downloading MobiBiz.</strong> </font></h3>';
		str +='<p><font color="#990000">The following applications are ready for download: </font></p>';
		str +='<br/><p><strong>'+name+': '+ path+'</strong></p><br/>';
		str +='<p>Please use the above link in your blackberry browser to initiate download. An email will also be sent to you with the same link.<br/></p>';
		str +='<p>For setup instructions, please refer to the following link:<br/>';
		str +='<strong><a href="http://mobibizlive.co.uk/timesheet/FAQ.html">http://mobibizlive.co.uk/timesheet/FAQ.html</a></strong><br/>';
		str +='If you have any additional questions, please mail us at <a href="info@kailaz.com">info@kailaz.com</a> <br/>';
		str +='Also, we have a forum with lots of information and discussions around MobiBiz. <br/>';
		str +='<a href="http://groups.google.com/group/mobibiz">http://groups.google.com/group/mobibiz</a></p>';
		document.getElementById("result").innerHTML = str;	
	} else {
		document.getElementById("result").innerHTML = '<font color="#990000">Device Not Supported for selected applications</font>'; 
	}
}


function ValidateEmail(){
	var emailID=document.form1.email
	var str = emailID.value
	if ((emailID.value==null)||(emailID.value=="")){
		alert("Please Enter your Email ID")
		emailID.focus()
		return false
	}
	if (echeck(emailID.value)==false){
		emailID.select()
		emailID.focus()
		return false
	}else{
	if (checkEmailforPrivate(str) == false)
	{
		emailID.select()
		emailID.focus()
		return false	
	}	
	else{
			document.getElementById("results1").innerHTML = ""
			CheckForEmailAvailability(str)
		}
	}
	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];
	var text = "We are not accepting the public domain !";
		switch (domain)	
		{
/*			case 'gmail':
				alert(text)
				return false
				break
			
			case 'yahoo':
				alert(text)
				return false
				break
			
			case 'msn':
				alert(text)
				return false
				break
			
			case 'indiatimes':
				alert(text)
				return false
				break
			
			case 'in':
				alert(text)
				return false
				break
			
			case 'live':
				alert(text)
				return false
				break
			
			case 'rediff':
				alert(text)
				return false
				break
				
			case 'hotmail':
				alert(text)
				return false
				break		
			
			case 'zapak':
				alert(text)
				return false
				break		*/	
		} 
	return true;
}

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){
		   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					
	}

var accountId = '';	
var mob='';
var xmlbody1='';
function showAppType()
{
	var fName= '';
	var lName= '';
	var temp = document.form1.name.value;
	var n = temp.split(" ");
	if (n.length > 1){
		fName = n[0];
		lNmae = n[1];
	}else{
		fName = n[0];
	}
	mob = document.form1.isdcodes.value + document.form1.phone.value;
	
	
	// here we are getting the components selected by the user. 
	var str = document.form1.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+"'  />"
		}
	}
	//for account creation
	 var xmlbody = "<?xml version='1.0' ?>"+
	   			"<employer xmlns='urn:mobibiz:tc:api:v1' login='"+
	   			document.form1.email.value+"' password =''"+ 
	   			" companyName=' "+document.form1.companyName.value+"' website='' >"+
	   			"<address>"+
	   				"<addressLine1></addressLine1>"+
	   				"<addressLine2></addressLine2>"+
	   				"<city></city>"+
	   				"<postcode></postcode>"+
	  				"<country></country>"+
	   				"<state></state>"+
	   				"<timeZone>"+document.form1.timeZone.value+"</timeZone>"+
	   			"</address>"+
	   			"<primaryContact name ='"+document.form1.name.value+
	   			"' phone = '"+mob+"' email='"+document.form1.email.value+"'/>"+
	   			comp+"</employer>";  //comp here to add the component in the employer xml
	
	//for employee creation
	var state = 'ACTIVATED';
  	var val = document.form1.phoneModel.value
  	var dev_make = ''
  	var dev_model = '' 
  	if(val != ''){
  		var n = val.split(':');
  		dev_make = n[0].trim()
  		dev_model = n[1].trim()	
  	}
  	xmlbody1= " firstName='"+fName+"' lastName='"+lName+"' state='DEACTIVATED' "+
  				" optIn='true' mobilePhone='"+mob+"' operator='OTHER' "+
  				" isSupervisor='false' payrollNumber='' "+
 				" userName='"+document.form1.email.value+"' password='' deviceMake='"+dev_make+
 				"' deviceModel='"+dev_model+
 				"' includeHomeTravel='true'  />";
	
	//new employee creation is finished in the getAccountId() function after creating accountId below
	
	
	var posturl = "/tc/APIFS/V1/employers";
    var ajaxPost=new CoreAjax(posturl,'POST', true, getAccountId, 'True');
    top.document.getElementById("hideme2").style.display = "block";
    if(ajaxPost.doReq("request="+xmlbody+"&username=user")){
       //	kz_alert("updated successfully!");
	   
	  
    }
	
	if (accountId == ''){
		alert("creation of account has failed!!!");
		return false;
	}
	
	
	
	// for getting valid application type for the account
	
//        var ajaxCore=new CoreAjax(appUrl, 'GET', false, populateApplicationType);
//        top.document.getElementById("hideme2").style.display = "block";
//        if(ajaxCore.doReq(null))
//        	alert("update successfully");
//        else
//        	alert("update failed");
	
	//document.getElementById('appTypeLabel').style.display = 'block'; //hiding the application type selction from user at the start 
	//document.getElementById('appType').style.display = 'block';
	
	
}

function populateApplicationType(resp){
	var type = resp.getElementsByTagName('type');
	var id = resp.getElementsByTagName('id');
	var j=1;
	for (var i= 0; i<type.length; i++)	{		
		document.forms1.appType.options[j] = new option(type[i].firstChild.nodeValue, id[i].firstChild.nodeValue);
		j++;
	}	
}
 
function getAccountId(resp){
	accountId = resp.getElementsByTagName("accountId")[0].firstChild.nodeValue;
	
	xmlbody1="<?xml version='1.0' ?><employee xmlns='urn:mobibiz:tc:api:v1' employerId='"+accountId+"' " + xmlbody1;
  				
	//create employee
	var posturl = "/tc/APIFS/V1/employee";
    var ajaxPost=new CoreAjax(posturl,'POST',true,null,'True');
    top.document.getElementById("hideme2").style.display = "block";
	
    if(ajaxPost.doReq("request="+xmlbody1+"&username=user&accountId="+accountId)){
    	//kz_alert("updated sucessfully!");       
    }else{
    	alert("update failed");
    }
	top.document.getElementById("hideme2").style.display = "none";	
}

// this method is called when the user click on the submit button
function validateAccount(frm)
{

	//with (frm)
	//	{
			user = 'guest';
			pass = 'guest';
			var date = new Date();
			date.setTime(date.getTime()+(365*24*60*60*1000));
			var expires = "; expires="+date.toGMTString(); 
			document.cookie = "username="+user+"; path=/" +expires;
			document.cookie = "password="+pass+"; path=/" +expires;
			
			var name = document.form1.name.value
			var companyName = document.form1.companyName.value
			var email = document.form1.email.value
			var isdcodes = document.form1.isdcodes.value
			var phone = document.form1.phone.value
			var timeZone = document.form1.timeZone.value
			var phoneModel = document.form1.phoneModel.value
			var component = document.form1.component.options[document.form1.component.selectedIndex];
			
			/*
			if (validate_required(name, "Name must be filled out!")==false)
			{
			   name.focus();return false;
	  		}
			if (validate_required(companyName, "Company Name must be filled out!")==false)
			{
			   companyName.focus();return false;
	  		}
	  		if (validate_required(email,"email must be filled out !")==false)
			{
				email.focus();return false;
			}
			if (validate_required(isdcodes,"ISD code must be filled out!")==false)
			{
				isdcodes.focus();return false;
			}
			if (validate_required(phone,"phone must be filled out!")==false)
			{
				phone.focus();return false;
			}
			if (validate_required(timeZone,"Time Zone must be filled out!")==false)
			{
				timeZone.focus();return false;
			}
			if (validate_required(phoneModel,"phone model must be filled out!")==false)
			{
				phoneModel.focus();return false;
			}
		
			if (validate_required(component,"Application Type must be filled out!")==false)
			{
				component.focus();return false;
			}
				*/		
		
		var appName = new Date().getTime();
		
		var posturl = "/tc/APIFS/buildapplication?accountId="+accountId+"&input=compType="+component.value+",phoneNum="+mob+",appName="+appName;
	    
	    var ajaxPost=new CoreAjax(posturl,'POST',true,handleSubmitResponse);
	    kz_alert("accountId="+accountId+"&input=compType="+component.value+",phoneNum="+mob+",appName="+appName);
	    //document.getElementById("loadingMsg").style.display = "block";
	    
	    kz_alert(phoneModel.value+" "+component.value);
	    
			  
	    if(ajaxPost.doReq(null)){
	       	kz_alert("updated successfully!"); 			
		}else
	       	alert("update failed");
	    
	  
		//return true;				
	//}
	
	
    
}
function validate_required(field, alerttxt)
{
    with (field)
	{
		var val = value.trim();
		var flag = false
		if (val == null || val == "")
	    {
	    	alert(alerttxt);  
	    	field.focus();
	    	return false;
	    }
	   	return true
   }
}

function detect(){
	//Detect IE5.5+
	version=0;
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		temp=navigator.appVersion.split("MSIE")
		version=parseFloat(temp[1])
	}
			
	if (version>=5.5){
	} //NON IE browser will return 0				
	else
		alert("Please use a different browser. \nTimeCollection works on Internet Explorer versions 5.5 or newer.")
			
}
