function unexpectedAJAXFailure(xhr, json) {
	alert("An unexpected AJAX failure occurred, please contact administrator.");
}

// Called from the base template to remotely request the login form.
function submitLogin() {
	$('loginFormLoading').show();
	$('loginFormButton').disable();
	$('loginMessage').innerHTML = "";
	$('loginMessage').hide();
	new Ajax.Request('/r/login', {method: 'post',
			parameters: { username: $F('id_username'), password: $F('id_password')},
			onSuccess: processSubmitLogin, onFailure: unexpectedAJAXFailure }
	);
}

function processSubmitLogin(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		window.location = response.redirect_to;
	} else { // Failure
		$("username_errors").hide();
		$("password_errors").hide();
		for (fieldName in response.message) {
			if (fieldName == "__all__") continue;
			$(fieldName + "_errors").innerHTML = response.message[fieldName];
			$(fieldName + "_errors").show();
		}
		if (response.message.__all__) {
			$('loginMessage').innerHTML = response.message.__all__;
			$('loginMessage').show();
		} else {
			$('loginMessage').innerHTML = "";
			$('loginMessage').hide();
		}
		$('loginFormButton').enable();
	}
	$('loginFormLoading').hide();
}

// Called from the user panel to request a password change.
function changePassword() {
	$('changePasswordLoading').show();
	$('changePasswordButton').disable();
	$('changePasswordMessage').innerHTML = "";
	$('changePasswordMessage').hide();
	new Ajax.Request('/r/changepass', { method: 'post',
			parameters: { original: $F('currentPassword'),
				new_password: $F('newPassword'), confirmation: $F('newPasswordConfirmation')},
			onSuccess: processChangePassword, onFailure: function() {
					$('changePasswordButton').enable();
					$('changePasswordLoading').hide();
					unexpectedAJAXFailure();
				}
			}
	);
	return false;
}

function processChangePassword(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		alert("Your password was successfully updated.");
		$('newPassword').value = "";
		$('newPasswordConfirmation').value = "";
		$('currentPassword').value = "";
		$('changePassword').hide();
		$('changePasswordButton').enable();
	} else { // Failure
		$('changePasswordMessage').innerHTML = response.message;
		$('changePasswordButton').enable();
		$('changePasswordMessage').show();
	}
	$('changePasswordLoading').hide();
}

// Called from the user panel to request a password change.
function changeEmail() {
	$('changeEmailLoading').show();
	$('changeEmailButton').disable();
	$('changeEmailMessage').innerHTML = "";
	$('changeEmailMessage').hide();
	new Ajax.Request('/r/changeemail', { method: 'post',
			parameters: { email: $F('newEmail'), email_confirmation: $F('newEmailConfirmation')},
			onSuccess: processChangeEmail, onFailure: function() {
					$('changeEmailButton').enable();
					$('changeEmailLoading').hide();
					unexpectedAJAXFailure();
				}
			}
	);
	return false;
}

function processChangeEmail(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		$('currentEmail').innerHTML = $F("newEmail");
		alert("Your email was successfully updated.");
		$('newEmail').value = "";
		$('newEmailConfirmation').value = "";
		$('changeEmail').hide();
		$('changeEmailButton').enable();
	} else { // Failure
		$("email_errors").hide();
		$("email_confirmation_errors").hide();
		for (fieldName in response.message) {
			if (fieldName == "__all__") continue;
			$(fieldName + "_errors").innerHTML = response.message[fieldName];
			$(fieldName + "_errors").show();
		}
		if (response.message.__all__) {
			$('changeEmailMessage').innerHTML = response.message.__all__;
			$('changeEmailMessage').show();
		} else {
			$('changeEmailMessage').innerHTML = "";
			$('changeEmailMessage').hide();
		}
		$('changeEmailButton').enable();
	}
	$('changeEmailLoading').hide();
}

// Confirms the deletion and then deletes the user.
function deleteUser(userId) {
	if (!confirm("Are you sure you want to delete this user?\nThis will also delete all the reports for this user.")) {
		return;
	}
	$("deleteUserLoading_"+userId).show();
	new Ajax.Request('/r/account/delete', { method: 'post', parameters: { user_id: userId },
		onSuccess: processDeleteUser, onFailure: unexpectedAJAXFailure
	});
}

function processDeleteUser(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		window.location.reload();
	} else { // Failure
		alert(response.message);
		$("deleteUserLoading_"+response.user_id).hide();
	}
}

function deleteReport(reportId) {
	if (!confirm("Are you sure you want to delete this report?")) {
		return;
	}
	$("deleteReportLoading_" + reportId).show();
	new Ajax.Request('/r/report/delete', { method: 'post', parameters: { report_id: reportId },
		onSuccess: processDeleteReport, onFailure: unexpectedAJAXFailure
	});
}

function processDeleteReport(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		window.location.reload();
	} else { // Failure
		alert(response.message);
		$("deleteReportLoading_"+response.report_id).hide();
	}
}

function previewContentNode(fieldId) {
	$(fieldId + "_loading").toggle();
	new Ajax.Request('/r/report/delete', { method: 'post', parameters: { report_id: reportId },
		onSuccess: processDeleteReport, onFailure: unexpectedAJAXFailure
	});
}
function processPreviewContentNode(fieldId) {
	$(fieldId + "_loading").toggle();
}

function deleteTest(testId) {
	if (!confirm("Are you sure you want to delete this test?")) {
		return;
	}
	$("deleteLoading").show();
	new Ajax.Request('/r/test/delete', { method: 'post',
		parameters: { test_id: testId },
		onSuccess: processDeleteTest, onFailure: unexpectedAJAXFailure
	});
}

function processDeleteTest(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		window.location = response.nextURL;
	} else { // Failure
		alert(response.message);
		$("deleteLoading").hide();
	}
}

function deleteNews(newsId) {
	if (!confirm("Are you sure you want to delete this news item?")) {
		return;
	}
	$("deleteLoading").show();
	new Ajax.Request('/r/news/delete', { method: 'post',
		parameters: { id: newsId },
		onSuccess: processDeleteNews, onFailure: unexpectedAJAXFailure
	});
}

function processDeleteNews(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		window.location = response.nextURL;
	} else { // Failure
		alert(response.message);
		$("deleteLoading").hide();
	}
}

function deleteInstrument(id) {
	if (!confirm("Are you sure you want to delete this instrument?")) {
		return;
	}
	$("deleteLoading_" + id).show();
	new Ajax.Request('/r/instrument/delete', { method: 'post',
		parameters: { id: id },
		onSuccess: processDeleteInstrument, onFailure: unexpectedAJAXFailure
	});
}

function processDeleteInstrument(xhr) {
	var response = xhr.responseText.evalJSON();
	if (response.result == 'success') {
		window.location = response.nextURL;
	} else { // Failure
		alert(response.message);
		$("deleteLoading_" + response.id).hide();
	}
}
