MG.namespace("MG.widget.Applicant");
MG.widget.Applicant = (function() {
	var address_defaults = {
		address_1 : 'Address 1',
		address_2 : 'Address 2',
		city : 'City',
		state : 'AA',
		zip : 'Zip Code'
	};
	var templates = {
		myJobsItem : [
			'<a href="javascript:void(0);" onclick="MG.widget.JobPosting.showJob(\'{id}\', false);">{job_name}</a><br/>'
		].join(""),
		applicant : [
			'<div id="applicationForm" style="visibility:hidden;">',
				'<h3>Create an Account</h3>',
				'<form name="newCandidate" id="newCandidate" action="index.php" method="post" enctype="multipart/form-data" onsubmit="MG.util.Modal.showSaving();" >',
					'<input type="hidden" name="view" value="handleNewCandidate" />',
					'<dl id="new_applicant_elements">',
						'<dt>Email Address:</dt>',
						'<dd><input id="new_applicant_email" class="required email-address" type="text" name="email" value="" /></dd>',
						'<dt>First Name:</dt>',
						'<dd><input type="text" class="required" name="first_name" value="" /></dd>',
						'<dt>Last Name:</dt>',
						'<dd><input type="text" class="required" name="last_name" value="" /></dd>',
			
						'<dt>Daytime Telephone:</dt>',
						'<dd><input type="text" class="required" name="phone" value="" /></dd>',
			
						'<dt>Resum&eacute; (*.txt, *.doc, *.pdf accepted):</dt>',
						'<dd><input type="file" class="required" name="resume"/></dd>',
			
						'<dt>Preferred Method of Contact:</dt>',
						'<dd>' +
							'<input type="radio" name="preferred_method" value="email" checked="checked" />Email',
							'<input type="radio" name="preferred_method" value="phone" />Telephone',
						'</dd>',
			
						'<dt>&nbsp;</dt>',
						'<dd>' +
							'<input type="button" value="Cancel" onclick="MG.widget.Applicant.showLogin();" />' +
							'<input type="button" value="Create Account" onclick="MG.widget.Applicant.submitNewAccount();" />' +
						'</dd>',
					'</dl>',
				'</form>',
			'</div>'
		].join("")	
	};
	
	
	/**
	 * Handles candidate login
	 */
	function handleLogin(o) {
		if(true) {
			window.location.href = 'index.php?view=jobs';
		} else {
		}
	}
	
	function submitNewAccount() {
		if(MG.util.Form.validateForm(gel("newCandidate"))) { 
			$("#newCandidate").submit();
		}
	}
	

	/**
	 * Shows a profile photo upload modal
	 */
	function updateProfilePhoto() {
		$("#updateProfilePhoto").dialog({
			title			: "Update Profile Photo",
			modal			: true,
			buttons			: {
				"Cancel" : function() {
					$(this).dialog('close');
				},
				"Update" : function() {
					gel("updateProfilePhotoForm").submit();
				}
			}
		});
	}

	/**
	 * Shows a resume file upload modal
	 */
	function updateResume() {
		$("#updateResume").dialog({
			title			: "Update Resum&eacute;",
			modal			: true,
			buttons			: {
				"Cancel" : function() {
					$(this).dialog('close');
				},
				"Update" : function() {
					gel("updateResumeForm").submit();
				}
			}
		});
		
	}
	
	
	/**
	 * Validates change password fields
	 */
	function validateChangePassword(d) {
		var ret = true;
		var message = $(d).find(".message"); 
		message.empty();
		
		$(d).find('input').each(function() {
			$(this).removeClass("error");
			
			if(this.value == "") {
				$(this).addClass("error");
				message.html('All fields are required.');
				ret = false;
			}
		});
		
		if($("#new_password_1").val() != $("#new_password_2").val()) {
			message.html("The new passwords do not match");
			ret = false;
		}
		
		return ret;
	}
	
	
	/**
	 * Show  change password modal
	 */
	function startChangePassword() {
		$("#changePassword").dialog({
			title			: 'Change My Password',
			modal			: true,
			buttons			: {
				"Cancel" : function() {
					$(this).dialog("close");
				},
				"Update Password" : function() {
					var dialog = this;
					
					if(validateChangePassword(dialog)) {
						$.ajax(MG.util.Async.getConfig({
							data	: {
								action				: 'changePassword',
								current_password	: $(this).find("input[name=current_password]").val(),
								new_password		: $(this).find("input[name=new_password_1]").val()
							},
							success : function(json) {
								var o = $.parseJSON(json);
								
								if(o.status == 'success') {
									$(dialog).dialog('close');
									MG.util.Async.handleMessaging(json);
								} else {
									$(dialog).find(".message").html(o.message);
								}
							}
						}));
					}
				}
			}
		});
	}

	/**
	 * Sends the user an email with a temp password.
	 */
	function forgotPassword() {
		var e = gel("login_email");
		
		if(MG.isValidEmail(e.value)) {
			MG.util.Modal.showSaving();
			$.ajax(MG.util.Async.getConfig({
				data : {
					action	: 'reset_password',
					email	: e.value
				},
				success : function(json) {
					MG.util.Modal.hideModal();
					MG.util.Async.handleMessaging(json);
				}
			}));
		} else {
			$(e).addClass("error");
			$.jGrowl("Please provide a valid email address.", {sticky:true});
		}
	}
	
	/**
	 * Redirects the user to the apply view
	 */
	function applyForPosition(id) {
		MG.util.Modal.hideModal();
		MG.util.Modal.showSaving();
		window.location.href = "index.php?view=jobs&action=applyForPosition&job_id=" + id;
	}
	
	/**
	 * Redirects to the Edit page
	 */
	function edit() {
		window.location.href = "index.php?view=myAccount&action=edit";
	}
	
	/**
	 * Redirects to Detail page
	 */
	function cancelSave() {
		var s = $("#simpleModal");
		s.empty();
		s.html("Really cancel all changes and revert to previous?");
		s.dialog({
			title	: "Lose All Changes?",
			modal	: true,
			buttons	: {
				"Cancel" : function() {
					$(this).dialog("close");
				},
				"Lose Changes" : function() {
					window.location.href = "index.php?view=myAccount&action=detail";
				}
			}
		});
	}

	/**
	 * Hides applicant form, shows login form
	 */
	function showLogin() {
		$("#applicationForm").hide(250, function() {
			$("#loginForm").show(250, MG.fixContentHeight);
		});
		
		$("#applicant_link").toggleClass("show-register");
	}
	
	/**
	 * Hides the login form, shows the application form
	 */
	function showRegister() {
		function _afterShow() {
			MG.fixContentHeight();
			gel("new_applicant_email").value = gel("login_email").value;	
		}
		
		if(gel("applicationForm") === null) {
			$("#loginForm").hide(250, function() {
				var t = new MG.util.Template(templates.applicant);
				t.append("form");
				
				$("#applicationForm").css("display", "none").css("visibility", "visible").show(250, _afterShow);
			});
		} else {
			$("#loginForm").hide(250, function() {
				$("#applicationForm").show(250, _afterShow);
			});
		}
		
		$("#applicant_link").toggleClass("show-register");
	}
	
	
	/**
	 * Shows the jobs applied to
	 */
	function showMyApplications() {
		MG.util.Modal.showSaving();
		
		$.ajax(MG.util.Async.getConfig({
			data : {
				action : 'getMyJobs'
			},
			success : function(json) {
				MG.util.Modal.hideModal();
				$("#modal_content").empty();
				
				var o = $.parseJSON(json), t, s='', i=0;
				
				for(var k in o.items) {
					if(o.items.hasOwnProperty(k)) {
						i++;
						t = new MG.util.Template(templates.myJobsItem);
						t.applyValues(o.items[k]);
						s += t.toString();
					}
				}
				
				if(i > 0) {
					MG.util.Modal.showMessageInAModal(s, 'Positions Applied');
				} else {
					$.jGrowl("You have not yet applied for a position.", { theme : 'standard' });
				}
			}
		}));
	}
	
	/**
	 * Validates inputs in my account form
	 * @param	{HTMLForm} f
	 * @return	{Boolean}
	 */
	function _validateMyAccountForm(f) {
		var success = true;

		// validate address section
		$(".address").find("input").each(function() {
			if(this.value == address_defaults[this.name]) {
				this.value = "";
			}
		});
		
		success = MG.util.Form.validateForm(f);
		
		return success;
	}
	/**
	 * Saves applicant info from My Account
	 */
	function save() {
		MG.closeGrowl();
		var f = gel("myAccount"), vars = {}, i, n, el;
		
		if(_validateMyAccountForm(f) === true) {
			for(i=0, n=f.elements.length; i<n; i++) {
				el = $(f.elements[i]);
				
				vars[el.attr("name")] = el.val();
			}
			
			MG.util.Modal.showSaving();
			
			$.ajax(MG.util.Async.getConfig({
				data	: vars,
				success	: function(json) {
					MG.util.Modal.hideModal();
					var o = MG.util.Async.handleMessaging(json);
					
					if(o !== null && o.status == 'success') {
						window.location.href = 'index.php?view=myAccount&action=detail';
					}
				}
			}));
		}
	}
	
	function initAddressForm() {
		var d = $(".address");
		
		d.find("input").each(function() {
			$(this).bind("focus", _handleFocus).bind("blur", _handleBlur).bind("keyup", _handleKeyUp);
			if(this.value == "") {
				this.value = address_defaults[this.name];
			}
			
			if(this.value == address_defaults[this.name]) {
				$(this).addClass("address_defaults");
			}
		});
	}
	function _handleFocus(e) {
		if(e.target.value == address_defaults[e.target.name]) {
			e.target.value = "";
			$(e.target).removeClass("address_defaults");
		}
	}
	function _handleBlur(e) {
		if(e.target.value == "") {
			e.target.value = address_defaults[e.target.name];
			$(e.target).addClass("address_defaults");
		}
	}
	function _handleKeyUp(e) {
		if(e.target.value == "") {
			/*
			e.target.value = address_defaults[e.target.name];
			$(e.target).addClass("address_defaults");
			*/
		} else if(e.target.value != address_defaults[e.target.name]) {
			$(e.target).removeClass("address_defaults");
		} else if(e.target.value == address_defaults[e.target.name]) {
			$(e.target).removeClass("address_defaults");
			e.target.value = "";
		}
	}
	
	MG.registerBoot(initAddressForm);
	
	
	$("#newCandidate, #candidateLogin").bind("keyup", function(e) {
		if(e.keyCode == 13) {
			$(this).submit();
		}
	});
	
	return {
		applyForPosition	: applyForPosition,
		cancelSave			: cancelSave,
		edit				: edit,
		forgotPassword		: forgotPassword,
		handleLogin			: handleLogin,
		save				: save,
		showRegister		: showRegister,
		showLogin			: showLogin,
		showMyApplications	: showMyApplications,
		startChangePassword	: startChangePassword,
		submitNewAccount	: submitNewAccount,
		updateProfilePhoto	: updateProfilePhoto,
		updateResume		: updateResume 
	};
})();
