/**
 * @author Rich
 */

 $(document).ready(function() {
 	keyRing.initKeys("post");
 });

 function resetPassword() {
	if ($("#password").val() != $("#confirm").val()) showMessage("error","The passwords you entered do not match.",false,"resetPassword");
	else if (keyRing.acquireKey("post"))
		$.ajax({
			url			: "/ajax_reset_password/",
			data		: {"id"					: $("#id").val(),
						   "reset_authKey"		: encode64($("#email").val()+":"+$("#pass_code").val()),
						   "password"			: ($("#password").val() == "") ? "" : MD5($("#password").val()),
						   "authenticity_token"	: $("#authenticity_token").val()},
			cache		: false,
			timeout		: TIMEOUT_LIMIT,
			type		: "POST",
			beforeSend	: function() {
				startLoading("Updating password...");
			},
			success		: function(data) {
				showMessage("warning","Your password has been reset. Redirecting to your account...",false,"resetPassword");
				setAuthKey($("#email").val(), MD5($("#password").val()),'');
				document.cookie = "email=" + $("#email").val() + "; path=/;";
				window.location = '/home'	
			},
			error		: function(xhr, type, error) {
				showMessage("error","The server encountered an error.  Please try again later.",false,"resetPassword",xhr.responseText);
				if (DEBUG) showMessage("error",xhr.status+" "+ xhr.responseText+" "+ type+" "+ error,false,"resetPassword");
			},
			complete	: function() {
				doneLoading();
				keyRing.releaseKey("post");
			}
		});
	return false;
 }
 
  function requestPasswordReset(media) {
	if (keyRing.acquireKey("post"))
		$.ajax({
			url			: "/ajax_request_password_reset/",
			data		: {"id"					: $("#id").val(),
						   "lostPasswordEmail"				: (media=="email")?$("#lostPasswordEmail").val():"",
						   "lostPasswordPhone"				: (media=="phone")?$("#lostPasswordPhone").val():"",
						   "authenticity_token"	: $("#authenticity_token").val()},
			cache		: false,
			timeout		: TIMEOUT_LIMIT,
			type		: "POST",
			beforeSend	: function() {
				startLoading("Sending password request...");
			},
			success		: function(data) {
				showMessage("warning","A link will be sent to your "+media+" very shortly.",false,"requestPasswordReset");
			},
			error		: function(xhr, type, error) {
				if (xhr.responseText != "") {
					showMessage("error", xhr.responseText,false,"requestPasswordReset",xhr.responseText);
				}else {
					showMessage("error", "The server encountered an error.  Please try again later.",false,"requestPasswordReset",xhr.responseText);
				}
				if (DEBUG) showMessage("error",xhr.status+" "+ xhr.responseText+" "+ type+" "+ error,false,"requestPasswordReset");
			},
			complete	: function() {
				doneLoading();
				keyRing.releaseKey("post");
			}
		});
	return false;
 }