/*global jQuery, $ */
/*jslint browser: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true */
/**
 * This file contains the code necessary to handle generic CMS Admin functions
 * and is a jQuery based replacement of the Ext version
 */

/**
 * Prepares the User Profile Window to be used, registering a click event on the objTrigger argument to actually open the window.
 * 
 * @param element objTrigger The element on the page that will trigger the window to appear.
 * @param object  options    An object specifying additional config options.
 *                           Currently supported options (keys) include:
 *                            * data (Optional) A string of encoded data to be
 *                                              included in the POST
 * @return jQuery object
 */
function setupUserProfileWindow(objTrigger, options) {
	/**
	 * 
	 *
	 * @param array data
	 * @param string textStatus
	 * @return bool
	 */
	function onProfileLoad(data, textStatus) {
		var obj_response,
			inputs = ['name', 'fname', 'lname', 'email', 'phone'],
			i;

		if (data === undefined) {
			alert("Your profile information could not be retrieved.");
			return;
		}

		try {
			if (typeof JSON === 'undefined' || typeof JSON.parse !== 'function') {
				obj_response = eval('(' + data + ')');
			} else {
				obj_response = JSON.parse(data);
			}
		} catch (e) {
			alert("Your profile information could not be retrieved.");
			return;
		}
		
		if (!obj_response.success) {
			alert("Your profile information could not be retrieved. The following errors occurred:\n" +
					obj_response.errors.reason);
			return;
		}
		
		for (i = 0; i < inputs.length; i += 1) {
			$('input[name="' + inputs[i] + '"]').val(obj_response.data[inputs[i]]);
		}
	}
	
	/**
	 * 
	 *
	 * @param array data
	 * @param string textStatus
	 * @return bool
	 */
	function onProfileSave(data, textStatus) {
		var obj_response;

		if (data === undefined) {
			alert("Your profile information could not be saved.");
			return false;
		}

		try {
			if (typeof JSON === 'undefined' || typeof JSON.parse !== 'function') {
				obj_response = eval('(' + data + ')');
			} else {
				obj_response = JSON.parse(data);
			}
		} catch (e) {
			alert("Your profile information could not be saved.");
			return false;
		}
		
		if (!obj_response.success) {
			alert(obj_response.errors.reason);
			return false;
		}
		
		alert("Your profile has been updated.");
		return true;
	}
	
	$('#itr_userprofile').dialog({
		title: 'Update My Account',
		modal: true,
		autoOpen: false,
		width: 300,
		position: ['center', 70],
		dialogClass: 'itr_cms',
		resizable: false,
		open: function () {
			var extraData = "";
			if (options && (typeof options.dataProvider === "function")) {
				extraData = '&' + options.dataProvider();
			}
			
			// load the data using AJAX
			$.ajax({
				type:	"POST",
				url:	"/admin/modules/user/user.php",
				data:	"response_mode=ajax&action=getUserProfile" + extraData,
				success: onProfileLoad
			});
		}
	});
	
	$('#itr_userprofile').find('.button.submit').click(function () {
		$('#itr_userprofileform').ajaxSubmit({
			type: "POST",
			success: function (data, text) {
				if (onProfileSave(data, text)) {
					$('#itr_userprofile').dialog('close');
				}
			}
		});
		
		return false;
	});
	$('#itr_userprofile').find('.button.cancel').click(function () {
		$('#itr_userprofile').dialog('close');
		return false;
	});
	
	//Open the dialog when clicking the trigger button
	$(objTrigger).click(function () {
		$('#itr_userprofile').dialog('open');
		return false;
	});
	
	return $('#itr_userprofile');
}

$(document).ready(function () {
	$('a#user-account').add('a.user-account').one('click', function (evt) {
		var w;
		try {
			w = setupUserProfileWindow(this);
			w.dialog('open');
		} catch (e) {
		}
		
		evt.preventDefault();
		return false;
	});
});

