/**
 * Copyright (c) 2008 MiEnterprise Pty Ltd. All rights reserved.
 */

	successDisplayPeriod = 500;

	function sendAdminUpdate(action, params, onSuccessFunction, onCompleteFunction, options)
	{
		sendUpdate('admin', action, params, onSuccessFunction, onCompleteFunction, options);
	}	
	
	function sendMembersUpdate(action, params, onSuccessFunction, onCompleteFunction, options, onAjaxErrorFunction)
	{
		sendUpdate('members', action, params, onSuccessFunction, onCompleteFunction, options, onAjaxErrorFunction);
	}	

	function sendCommonUpdate(action, params, onSuccessFunction, onCompleteFunction, options)
	{
		sendUpdate('common', action, params, onSuccessFunction, onCompleteFunction, options);
	}	
	
	function sendPublicMemberUpdate(action, params, onSuccessFunction, onCompleteFunction, options)
	{
		sendUpdate('publicmember', action, params, onSuccessFunction, onCompleteFunction, options);
	}	

	function sendUpdate(role, action, params, onSuccessFunction, onCompleteFunction, options, onAjaxErrorFunction)
	{		
		var isAsynchronous = (options != null && options.asynchronous != null) ? options.asynchronous : true;
		var postMethod = (options != null && options.method != null) ? options.method : 'post';
		var isSpinner = (options != null && options.spinner != null) ? options.spinner : true;
		var isProcessing = (options != null && options.processing != null) ? options.processing : false;
		var displaySuccess = (options != null && options.displaySuccess != null) ? options.displaySuccess : true;
		var successDisplayPeriod = (options != null && options.successDisplayPeriod != null) ? options.successDisplayPeriod : 500;
		
		if (isSpinner)
		{
			displaySpinner();
		}
		
		if (isProcessing)
		{
			displayProcessing();
		}
		
		if(role == 'admin'){
			role = 'members/admin';
		}
		
		try {
			new Ajax.Request('/' + role + '/Ajax?doAction=' + action,
			{
				method: postMethod,
				asynchronous: isAsynchronous,
				parameters: params,
				onSuccess: function(transport)
					{
						removeSpinner();
						if (hasErrors(transport))
						{
							if (isProcessing) {
								processAjaxErrors(transport, onAjaxErrorFunction);
							} else {
								processErrors(transport);
							}
						}
						else
						{
							processSuccess(displaySuccess, successDisplayPeriod, onSuccessFunction, transport);
						}
						if (onCompleteFunction != null)
						{
							onCompleteFunction(transport);
						}
					},
				onFailure: function(transport)
					{
						removeSpinner();
						processFailure(transport);
					}
			});
		}
		catch (e)
		{
			removeSpinner();
			alert("An exception has occurred - " + e.message);
		}
	}
	
	function displaySpinner()
	{
		if ($('spinnerDiv') == null)
		{
			var spinnerDiv = document.createElement("div");
			spinnerDiv.setAttribute('id','spinnerDiv');
			spinnerDiv.innerHTML = '<img border="0" src="/icons/spinner.gif"></img>';		
			document.body.appendChild(spinnerDiv);
		}
		setInitialFramePosition($('spinnerDiv'));
		$('spinnerDiv').show();
		return;
	}
	
	function displayProcessing()
	{
		if ($('kbExInfo') == null)
		{
			var spinnerDiv = document.createElement("div");
			spinnerDiv.setAttribute('id','kbExInfo');
			spinnerDiv.setAttribute('class','kbProcess');
			spinnerDiv.innerHTML = '<img src="/product/SEImages/spinnerBig.gif" width="110" height="110" />';		
			document.body.appendChild(spinnerDiv);
		}
		
		$('kbExInfo').show();
		
		return;
	}
	
	function removeSpinner()
	{
		if ($('spinnerDiv') != null)
		{
			$('spinnerDiv').hide();
		}
		
		if ($('kbExInfo') != null)
		{
			$('kbExInfo').hide();
		}
	}
	
	function doWithSpinner(action)
	{	
		actionFunction = function()
		{
			try {
				action();
				removeSpinner();
			}
			catch(e)
			{
				removeSpinner();
			}
		}
		displaySpinner();
		setTimeout("actionFunction()", 0);
	}
	
	function hasErrors(transport)
	{
		var errors = getFromTransport(transport,"Error");
		return errors != null && errors.length > 0;
	}

	function processErrors(transport)
	{
		var errorContent = "";
		var xmlDoc;
		var frame;

		var errors = getFromTransport(transport,"Error");

		$('successFrame').hide();
		$('errorFrame').hide();		
		
		if (errors !== null && errors.length > 0)
		{
			if (errors.length > 0)
			{
				var cellModifiedDisplayed = false;
				errorContent = errorContent + "<table>";
				for (var i=0; i<errors.length; i=i+1) {
					
					var error = errors[i];
					var errorText = getTagContent(error, "ErrorText");
					var formKey = getTagContent(error, "FormKey");
					var cellId = getTagContent(error, "CellId");
					
					if (formKey == "cellModifiedError" && cellModifiedDisplayed)
					{
						continue;
					}
					errorContent = errorContent + "<tr><td width='30px'><img height='18px' src='/icons/alert_fail.gif' border='0'/></td><td>";
					
					if (formKey == "pageError")
					{
						errorContent = errorContent + errorText;
					}
					else if (formKey == "cellError" && cellId != null)
					{
						errorContent = errorContent + "<td><a href=\"javascript:selectCell('" + cellId + "');\">" + errorText + "</a>";
					}
					else if (formKey == "cellModifiedError" && cellId != null && !cellModifiedDisplayed)
					{
						errorContent = errorContent + "<td><a href=\"javascript:window.location.reload();\">" + errorText + "</a>";
						cellModifiedDisplayed = true;
					}
					else
					{
						errorContent = errorContent + "<td><a href=\"javascript:gotoField('" + formKey + "');\">" + errorText + "</a>";
					}
					errorContent = errorContent + "</td></tr>";
				}
				errorContent = errorContent + "</table>";
				errorContent = errorContent + "<br>"
			}
			
			frame = $('errorFrame');
			$('errorFrameContent').innerHTML = errorContent;
		}
		setInitialFramePosition(frame);
		frame.show();
	}
	
	function removeWarnings()
	{
		if ($('kbWarningInfo') != null)
		{
			$('kbWarningInfo').remove();
		}
	}
	
	function processAjaxErrors(transport, onAjaxErrorFunction) 
	{
		removeWarnings();
		var callBackStr = '';
		if (onAjaxErrorFunction != null) {
			callBackStr = onAjaxErrorFunction + '()';
		}
		
		var html = '<div id="kbExInfoTp"><a href="javascript:removeWarnings(' + callBackStr + ');" class="closeBt"><img src="/product/SEImages/warnCloseBt.png" alt="Close" width="102" height="41" border="0" /></a></div>' +
			'<div id="kbExInfoBod"><img src="/product/SEImages/warningTri.png" width="45" height="43" border="0" class="warnTri" />';

		var errors = getFromTransport(transport,"Error");	
		if (errors !== null && errors.length > 0)
		{
			for (var i=0; i < errors.length; i=i+1) {
				
				var error = errors[i];
				var errorText = getTagContent(error, "ErrorText");
				var formKey = getTagContent(error, "FormKey");
				var cellId = getTagContent(error, "CellId");
				var additionalText = getTagContent(error, "AdditionalText");
				if (additionalText != null && additionalText != '') {
					errorText = additionalText + errorText;
				}
				
				html = html + '<p>' + errorText + '</p>';
			}
		}
		
		html = html + '</div><div id="kbExInfoBt"></div>';
		
		var errorDiv = document.createElement("div");
		errorDiv.setAttribute('id','kbWarningInfo');
		errorDiv.setAttribute('class','kbWarning');
		errorDiv.innerHTML = html;		
		document.body.appendChild(errorDiv);
				
		$('kbWarningInfo').show();
	}

	function getFromTransport(transport, tagName)
	{
		var xmlResponse=transport.responseXML;	
		if (xmlResponse != null)
		{
			xmlDoc=xmlResponse.documentElement;
			if (xmlDoc != null)
			{
				return getFromRootNode(xmlDoc, tagName);
			}
		}
		return new Array();
	}
	
	function getSingleTagFromTransport(transport, nodeName)
	{
		var node = getFromTransport(transport, nodeName);
		if (node.length > 0)
		{
			return node[0].firstChild.nodeValue;
		}
		return null;
	}
	
	function getFromRootNode(rootNode, tagName)
	{
		if (rootNode != null)
		{
			return rootNode.getElementsByTagName(tagName);
		}
		return new Array();
	}
	
	function getTagContent(rootElement, name)
	{
		var formKeys = rootElement.getElementsByTagName(name);
		if (formKeys != null && formKeys.length == 1)
		{
			if (formKeys[0].firstChild == null)
			{
				return "";
			}
			
			var retVal = formKeys[0].firstChild.nodeValue;
			if (retVal == null) {
				retVal = "";
			}
			
			return retVal;
		}
		
		return "";
	}

	function processSuccess(displaySuccess, time, onSuccessFunction, transport)
	{
		if (displaySuccess)
		{
			try {
				$('errorFrame').hide();
				var frame = $('successFrame');
				setInitialFramePosition(frame);
				setTimeout("$('successFrame').fade();", time);
				frame.show();
			} catch (e) {}
		}
		if (onSuccessFunction != null)
		{
			onSuccessFunction(transport);
		}
	}
	
	function setInitialFramePosition(frame)
	{
		if (frame.style.top == null || frame.style.top == '')
		{
			frame.style.position = "fixed";
			frame.style.top = '50%';
			frame.style.left = '50%';
			frame.style.zIndex = '10000';
		}
	}
	
	function setInitialFailureFramePosition(frame)
	{
		if (frame.style.top == null || frame.style.top == '')
		{
			frame.style.position = "fixed";
			frame.style.top = '100px';
			frame.style.zIndex = '10000';
		}
	}
	
	function processFailure(transport)
	{		
		$('successFrame').hide();
		$('errorFrame').hide();
		
		if (transport.status == 401)
		{
			// force a reload, this will redirect to the logic page
			window.location.reload();
			return;
		}
		
		var frame = $('failureFrame');
		
		var exceptionError = getExceptionError(transport);
		
		var errorMessageSpan = $('errorMessage');
		if (errorMessageSpan != null)
		{
			errorMessageSpan.innerHTML = getErrorMessage(exceptionError);	
		}
			
		var stackFrame = $('failureFrameStackContent');
		if (stackFrame != null)
		{
			stackFrame.innerHTML = getStackContent(exceptionError);	
		}
		
		var requestUID = $('requestUID');
		if (requestUID != null)
		{
			requestUID.innerHTML = getRequestUID(exceptionError);	
		}
		
		setInitialFailureFramePosition(frame);	
		frame.show();
	}
	
	function getExceptionError(transport)
	{
		var errors = getFromTransport(transport,"ExceptionError");
		if (errors != null && errors.length == 1)
		{
			return errors[0];
		}
		return null;
	}
	
	function getErrorMessage(exceptionError)
	{
		if (exceptionError != null)
		{
			return getTagContent(exceptionError, 'ErrorMessage');
		}
		return 'Error message not available';
	}
	
	function getStackContent(exceptionError)
	{
		if (exceptionError != null)
		{
			return '<center><textarea rows="15" cols="108" readonly="readonly">' + getTagContent(exceptionError, 'ErrorTrace') + '</textarea></center>';
		}
		return 'Stack trace not available';
	}
	
	function getRequestUID(exceptionError)
	{
		if (exceptionError != null)
		{
			return getTagContent(exceptionError, 'RequestUID');
		}
		return 'RequestUID not available';
	}
	
	function gotoField(fieldName)
	{
		var fields = document.getElementsByName(fieldName);
		if (fields.length > 0)
		{
			fields[0].focus();
			Effect.Pulsate(fields[0], {duration: 1});
		}
	}
	
	function modalboxIsDisplayed()
	{
		try {
			return Modalbox.initialized;
		}
		catch (error)
		{}	
		return false;
	}

