// Get the HTTP Object
function getHTTPObject(){
	if (window.ActiveXObject) 
		return new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest) 
		return new XMLHttpRequest();
	else {
		alert("Your browser does not support AJAX.");
		return null;
	}
}

//Get Query String
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

//And another job to the application form on apply.php
function addJob() {
	if ($("#add_job").parent().parent().prev().hasClass("j1")) {
		var count = '2';
	} else if ($("#add_job").parent().parent().prev().hasClass("j2")) {
		var count = '3';
	} else {
		alert("You can only submit three work experiences.");	
	}
	if (count=='2' || count=='3') {
		$("#add_job").parent().parent().before(
			"<tr class='j"+count+"'><td>Job Title<span class='style1'>*</span></td><td><input type='text' class='job req' name='title"+count+"' /></td></tr>" +
            "<tr class='j"+count+"'><td>Company<span class='style1'>*</span></td><td><input type='text' class='job req' name='company"+count+"' /></td></tr>" +
            "<tr class='j"+count+"'><td>City<span class='style1'>*</span></td><td><input type='text' class='job req' name='city"+count+"' /></td></tr>" +
            "<tr class='j"+count+"'><td>Country<span class='style1'>*</span></td><td><input type='text' class='job req' name='country"+count+"' /></td></tr>" +
			"<tr class='j"+count+"'><td>Start Date<span class='style1'>*</span></td><td><select name='j_dateStartMo"+count+"' id='cj_dateStartMo"+count+"' tabindex='8' class='input req'><option value='' selected='selected'>Month</option><option value='Jan'>Jan</option><option value='Feb'>Feb</option><option value='Mar'>Mar</option><option value='Apr'>Apr</option><option value='May'>May</option><option value='Jun'>Jun</option><option value='Jul'>Jul</option><option value='Aug'>Aug</option><option value='Sep'>Sep</option><option value='Oct'>Oct</option><option value='Nov'>Nov</option><option value='Dec'>Dec</option></select>&nbsp;<select name='j_dateStartYr"+count+"' id='cj_dateStartYr"+count+"' class='input req'><option value='' selected='selected'>Year</option><option value='2010'>2010</option><option value='2009'>2009</option><option value='2008'>2008</option><option value='2007'>2007</option><option value='2006'>2006</option><option value='2005'>2005</option><option value='2004'>2004</option><option value='2003'>2003</option><option value='2002'>2002</option><option value='2001'>2001</option><option value='2000'>2000</option><option value='1999'>1999</option><option value='1998'>1998</option><option value='1997'>1997</option><option value='1996'>1996</option><option value='1995'>1995</option><option value='1994'>1994</option><option value='1993'>1993</option><option value='1992'>1992</option><option value='1991'>1991</option><option value='1990'>1990</option></select></td></tr>" +
            "<tr class='j"+count+"'><td>End Date<span class='style1'>*</span></td><td><select name='j_dateEndMo"+count+"' id='cj_dateEndMo"+count+"' tabindex='8' class='input req'><option value='' selected='selected'>Month</option><option value='Jan'>Jan</option><option value='Feb'>Feb</option><option value='Mar'>Mar</option><option value='Apr'>Apr</option><option value='May'>May</option><option value='Jun'>Jun</option><option value='Jul'>Jul</option><option value='Aug'>Aug</option><option value='Sep'>Sep</option><option value='Oct'>Oct</option><option value='Nov'>Nov</option><option value='Dec'>Dec</option></select>&nbsp;<select name='j_dateEndYr"+count+"' id='cj_dateEndYr"+count+"' class='input req'><option value='' selected='selected'>Year</option><option value='2010'>2010</option><option value='2009'>2009</option><option value='2008'>2008</option><option value='2007'>2007</option><option value='2006'>2006</option><option value='2005'>2005</option><option value='2004'>2004</option><option value='2003'>2003</option><option value='2002'>2002</option><option value='2001'>2001</option><option value='2000'>2000</option><option value='1999'>1999</option><option value='1998'>1998</option><option value='1997'>1997</option><option value='1996'>1996</option><option value='1995'>1995</option><option value='1994'>1994</option><option value='1993'>1993</option><option value='1992'>1992</option><option value='1991'>1991</option><option value='1990'>1990</option></select></td></tr>" +
            "<tr class='j"+count+"'><td>Description.<span class='style1'>*</span>  300 words max.</td><td><textarea cols='30' rows='8' class='job req' name='desc"+count+"'></textarea></td></tr>");
	}
}


//Add another qualification to the application form on apply.php
function addQual() {
	if ($("#add_qual").parent().parent().prev().hasClass("q1")) {
		var count = '2';
	} else if ($("#add_qual").parent().parent().prev().hasClass("q2")) {
		var count = '3';
	} else {
		alert("You can only submit three qualifications.");	
	}
	if (count=='2' || count=='3') {
		$("#add_qual").parent().parent().before(
            "<tr class='q"+count+"'><td>Qualification (High School, Degree, etc)<span class='style1'>*</span></td><td><input type='text' class='qual req' name='degree"+count+"' /></td></tr>" +
            "<tr class='q"+count+"'><td>Subject(s)<span class='style1'>*</span></td><td><input type='text' class='qual req' name='subject"+count+"' /></td></tr>" +
            "<tr class='q"+count+"'><td>Institution<span class='style1'>*</span></td><td><input type='text' class='qual req' name='institute"+count+"' /></td></tr>" +
            "<tr class='q"+count+"'><td>Dates<span class='style1'>*</span></td><td><input type='text' class='qual req' name='q_dates"+count+"' /></td></tr>" +
            "<tr class='q"+count+"'><td>Grade<span class='style1'>*</span></td><td><input type='text' class='qual req' name='grade"+count+"' /></td></tr>");
	}
}

//Write selected job names to hidden input field so they can be passed to application.php
function jobCode() {
	var str='';
	$("#cpcode option:selected").each(function () {
                str += $(this).text() + " | ";
              });
	$('#cpname').val(str.substring(0,str.length-3));
}

//Write selected org name to hidden input field so it can be passed to application.php
function orgName() {
	$('#cplname').val($('#cporg option:selected').text());	
}

//Handle the results from placement.php by inserting the list of orgs and the list of jobs into the form on apply.php
function orgPost(){
	if(httpObject.readyState == 4){
		var response = eval('(' + httpObject.responseText + ')');
		
		//fill in orgs and hidden name field
		var orgs='';
		for (i in response.orgs) {
			orgs+=response.orgs[i];
		}
		$('#cporg').html(orgs);
		orgName();
		
		//fill in jobs and hidden name field
		var jobs='';
		for (i in response.jobs) {
			jobs+=response.jobs[i];
		}
		$('#cpcode').html(jobs);
		jobCode();
		
		//get rid of wait gif
		$("#wait_img").html('');
		
	}	
}

//Send request from apply.php to placements.php to get list of orgs and jobs
function getOrgs(pcode) {
	//insert spinning image to indicate a process is happening and the user should wait until it completes
	$("#wait_img").html("<img src='http://"+location.host+"/funcs/imgs/ajax-loader.gif' />");
	httpObject = new getHTTPObject();
	
	//can use the gup function to reset the value for pcode if, at some future point, you pass a GET variable of pcode from the placement/position page to apply.php
	//var pcode = gup('pcode');
	var ocode = $("#cporg option:selected").val();
	pcode!=''?params='pcode='+pcode:params='';
	ocode!=null?params+='&ocode='+ocode:params+='';
	var url = "http://"+location.host+"/funcs/placements.php?"+params;
	if (httpObject != null) {
		httpObject.onreadystatechange = orgPost;
		httpObject.open("GET", url, true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.send(params);
	}
}


//Handle the response from contact.php
function questResp() {
	if(httpObject.readyState == 4){
		$("#response").html(httpObject.responseText);
		$("#wait_img2").html('');
		var input = $("form input:text, textarea, select");
		jQuery.each(input, function() {
			this["value"] = '';
		});
	}
}

//Send requestion from contactus.html to contact.php
function ajaxQuest() {
	$("#response").html('');
	$("#wait_img2").html("<img src='funcs/imgs/ajax-loader.gif' />");
	httpObject = new getHTTPObject();
	
	var params="fname="+encodeURIComponent($("#cfname").val())+"&lname="+encodeURIComponent($("#clname").val())+"&email1="+encodeURIComponent($("#cemail1").val())+"&nationality="+encodeURIComponent($("#cnationality").val())+"&porg="+encodeURIComponent($("#cporg").val())+"&qType="+encodeURIComponent($("#cqType").val())+"&question="+encodeURIComponent($("#cquestion").val())+"&plname="+encodeURIComponent($("#cplname").val());
	var url = "/funcs/contact.php?"+params;
	if (httpObject != null) {
		httpObject.onreadystatechange = questResp;
		httpObject.open("POST", url, true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.send(params);
	}
}

//Check required form inputs using the below contraints
function checkForm() {
		var bad = 0;
		var input = $("form input:text, textarea, select");
		var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		jQuery.each(input, function() {		
			if (this["value"].length < 1 && $("#c"+this["name"]).hasClass('req') && !$("#c"+this["name"]).hasClass('text500')) {
				if(!$("#c"+this["name"]).next().hasClass("error")){
					$("#c"+this["name"]).after("<span class='error'>This is a required field.</span>");
				}
				bad++;
			} else if (this["name"]=="email1" && !emailReg.test(this["value"])) {
				if(!$("#c"+this["name"]).next().hasClass("error")){
					$("#c"+this["name"]).after("<span class='error'>Please enter a valid email address.</span>");
				}
				bad++;
			} else if (this["name"]=="email2" && this["value"]!=$("#cemail1").val()) {
				if(!$("#c"+this["name"]).next().hasClass("error")){
					$("#c"+this["name"]).after("<span class='error'>The email addresses you entered do not match.</span>");
				}
				bad++;
			} else if (($("#c"+this["name"]).hasClass("text500") && $("#c"+this["name"]).hasClass('req') && this["value"].match(/\s/g) && this["value"].match(/\s/g).length < 200) || ($("#c"+this["name"]).hasClass("text500") && $("#c"+this["name"]).hasClass('req') && this["value"].match(/\s/g)==null )) {
				if(!$("#c"+this["name"]).next().hasClass("error")){
					$("#c"+this["name"]).after("<span class='error'>Please respond with at least 200 words.</span>");
				}
				bad++;
			} else if ($("#c"+this["name"]).hasClass("text500") && this["value"].match(/\s/g) && this["value"].match(/\s/g).length > 500) {
				if(!$("#c"+this["name"]).next().hasClass("error")){
					$("#c"+this["name"]).after("<span class='error'>Please limit your response to 500 words.</span>");
				}
				bad++;
			} else {
				if($("#c"+this["name"]).next().hasClass("error")){
					$("#c"+this["name"]).next().remove();
				}
			}
		});
		return bad;
}

//When html page loads, execute the following functions
$(document).ready(function(){		
	//Load orgs, jobs, hidden name fields
	getOrgs(gup('pcode'));
	
	
	//Define click behavior for each element below
	$("#add_job").click(function () { 
		addJob();	
		defineInput();
    });
	$("#add_qual").click(function () { 
		addQual();		
		defineInput();
    });
	$("#cporg").change(function () { 
		pcode = '';		
		getOrgs(pcode);
    });
	
	//Apply.php submit function					   
	$("#msgform").submit(function() {
		if (checkForm()==0) {
			if ($('#cterms').attr('checked')) {
				$(this).parents().filter("form").trigger("submit");
			} else {
				alert('Please confirm that you have read and understand Ikando\'s terms & conditions.');
				return false;
			}
		} else {
			alert('You are missing some required fields.');
			return false;
		}
	});
	
	$('#msgform').bind('keypress', function(e) {
		if (e.keyCode == 13) {
			return false;
		}
	});
	
	//Contact Us page question submit
	$("#questform").submit(function() {
		if (checkForm()==0) {
			//$(this).parents().filter("form").trigger("submit");
			ajaxQuest();
			return false;	
		} else {
			alert('You are missing some required fields.');
			return false;
		}
	});
	
	$('#questform').bind('keypress', function(e) {
		if (e.keyCode == 13) {
			return false;
		}
	});
	
});

