// JavaScript Document
//Global variables
var bLoggedIn = false;

//function for initialiseing the event handlers
function initHandlers()
{
	var btnUpload = document.getElementById("btnUpload");
	var txtEmail = document.getElementById("txtEmail");
	var txtLoginEmail = document.getElementById("txtLoginEmail");
	var txtPassword = document.getElementById("txtPassword");
	var txtFirst = document.getElementById("txtFirstName");
	var txtLast = document.getElementById("txtLastName");
	var txtEditor = document.getElementById("txtEditor");	
	var chkAccept = document.getElementById("chkAccept");	
	var cvFile = document.getElementById("cvFile");	
	btnUpload.disabled = true;
	//subscribe to events
	txtEmail.onchange = ValidateField;
	txtLoginEmail.onchange = ValidateLogin;
	txtPassword.onchange = ValidateField;
	txtEditor.onchange = ValidateField;
	txtFirst.onchange = ValidateControl;
	txtLast.onchange = ValidateControl;
	chkAccept.onchange = ValidateControl;
	cvFile.onchange = ValidateControl;
	//set validity to false if contents empty, else raise event
	if(txtFirst.value.length > 0)
		CheckField(txtFirst,"fmRegister");
	else txtFirst.valid = false;	
	//check last name	
	if(txtLast.value.length > 0)
		CheckField(txtLast,"fmRegister");
	else txtLast.valid = false;	
	
	if(txtEmail.value.length > 0)
		ServerSideCheck(txtEmail,"fmRegister");
	else txtEmail.valid = false;	
	
	if(txtLoginEmail.value.length > 0)
		ServerSideCheck(txtLoginEmail,"fmLogin");
	else txtLoginEmail.valid = false;	
	
	if(txtPassword.value.length > 0)
		ServerSideCheck(txtPassword,"fmRegister");
	else txtPassword.valid = false;
	
	if(txtEditor.value.length > 0)
		ServerSideCheck(txtEditor,"fmRegister");
	else txtEditor.valid = false;	
	
	if(chkAccept.value.length > 0)
		CheckField(chkAccept,"fmRegister");
	else chkAccept.valid = false;
	
	if(cvFile.value.length > 0)
		CheckField(cvFile,"fmRegister");
	else cvFile.valid = false;	
	YAHOO.log("Initialised all fields");
};

function isFormValid(fmName)
{
	var frmMain = document.getElementById(fmName);
	var blnValid = true;
	for (var i=0; i < frmMain.elements.length; i++) 
	{
		if (typeof frmMain.elements[i].valid == "boolean") 
		{
			blnValid = blnValid && frmMain.elements[i].valid;
		}
	}
	return blnValid;
};



//Function for handling the response from the server
var oFormValidateObject = 
{
	name : "Form Validate:",
	//function called on success
	handleSuccess : function (oResponse) 
	{
		 if(oResponse.responseText !== undefined)
		 {								
			//convert to JSON
			if(YAHOO.lang.JSON.isValid(oResponse.responseText))
			{
				try
				{
					var jsResponse = YAHOO.lang.JSON.parse(oResponse.responseText);
					var txtField = oResponse.argument[0];
					var fmName = oResponse.argument[1];
					var imgError = document.getElementById("img"
							+ txtField.id.substring(3) + "Error");					
					if (!jsResponse.valid) 
					{
						imgError.src = "images/error.png";
						imgError.title = jsResponse.message;
						imgError.style.display = "inline";
						txtField.valid = false;
					} 
					else 
					{
						imgError.src = "images/greenTick.png";
						imgError.title = "Valid";
						imgError.style.display = "inline";
						txtField.valid = true;
					}
					//check if this is login or registeration form
					if(fmName == "fmRegister")
					{
						var btnUpload = document.getElementById("btnUpload");
						btnUpload.disabled = !isFormValid(fmName);
					}
				}
				catch(Ex)
				{
					YAHOO.log("Error: " + Ex);
				}
				//jsResponse.
			}
			else
			{
				YAHOO.log("Invalid json");
			}
		}//end if response
	},
	//function called on failure
	handleFailure : function (oResponse) 
	{
		alert(this.name + " An error occurred." + oResponse.statusText + 
			  oResponse.responseText);
	}
};

//Main function called when user clicks the submit button
function ValidateField(oEvent)
{	
	oEvent = oEvent || window.event;
	//save the text form field to a variable
	var txtCVFormField = oEvent.target || oEvent.srcElement;
	YAHOO.log("Validate " + txtCVFormField.name);
	ServerSideCheck(txtCVFormField, "fmRegister");
};

function ValidateLogin(oEvent)
{
	oEvent = oEvent || window.event;
	//save the text form field to a variable
	var txtFormField = oEvent.target || oEvent.srcElement;
	ServerSideCheck(txtFormField, "fmLogin");
};
//Function for validation using server side
function ServerSideCheck(txtCVFormField, fmName)
{
	YAHOO.log("ServerSide Check " + txtCVFormField + fmName);
	//set url to php handler
	var url="scripts/php/uploadScript.php";
	//&targetField=" + txtField.name + "&sid="+Math.random();
	
	//get the contents of the form to be posted
	var oForm = document.getElementById(fmName);
	//set the form data
	YAHOO.util.Connect.setForm(oForm);	
	
	//callback for connection manager
	oFormCallback = 
	{
		success: oFormValidateObject.handleSuccess,
		failure: oFormValidateObject.handleFailure,
		timeout: 3000,
		scope: oFormValidateObject,
		argument: [txtCVFormField, oForm.name]
	};
	
	//call the async request of the connection manager
	var objAsync = YAHOO.util.Connect.asyncRequest('POST', url, oFormCallback,
						"targetField="+txtCVFormField.name); 
}

///Event handler for validating the rest of the controls for length and selection
function ValidateControl(oEvent)
{
	oEvent = oEvent || window.event;
	//save the form field to a variable
	var fmField = oEvent.target || oEvent.srcElement;
	CheckField(fmField,"fmRegister");
};
//Client side checking of controls
function CheckField(fmField, fmName)
{
	YAHOO.log("Field checked");
	//switch on the field type
	if( (fmField.type == "text") || (fmField.type == "file"))
	{
		if(fmField.value.length > 0)
		{
			fmField.valid = true;
		}
	}
	else if(fmField.type == "checkbox")
	{
		if(fmField.checked) fmField.valid = true;
	}	
	//set image valid if field true
	if(fmField.valid == true)
	{
		//get the image tag
		var imgValid = document.getElementById("img" + fmField.id);
		//set the image tick
		imgValid.style.display = "inline";
		imgValid.title = "Valid";
	}				
	//call method to enable button if all true
	document.getElementById("btnUpload").disabled = !isFormValid(fmName);
}


//Main function called when user clicks the submit button
function RegisterCandidate()
{	
	//display progress image
	var progressImage = document.getElementById("cvUploading");
	//set html for image
	progressImage.innerHTML = "<img src=\"images/cv-uploader.gif\" alt=\"CV uploading..\" />";
	YAHOO.log(progressImage.src);
	//set url to php handler
	var url="scripts/php/cvUploadHandle.php";
	//get the contents of the form to be posted
	var oForm = document.getElementById("fmRegister");
	YAHOO.log("Button pressed" + oForm.name);
	//the second argument of setForm is crucial,
    //which tells Connection Manager this is a file upload form
	YAHOO.util.Connect.setForm(oForm, true);	
	
	//callback for connection manager
	oCVCallback = 
	{
		upload: function(oResponse)
		{
			YAHOO.log("Responded");
			//clear the upload image
			//display progress image
			var progressImage = document.getElementById("cvUploading");
			//set html for image
			progressImage.innerHTML = "";
	
			//try and convert to JSON
			if(YAHOO.lang.JSON.isValid(oResponse.responseText))
			{						
				var jsResponse = YAHOO.lang.JSON.parse(oResponse.responseText);
				alert(jsResponse.message);
			}				
			else alert(oResponse.responseText);				
		}
	};
	//start upload
	YAHOO.log("Start upload");
  	YAHOO.util.Connect.asyncRequest('POST', url, oCVCallback);
	return false;
};


//Function for handling the response from the server
//when an existing candidate logs in
var oFormLoginObject = 
{
	name : "Form Login:",
	//function called on success
	handleSuccess : function (oResponse) 
	{
		YAHOO.log("Responded:" + oResponse.responseText);
		 if(oResponse.responseText !== undefined)
		 {								
			//convert to JSON
			if(YAHOO.lang.JSON.isValid(oResponse.responseText))
			{
				try
				{
					var jsResponse = YAHOO.lang.JSON.parse(oResponse.responseText);				
					if (jsResponse.valid != 0) 
					{
						//the response is valid, so display the candidate details as they have logged in
						bLoggedIn = true;
						//redirect to new self page
						window.location = "http://www.two76.com/jobs/submitCVLoggedIn.php";
					} 
					else 
					{
						//display error message to user
						YAHOO.log("JSON parse error:" +oResponse.responseText);		
					}
				}
				catch(Ex)
				{
					YAHOO.log("Error: " + Ex);
				}
			}
			else
			{
				YAHOO.log("Invalid json: " + oResponse.responseText );
			}
		}//end if response
	},
	//function called on failure
	handleFailure : function (oResponse) 
	{
		alert(this.name + " An error occurred." + oResponse.statusText + 
			  oResponse.responseText);
	}
};

//Function for login in a candidate
function CandidateLogin()
{	
	//this stage reached after email has been checked	
	//set url to php handler
	var url="scripts/php/existingCandidate.php";
	//get the contents of the form to be posted
	var oForm = document.getElementById("fmLogin");
	YAHOO.log("Button pressed" + oForm.name);	
	YAHOO.util.Connect.setForm(oForm);		

	//callback for connection manager
	oCVCallback = 
	{
		success: oFormLoginObject.handleSuccess,
		failure: oFormLoginObject.handleFailure,
		timeout: 3000,
		scope: oFormLoginObject
	};
	//start upload
	YAHOO.log("Start login");
  	YAHOO.util.Connect.asyncRequest('POST', url, oCVCallback);
	//alert("Apologies, this feature is not yet supported.");
};

/*
Function for logging out the candidate
*/
function CandidateLogout()
{
	//unset the flag
	bLoggedIn = false;
	//unset the php logged in script
	var url="scripts/php/existingCandidate.php";
	//get the contents of the form to be posted
	//var oForm = document.getElementById("fmLogin");
	//YAHOO.log("Button pressed" + oForm.name);	
	//YAHOO.util.Connect.setForm(oForm);		

	//callback for connection manager
	oLogoutCallback = 
	{
		success: function(oResponse)
		{
			YAHOO.log(oResponse.responseText);
			//redirct to submit cv page
			window.location = "http://www.two76.com/jobs/submitCV.php";
		},
		failure: function(oResponse)
		{
			YAHOO.log(oResponse.responseText);
		},
		timeout: 3000
	};
	if(confirm("Are you sure you want to logout?"))
	{
		//log out candidate
	  	YAHOO.util.Connect.asyncRequest('POST', url, oLogoutCallback, "logout=true");	
	}

}
