

/**
 * Calls a PHP script which simply restores our session, preventing the user from being logged out.
 */
function keepSessionAlive() {
	$.get("/haf/keep_session_alive.php");
}

/**
 * Jumps to a section when the section select box is changed.
 *
 * @param	string		section		Which section to jump to.
 */
function jumpToSection(section) {
	location.href = '/chevin.php/cat/1/sub_cat/20/section/' + section + '/';
}

/**
 * Logs the user in.
 * Used on index.php
 */
function logIn() {
	postdata = $("#login_form").serialize();

	$.post("/haf/process_login.php", postdata, 
		function(data) {
			if (data.status == "VALID") {
				// Redirect user to last section they were completing (or section 1 if this is their first login)
				location.href = '/chevin.php/cat/1/sub_cat/20/section/' + data.last_section + '/';
			} else {
				// Set status message and show
				$("#status_message").addClass(data.message_type).text(data.message).fadeIn("slow");
			}
			
			// Clear password field
			$("#login_form #password").val("");
		}, "json");
}

/**
 * Registers the user.
 */
function register() {
	postdata = $("#registration_form").serialize();

	$.post("/haf/process_registration.php", postdata, 
		function(data) {
			switch (data.status) {
				case "SUCCESS":
					// Redirect user to section 1 of the application form
					location.href = '/chevin.php/cat/1/sub_cat/20/section/1/';
					break;
				case "EMAIL_ADDRESS_IN_USE":
				case "NI_NUMBER_IN_USE":
				case "VALIDATION_ERROR":
					// Set status message and show
					$("#status_message").addClass(data.message_type).text(data.message).fadeIn("slow");
					break;
			}
			
			// Clear password fields
			$("#registration_form #password, #registration_form #confirm_password").val("");
		}, "json");
}

/**
 * Refreshes the list of child applicants in section 4 whenever we alter applicants' dates of births in the same section.
 */
function reloadChildApplicants() {
	$("#schools .child_applicants").each(function() {
		selectedApplicantID = $(this).val();
		$(this).empty();
		obj = $(this);
		$.post("/haf/fetch_children.php", {selected_applicant_id: selectedApplicantID}, function(response) {
			$.each(response, function(i, v) {
				$(obj).append(v);
			});
		}, "json");
	});
}

/**
 * Attaches a datepicker widget to the last/newly-inserted datefield.
 */


/**
 * Loads in the relevant form into our form_container div, depending on which radio button was selected.
 * Used on index.php
 *
 * @param 	string 		action 		Which action to take/which form to load in.
 */
function changeFormType(action) {
	// Hide error message
	$("#status_message").hide();
	
	$("#form_container").slideUp("medium", function() {
		$("#form_container").load("/haf/form_" + action + ".php", function() {
			$("#form_container").slideDown("medium");
		});
	})
}

/**
 * Saves single form values in the database on-the-fly when changed, using AJAX.
 */
function saveFormValueDate(field, value) {
	row_id = $("[name*=" + field + "]").parents("table").attr("rel");
	
	//alert(field);

	$.post("/haf/save_form_value.php", {field: field, value: value, row_id: row_id}, 
		function(response) {
			//console.log(response.validation_type);
		}, "json");
}

/**
 * Saves single form values in the database on-the-fly when changed, using AJAX.
 */
function saveFormValue(obj) {
	field = $(obj).attr("name");
	value = $(obj).val();
	row_id = $(obj).parents("table").attr("rel");
	
	//alert(value);

	$.post("/haf/save_form_value.php", {field: field, value: value, row_id: row_id}, 
		function(response) {
			//console.log(response.validation_type);
			liveEventsReplicator();
		}, "json");
}

/**
 * Saves multiple form values in the database on-the-fly when changed, using AJAX.
 */
function saveMultipleFormValues(obj) {
	field = $(obj).attr("name");
	value = "";
	row_id = $(obj).parents("table").attr("rel");

	$("input[name=" + field + "]").each(function (i) {
		if (this.checked) {
			value += $(this).val() + "\n";
		}
	});
	
	//alert(value);
	
	$.post("/haf/save_form_value.php", {field: field, value: value, row_id: row_id}, 
		function(response) {
			//console.log(response.validation_type);
			liveEventsReplicator();
		}, "json");
}

/**
 * Adds a new row into the database for the additional question part
 */
function addAdditionalPartRow(section, part, htmlBlock) {
	$.post("/haf/add_additional_part.php", {section: section, part: part}, 
		function(response) {
			// Change ID's and show new part fields
			$("#" + part).append($("#" + htmlBlock).html()).show("fast", function() {
				$("#" + part + " table:last").attr("rel", "row_" + response.row_id);
				$("#" + part + " table:last [name]").each(function() {
					name = $(this).attr("name");
					$(this).attr("name", name + "[" + response.row_id + "]");
				});
				$("#" + part + " table:last [id]").each(function() {
					id = $(this).attr("id");
					$(this).attr("id", id + "[" + response.row_id + "]");
				});
				// For datefields
				$("#" + part + " table:last [rel]").each(function() {
					name = $(this).prevAll("input[type=hidden]").attr("name");
					$(this).attr("rel", name);
				});
				liveEventsReplicator();
			});
			
			location.reload();
		}, "json");
}

/**
 * Deletes an existing row from the database for the additional question part
 */
function deleteAdditionalPartRow(section, part, row_id, obj) {
	$.post("/haf/delete_additional_part.php", {section: section, part: part, row_id: row_id}, function(response) {
		$(obj).parents("table").remove();
	}, "json");
}

function validateSection(section) {
	data = $("#haf form *:not([class*=ignoreValidation])").filter(":visible, input[type=hidden]").serialize();
	data += '&';
	data += $(".allowHiddenSubmit").serialize();
	data += '&_section=' + section;
	//alert(data);
	
	// Remove all error/invalid response classes
	$("#haf .invalid_response").removeClass("invalid_response");
	$("#error_message").slideUp("slow");
	
	$.post("/haf/validate_section.php", data, function(response) {
		if (response.status == "validated") {
			// Go to next unvalidated section
			location.href = "/chevin.php/cat/1/sub_cat/20/section/" + response.next_unvalidated_section + "/";
		} else {
			$.each(response, function(i, v) {
				$("#error_" + v).addClass("invalid_response");
				$(".error_" + v).addClass("invalid_response");
				//alert(v);
			})
			$("#error_message").slideDown("slow");
			
			//$("button#submit_app_form").html('<img src="/images/icons/disk.png" alt="" class="icon" /><span>Save Section &amp; Submit Application</span>');
			//$("button#submit_app_form").attr("disabled", false);
			
			// Scroll up to error message
			location.href = "#error_message";
		}
	}, "json");
}

/**
 * Toggles show/hide visibility on fields which may or may not be required dependent on answers to other questions
 */
function toggle(obj) {
	fieldName = $(obj).attr("name");
	fieldValue = $(obj).val();

	divMap = new Object;
	
	divMap.related_to_staff = "#related_to_staff_container";
	divMap.have_children = "#schools_container";
	divMap.other_household_members = "#other_household_members";
	divMap.pets = "#pets_details_container";
	divMap.lived_continuously_in_uk = "#not_lived_continuously_container";
	divMap.asbo = "#asbo_container";
	divMap.excluded_from_housing_register = "#excluded_from_housing_register_container";
	divMap.rent_arrears = "#rent_arrears_container";
	divMap.have_convictions = "#convictions_container";
	divMap.current_accomodation = "#current_accomodation_details_container";
	divMap.been_evicted = "#applicants_evicted_container";
	
	if (divMap[fieldName] != undefined) {
		switch (fieldValue) {
			case "Yes":
				$(divMap[fieldName]).slideDown();
				$(divMap[fieldName] + " input").removeClass("ignoreValidation");
				$(divMap[fieldName] + " select").not(".datefield").removeClass("ignoreValidation");
				$(divMap[fieldName] + " textarea").removeClass("ignoreValidation");
				break;
			case "No":
				$(divMap[fieldName]).slideUp();
				$(divMap[fieldName] + " input").addClass("ignoreValidation");
				$(divMap[fieldName] + " select").not(".datefield").addClass("ignoreValidation");
				$(divMap[fieldName] + " textarea").addClass("ignoreValidation");
				break;
			case "Other":
				$(divMap[fieldName]).slideDown();
				$(divMap[fieldName] + " input").removeClass("ignoreValidation");
				$(divMap[fieldName] + " select").not(".datefield").removeClass("ignoreValidation");
				$(divMap[fieldName] + " textarea").removeClass("ignoreValidation");
				break;
			default:
				$(divMap[fieldName]).slideUp();
				$(divMap[fieldName] + " input").addClass("ignoreValidation");
				$(divMap[fieldName] + " select").not(".datefield").addClass("ignoreValidation");
				$(divMap[fieldName] + " textarea").addClass("ignoreValidation");
		}
	}
	
	if (fieldName == "joint_applicant") {
		switch (fieldValue) {
			case "Yes":
				$(".joint_applicant_field").show();
				$(".joint_applicant_field *").removeClass("ignoreValidation");
				$("#error_joint_applicant_relationship").slideDown();
				$("#error_joint_applicant_relationship *").removeClass("ignoreValidation");
				$("select[name*=joint_applicant_dob]").addClass("ignoreValidation");
				break;
			case "No":
				$(".joint_applicant_field").hide();
				$(".joint_applicant_field *").addClass("ignoreValidation");
				$("#error_joint_applicant_relationship").slideUp();
				$("#error_joint_applicant_relationship *").addClass("ignoreValidation");
				break;
		}
	}
	
	if (fieldName == "lived_continuously_in_uk") {
		switch (fieldValue) {
			case "Yes":
				$("#not_lived_continuously_container").slideUp();
				$("#not_lived_continuously_container" + " input").addClass("ignoreValidation");
				$("#not_lived_continuously_container" + " select").not(".datefield").addClass("ignoreValidation");
				$("#not_lived_continuously_container" + " textarea").addClass("ignoreValidation");
				break;
			case "No":
				$("#not_lived_continuously_container").slideDown();
				$("#not_lived_continuously_container" + " input").removeClass("ignoreValidation");
				$("#not_lived_continuously_container" + " select").not(".datefield").removeClass("ignoreValidation");
				$("#not_lived_continuously_container" + " textarea").removeClass("ignoreValidation");
				break;
		}
	}
}
