/**
 * generalAjax.js
 *
 * Author: Jarett Creason
 * Date: April 2008
 *
 * General AJAX javascript functions used for different things
 */


/**
 * AJAX function when adding new content to a page, finds the
 * div box to create into a popup dialog, handles validation,
 * handles the submit of the form, and also what to do with the
 * return data.
 */
function addNewContentInit() {
	// Instantiate the Dialog
	AddContentDialog = new YAHOO.widget.Dialog("addContentBox",
				{ width : "500px",
					fixedcenter : true,
					visible : false, 
					draggable : true, 
					close: true, 
					constraintoviewport : true,
					buttons : [ { text:"Submit", handler:function() { this.submit(); }, isDefault:true }, 
											{ text:"Cancel", handler:function() { AddContentDialog.hide(); this.cancel(); } } ]
				 } );

	// Define the callback functions
	// These get called when the AJAX response is done
	var addContentCallbackSuccess = function(o) {
		var error = false;

		// use this to add the new user dynamically to the page
		// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call in a try catch block
		try {
			// turn the result into a JSON array (basically a JavaScript object)
			var result = YAHOO.lang.JSON.parse(o.responseText);
		} catch (e) {
			error = true;
			alert("Caught illegal JSON encode!\nInvalid JSON data returned, please contact the web administrator.\n\n"+o.responseText);
		}

		if(! error) {
			// if the userError is set, that's a problem, as is the dbError
			if((result.dbError && result.dbError != "") || (result.userError && result.userError != "")) {
				alert(result.userError);
				getObject('addContentResponse').innerHTML  = "<div class='fail'>"+result.userError+"</div>";
				getObject('addContentResponse').innerHTML += "<div class='fail'>"+result.dbError+"</div>";

			} else {
				getObject('addContentResponse').innerHTML += "<div class='success bold'>New content successfully added!<br/>(Now refreshing page...)</div>";
				window.location.reload();
			}
		}
	};
	var addContentCallbackFailure = function(o) {
		alert("Submission failed, please contact the web administrator:\n\nERROR: " + o.status);
	};
	AddContentDialog.callback = { success: addContentCallbackSuccess, failure: addContentCallbackFailure};

	// Validate the entries in the form to require that both first and last name are entered
	AddContentDialog.validate = function() {
		var data = this.getData();
		if (data.Content == "") {
			alert("Please add some text to the content text area.");
			return false;
		} else {
			AddContentDialog.hide(); 
			return true;
		}
	};

	// Render the add user box
	AddContentDialog.render();

	YAHOO.util.Event.addListener("addNewContentLink", "click", AddContentDialog.show, AddContentDialog, true);
}

/**
 * AJAX function when modifing content on a page; finds the
 * div box to create into a popup dialog, handles validation,
 * handles the submit of the form, and also what to do with the
 * return data.
 */
function modifyContentInit() {

	// Define the callback functions
	// These get called when the AJAX response is done
	modifyContentCallback = {
		success: function(o) {
			var error = false;

			// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call in a try catch block
			try {
				// turn the result into a JSON array (basically a JavaScript object)
				var result = YAHOO.lang.JSON.parse(o.responseText);
			} catch (e) {
				error = true;
				alert("Caught illegal JSON encode!\nInvalid JSON data returned, please contact the web administrator.\n\n"+o.responseText);
			}

			if(! error) {
				// if the userError is set, that's a problem, as is the dbError
				if((result.dbError && result.dbError != "") || (result.userError && result.userError != "")) {
					alert(result.userError);
					getObject('pageInfoBox').innerHTML  = "<div class='fail'>"+result.userError+"</div>";
					getObject('pageInfoBox').innerHTML += "<div class='fail'>"+result.dbError+"</div>";
				
				// success! do the action (edit or delete)
				} else {
					// update the page
					if(result.actionType == 'edit') {
						var cid = result.ContentId;
						var form = document.forms['contentForm'+cid];

						// replace texts
						form.elements['ContentTitle'].value = result.ContentTitle;
						form.elements['Content'].value = result.Content;
						getObject('ContentTitleText'+cid).innerHTML  = result.ContentTitle;
						getObject('ContentText'+cid).innerHTML = nl2br(result.Content);

						// change classes
						YAHOO.util.Dom.replaceClass('ContentTitleText'+cid, 'hidden', 'shownBlock');
						YAHOO.util.Dom.replaceClass('ContentTitleEdit'+cid, 'shownBlock', 'hidden');
						YAHOO.util.Dom.replaceClass('ContentText'+cid, 'hidden', 'shownBlock');
						YAHOO.util.Dom.replaceClass('ContentEdit'+cid, 'shownBlock', 'hidden');
						YAHOO.util.Dom.replaceClass('editLink'+cid, 'hidden', 'shownInline');
						YAHOO.util.Dom.replaceClass('restoreLink'+cid, 'shownInline', 'hidden');

						// inform user of updates
						alert('Content successfully updated!');
						getObject('contentUpdBtn'+cid).enabled;

					// hide all of that content's stuff since it's been deleted
					} else if (result.actionType == 'delete') {
						var el = getObject('ContentSurround'+result.ContentId);
						el.parentNode.removeChild(el);
						alert('Content successfully deleted!');

					// unknown type passed back, just tell the user...
					} else {
						alert('Unknown actionType coming back from AJAX request, please contact the webmaster!\n\n'+result.actionType);
					}
				}
			}
		},
		failure: function(o) {
			alert("Submission failed, please contact the web administrator:\n\nERROR: " + o.status);
		}
	};
}

/**
 * AJAX function when adding a new new user on the siteAdmin.php page; 
 * finds the div box to create into a popup dialog, handles validation,
 * handles the submit of the form, and also what to do with the
 * return data.
 */
function addUserInit() {
	// Instantiate the Dialog
	AddUserDialog = new YAHOO.widget.Dialog("addUserBox", 
				{ width : "200px",
					fixedcenter : true,
					visible : false, 
					draggable : true, 
					close: true, 
					constraintoviewport : true,
					buttons : [ { text:"Submit", handler:function() { this.submit(); }, isDefault:true }, 
											{ text:"Cancel", handler:function() { AddUserDialog.hide(); this.cancel(); } } ]
				 } );

	// Define the addUser callback functions
	// These get called when the AJAX response is done
	var addUserCallbackSuccess = function(o) {
		var error = false;

		// use this to add the new user dynamically to the page
		// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call in a try catch block
		try {
			// turn the result into a JSON array (basically a JavaScript object)
			var result = YAHOO.lang.JSON.parse(o.responseText);
		} catch (e) {
			error = true;
			alert("Invalid JSON data returned, please contact the web administrator.\n\n"+o.responseText);
		}

		if(! error) {
			// if the userError is set, that's a problem, as is the dbError
			if((result.dbError && result.dbError != "") || (result.userError && result.userError != "")) {
				alert(result.userError);
				getObject('addUserResponse').innerHTML  = "<div class='fail'>"+result.userError+"</div>";
				getObject('addUserResponse').innerHTML += "<div class='fail'>"+result.dbError+"</div>";

			} else {
				getObject('addUserResponse').innerHTML = "<div class='success'>New user successfully added!<br/>(Now refreshing page...)</div>";
				window.location.reload();
			}
		}
	};
	var addUserCallbackFailure = function(o) {
		alert("Submission failed, please contact the web administrator:\n\nERROR: " + o.status);
	};

	AddUserDialog.callback = { success: addUserCallbackSuccess, failure: addUserCallbackFailure};

	// Validate the entries in the form to require that both first and last name are entered
	AddUserDialog.validate = function() {
		var data = this.getData();
		if (data.UserName == "") {
			alert("Please enter your username.");
			return false;
		} else if (data.FirstName == "" || data.LastName == "") {
			alert("Please enter your first and last names.");
			return false;
		} else if (! checkNewPassword(data.Password, data.Password2)) {
			return false;
		} else if (! isValidEmail(data.Email)) {
			return false;
		} else {
			AddUserDialog.hide(); 
			return true;
		}
	};

	// Render the add user box
	AddUserDialog.render();

	YAHOO.util.Event.addListener("addUserLink", "click", AddUserDialog.show, AddUserDialog, true);
}

/**
 * instiate the popup box for modifying users
 */
function modifyUserPopUpInit(userName, disabled) {
	var dsblBtnTxt = "Disable";

	if(disabled != 0) {
		dsblBtnTxt = "Enable";
	}

	// Instantiate the Dialog
	ModifyUserDialog[userName] = new YAHOO.widget.Dialog("userDetails"+userName, 
				{ width : "250px",
					fixedcenter : true,
					visible : false, 
					draggable : true, 
					close: true, 
					constraintoviewport : true,
					buttons : [ { text:"Update Info",      handler:function() { this.form.doFunction.value='modifyUser'; if(validateUserUpdate(this)) {this.submit();} }, isDefault:true }, 
					            { text:dsblBtnTxt+" User", handler:function() { this.form.doFunction.value='disableUser'; if(confirm('Are you sure you want to '+dsblBtnTxt+' this user?')) {this.submit();} }}, 
					            { text:"Delete User",      handler:function() { this.form.doFunction.value='deleteUser'; if(confirm('Are you sure you want to delete this user!?')) {this.submit();} }}, 
											{ text:"Cancel",           handler:function() { ModifyUserDialog[userName].hide(); this.cancel(); } } ]
				 } );

	ModifyUserDialog[userName].callback = { success: modifyUserCallbackSuccess, failure: modifyUserCallbackFailure };

	// Validate the entries in the form to require that both first and last name are entered
	validateUserUpdate = function(dialogObj) {
		var data = dialogObj.getData();
		if (data.FirstName == "" || data.LastName == "") {
			alert("Please enter your first and last names.");
			return false;
		} else if (! isValidEmail(data.Email)) {
			return false;
		} else {
			//ModifyUserDialog[userName].hide();
			return true;
		}
	};

	// Render the modify user box
	ModifyUserDialog[userName].render();

	YAHOO.util.Event.addListener("userNameLink"+userName, "click", ModifyUserDialog[userName].show, ModifyUserDialog[userName], true);
}

/**
 * AJAX function when modifing users; finds the
 * div box to create into a popup dialog, handles validation,
 * handles the submit of the form, and also what to do with the
 * return data.
 */
function modifyUserInit() {

	// Define the callback functions
	// These get called when the AJAX response is done
	modifyUserCallbackSuccess = function(o) {
		var error = false;

		// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call in a try catch block
		try {
			// turn the result into a JSON array (basically a JavaScript object)
			var result = YAHOO.lang.JSON.parse(o.responseText);
		} catch (e) {
			error = true;
			alert("Caught illegal JSON encode!\nInvalid JSON data returned, please contact the web administrator.\n\n"+o.responseText);
		}

		if(! error) {
			// if the userError is set, that's a problem, as is the dbError
			if((result.dbError && result.dbError != "") || (result.userError && result.userError != "")) {
				getObject('addUserResponse').innerHTML  = "<div class='fail'>"+result.userError+"</div>";
				getObject('addUserResponse').innerHTML += "<div class='fail'>"+result.dbError+"</div>";
				alert(result.userError);
			
			// success! do the action (edit or delete)
			} else {
				// UPDATED USER
				if(result.actionType == 'edit') {
					// TODO - make the update show on screen
					getObject('addUserResponse').innerHTML = "<div class='success'>User successfully updated!<br/>(Now refreshing page...)</div>";
					window.location.reload();

				// DISABLED/ENABLED USER
				} else if (result.actionType == 'disable') {
					var el = getObject('UserDisabledCell'+result.UserName);
					el.innerHTML = (result.UserDisabled == 0 ? 'No' : 'Yes');
					getObject('addUserResponse').innerHTML = "<div class='success'>User successfully "+(result.UserDisabled == 0 ? 'enabled' : 'disabled')+"!</div>";

				// DELETED USER
				} else if (result.actionType == 'delete') {
					// if the user was actually deleted, 'UserDisabled' will be zero
					if(result.UserDisabled == 0) {
						var el = getObject('UserRow'+result.UserName);
						el.parentNode.removeChild(el);
						ModifyUserDialog[result.UserName].destroy();
						getObject('addUserResponse').innerHTML = "<div class='success'>User successfully deleted!</div>";

					// else, the user couldn't be deleted, but was disabled
					} else {
						var el = getObject('UserDisabledCell'+result.UserName);
						el.innerHTML = (result.UserDisabled == 0 ? 'No' : 'Yes');
						getObject('addUserResponse').innerHTML = "<div class='success'>User successfully disabled!<br/><br/>(Since this user has created pages or content in the past, we need to keep their history around, so they cannot be fully deleted from the site.  They have been disabled and all permissions they once had have been removed, which will do the trick.)</div>";
					}

				// unknown type passed back, just tell the user...
				} else {
					alert('Unknown actionType coming back from AJAX request, please contact the webmaster!\n\n'+result.actionType);
				}
			}
		}
	};

	modifyUserCallbackFailure = function(o) {
		alert("Submission failed, please contact the web administrator:\n\nERROR: " + o.status);
	};
}
