var AUTHENTICATION_LOGIN_SUCCESS = 1;
var AUTHENTICATION_LOGIN_FAILED = 2;
var AUTHENTICATION_LOGOUT_SUCCESS = 3;
var AUTHENTICATION_VALIDATION_ERROR = 4;
var AUTHENTICATION_NO_USER = 5;

/**
 * Add events to Notifier
 */
Notifier.addEvents([
	'authentication_success',
	'logout_success',
]);

/**
 * Authentication class
 *
 * For managing properties.
 */
var Authentication = {};

// Static Methods

/**
 * Authenticates a user using AJAX
 *
 * The options parameter may contain the following callback functions
 * - onSuccess(message): Called when a user is successfully authenticated
 * - onFailure(message): Called when user authentication fails
 *
 * The Notifier event 'authentication_success' is raised if the user is successfully authenticated
 *
 * @param array user Hash containing the user details
 * @param element form (optional) The form containing the login fields (used for highlighting erroneous fields)
 * @param array options (optional) Callbacks
 */
Authentication.authenticateUser = function (user, form, options) {
	if (options == undefined) {
		options = {};
	}
	
	var postVars = user;
	
	new Ajax.Request ('/ajax/users/authenticate_user.php', {
		method: 'post',
		parameters: postVars,
		onSuccess: function(transport, json) {
			try {
				// Remove error class from fields previously marked as erroneous
				if ($(form)) {
					$(form).select('.error').invoke('removeClassName', 'error');
				}
				try {
					// Parse response
					var data = transport.responseText.evalJSON();
				} catch (err) {
					handleAjaxFailure(transport, json);
					if (options.onFailure != undefined) {
						options.onFailure('Your details could not be validated.');
					}
					return;
				}
				if (data.result == 'ok') {
					// Success
					if (options.onSuccess != undefined) {
						options.onSuccess(data.details);
					}
					Notifier.raise('authentication_success');
				} else {
					// Error
					switch (data.status) {
						case AUTHENTICATION_VALIDATION_ERROR:
							// Add error class to erroneous fields
							$A(data.errorfields).each(function(item) {
								var id = FormField.generateID(item);
								if ($(id)) {
									$(id).addClassName('error');
								}
							});
							break;
						case AUTHENTICATION_LOGIN_FAILED:
							break;
						default:
							// Unexpected Error
							handleAjaxFailure(transport, json);
					}
					if (options.onFailure != undefined) {
						if (data.details) {
							options.onFailure(data.details);
						} else {
							options.onFailure('Your details could not be validated.');
						}
					}
				}
			} catch (err) {
				alert ('caught error: ' + err);
			}
		},
		onFailure: function(transport, json) {
			handleAjaxFailure(transport, json);
			if (options.onFailure != undefined) {
				options.onFailure('Your details could not be validated.');
			}
		}
	});
}

/**
 * Logs out a user using AJAX
 *
 * The options parameter may contain the following callback functions
 * - onSuccess(message): Called when a user is successfully logged out
 * - onFailure(message): Called when a user cannot be logged out
 *
 * The Notifier event 'logout_success' is raised if the user is successfully logged out
 *
 * @param array options (optional) Callbacks
 */
Authentication.logoutUser = function (options) {
	if (options == undefined) {
		options = {};
	}
	
	new Ajax.Request ('/ajax/users/logout_user.php', {
		method: 'get',
		onSuccess: function(transport, json) {
			try {
				// Remove error class from fields previously marked as erroneous
				try {
					// Parse response
					var data = transport.responseText.evalJSON();
				} catch (err) {
					handleAjaxFailure(transport, json);
					if (options.onFailure != undefined) {
						options.onFailure('You could not be logged out.');
					}
					return;
				}
				if (data.result == 'ok') {
					// Success
					if (options.onSuccess != undefined) {
						options.onSuccess(data.details);
					}
					Notifier.raise('logout_success');
				} else {
					// Error
					handleAjaxFailure(transport, json);
					if (options.onFailure != undefined) {
						if (data.details) {
							options.onFailure(data.details);
						} else {
							options.onFailure('You could not be logged out.');
						}
					}
				}
			} catch (err) {
				alert ('caught error: ' + err);
			}
		},
		onFailure: function(transport, json) {
			handleAjaxFailure(transport, json);
			if (options.onFailure != undefined) {
				options.onFailure('You could not be logged out.');
			}
		}
	});
}

Authentication.validateLoginForm = function (form) {
	return true;
}