$(document).ready(document_Ready);

var service;

function document_Ready()
{
	assignEventListeners();
	
	service = new BHService();
	var service_Error = function(msg, code)
	{
		alert("service error: " + msg + "\n" + code);
	}
	service.setErrorHandler(service_Error);
}


function assignEventListeners()
{
	$("*[SearchFormReseter='true']").click(SearchFormReseter_Click);
	$(".profileLoginButton").click(profileLoginButton_Click);
	$(".createNewProfileButton").click(createNewProfileButton_Click);
	$("*[OnEnterClick]").bind("keydown", OnEnterClick_Press);
	$("#profileForm").submit(profileForm_Submit);
	$("#applySubmitButton").click(applySubmitButton_Click);
	$("#applyWithPasswordButton").click(applyWithPasswordButton_Click);
	$(".forgotPasswordButton").click(forgotPasswordButton_Click);
	$(".forgotPasswordLink").click(forgotPasswordLink_Click);
}


function authenticateAndLoadProfile(email, password, callback)
{
	var service_Result = function(result)
	{
		if(result)
		{
			var info_Result = function(result)
			{
				loadProfile(result[0]);
			}
			
			service.setCallbackHandler(info_Result);
			service.getCandidateInfo(email);
		}
		else
		{
			alert("The login credentials provided were not recognized. Please try again.");
			$("#profileLoginEmail").select();
		}
		
		if(callback != null)
		{
			// execute specified callback function
			callback();
		}
	};
	service.setCallbackHandler(service_Result);
	service.authenticateUser(email, password);
}


function loadProfile(data)
{
	//dumpObject(data);
	var elements = ["firstName", "lastName", "address1", "address2", "city", "state", "zip", "email", "password", "cell"];
	for(var i in elements)
	{
		var element = elements[i];
		$("#" + element).val(data[element.toUpperCase()]);
	}
	
	// fix zip
	var ziplength = parseInt(data.ZIP.toString().length);
	if(ziplength < 5)
	{
		var extraZeros = 5 - ziplength;
		var newZip = "";
		for(var i=0; i < extraZeros; i++)
		{
			newZip += "0";
		}
		newZip += data.ZIP;
		$("#zip").val(newZip);
	}
	
	// fix phone
	
	// fix cell
	
	$("#confirmPassword").val(data.PASSWORD);
	
	$("#profileLoginContainer").hide();
	$("#forgotPasswordContainer").hide();
	$("#profileFormContainer").show();
}


/*
 * Utilities
 */


function dumpObject(obj)
{
	var output = "";
	for(var prop in obj)
	{
		output += prop + ": " + obj[prop] + "\n";
	}
	alert(output);
}


function throbberSwap(type, elem, throbber)
{
	if(type.toLowerCase() == "on")
	{
		elem.hide();
		throbber.show();
	}
	else
	{
		elem.show();
		throbber.hide();
	}
}



/*
 * Event Handlers
 */


function forgotPasswordLink_Click()
{
	var sender = $(this);
	var container = $("#" + sender.attr("Container"));
	container.show(300);
}

function forgotPasswordButton_Click()
{
	var sender = $(this);
	var throbber = $("#" + sender.attr("Throbber"));
	var emailElem = $("#" + sender.attr("Email"));
	var email = emailElem.val();
	var keepEmail = sender.attr("KeepEmail") != null && sender.attr("KeepEmail") == "true";
	
	var isCurrentUser_Result = function(result)
	{
		if(result)
		{
			alert("The profile password has been sent.");
			if(!keepEmail)
			{
				emailElem.val("");
			}
			throbberSwap("off", sender, throbber);
			$("#forgotPasswordContainer").hide(300);
			
			var sendemail_Complete = function(){};
			
			service.setCallbackHandler(sendemail_Complete);
			service.sendPassword(email);
		}
		else
		{
			alert("The specified email was not recognized. Please retry.");
			throbberSwap("off", sender, throbber);
			emailElem.select();
		}
	};
	
	throbberSwap("on", sender, throbber);
	
	service.setCallbackHandler(isCurrentUser_Result);
	service.isCurrentUser(email);
}

function applyWithPasswordButton_Click()
{
	var sender = $(this);
	var throbber = $("#" + sender.attr("Throbber"));
	throbberSwap("on", sender, throbber);
	
	var auth_Result = function(result)
	{
		if(result)
		{
			// APPLY
			var apply_Complete = function(result)
			{
				alert("Thank you for your application.");
				$("#applyEmail").val("");
				$("#applyPassword").val("");
				$("#applyPasswordContainer").hide(300);
				
				throbberSwap("off", sender, throbber);
			}
			
			service.setCallbackHandler(apply_Complete);
			service.applyToJob( $("#applyEmail").val(), $("#jobId").val() );
		}
		else
		{
			alert("The login credentials specified were not recognized. Please retry.");
			throbberSwap("off", sender, throbber);
		}
	}
	
	service.setCallbackHandler(auth_Result);
	service.authenticateUser($("#applyEmail").val(), $("#applyPassword").val())
}

function applySubmitButton_Click()
{
	var sender = $(this);
	var throbber = $("#" + sender.attr("Throbber"));
	throbberSwap("on", sender, throbber);
	
	var isCurrentUser_Result = function(result)
	{
		if(result)
		{
			throbberSwap("off", sender, throbber);
			
			$("#applyPasswordContainer").show(300);
			var selectPassword = function()
			{
				$("#applyPassword").select();
			};
			
			setTimeout(selectPassword, 1000);
		}
		else
		{
			// fill in hidden form elements and submit
			$("#profileFormEmail").val( $("#applyEmail").val() );
			$("#hiddenApplyForm").attr("action", "/Profile/New/" + $("#jobId").val())
			$("#hiddenApplyForm").submit();
		}
	};
	
	service.setCallbackHandler(isCurrentUser_Result);
	service.isCurrentUser($("#applyEmail").val());
}

function profileForm_Submit()
{
	var sender = $("#profileFormSubmitButton");
	var throbber = $("#" + sender.attr("Throbber"));
	throbberSwap("on", sender, throbber);
	
	var stateValue = $("#state").val();
	if(stateValue == "")
	{
		alert("Please provide a state.");
		throbberSwap("off", sender, throbber);
		return false;
	}
	
	if($("#confirmPassword").val() != $("#password").val())
	{
		alert("Your confirmation password does not match.");
		$("#confirmPassword").select();
		throbberSwap("off", sender, throbber);
		return false;
	}
	
	// checking email address if new profile
	var isNewP = parseInt( $("#isNewProfile").val() );
	if(isNewP)
	{
		// check email address
		var usercheck_Complete = function(result)
		{
			if(result)
			{
				alert("There is already an account associated with the specified email address. Please use another.");
				$("#email").select();
				throbberSwap("off", sender, throbber);
				return false;
			}
			else
			{
				// form will never submit unless this is 0, we know the email is safe, so just set it to 0 and resubmit
				$("#isNewProfile").val("0");
				$("#profileForm").submit();
			}
		}
		service.setCallbackHandler(usercheck_Complete);
		service.isCurrentUser( $("#email").val() );
		
		// assume false and resubmit later if true
		return false;
	}
}

function OnEnterClick_Press(e)
{
	if(e.keyCode == 13)
	{
		var clickObject = $("#" + $(this).attr("OnEnterClick"));
		clickObject.trigger("click");
	}
}

function SearchFormReseter_Click()
{
	$(".SearchFormElement").val("");
}

function profileLoginButton_Click()
{
	var sender = $(this);
	var throbber = $("#" + sender.attr("Throbber"));
	var email = $("#profileLoginEmail").val();
	var password = $("#profileLoginPassword").val();
	
	if(email == null || email == "" || password == null || password == "")
	{
		alert("Please provide an email and password.");
		return;
	}
	
	var auth_Complete = function(result)
	{
		throbber.hide();
	}
	
	authenticateAndLoadProfile(email, password, auth_Complete);
	throbber.show();
}

function createNewProfileButton_Click()
{
	$("#profileLoginContainer").hide();
	$("#profileFormContainer").show();
	$("#isNewProfile").val("1");
	$("#email").attr("readonly", false);
	$("#firstName").select();
}


function SearchFormReseter_Click()
{
	$("#Keywords").val("");
	$("#Location").val("");
	$("#Keywords").select();
}

