
var AjaxForms = new Object()

AjaxForms.OnAjaxFailure = null
AjaxForms.ValidateForm = null
AjaxForms.UseXml = false

AjaxForms.OnSuccess = function(result){ }

AjaxForms.ParseReturnValue = function(sResponse)
{
	///The result was successful. Parse any return values:
	try {
		///HACKHERE - got to fix all this... evalJSON is stupid:
		sResponse = sResponse.replace(/(\n|\r)/g, "");
		return sResponse.evalJSON();
	} catch(e) {
		return null;
		//return {Error: e.getMessage()};
	}
}

AjaxForms.DoAjax = function(url, postBody, callback)
{
	var ajaxParams = new Object();
	ajaxParams.method = "post";
	ajaxParams.postBody = postBody

	if(typeof(callback) != "undefined")
		AjaxForms.OnSuccess = callback

    ///Show a "please wait" dialog and spin icon and disable the screen so user doesn't resubmit, etc:
    Tools.ShowMask()
    
    ///Submit the request with AJAX:
	ajaxParams.onSuccess = function(t)
	{ 
	    ///Get rid of the "please wait" masker and dialog:
        Tools.HideMask()

		if(AjaxForms.UseXml)
		{
			///See if we got XML back:
			if(t.responseXML == null)
			{
				///The server has not responsed with XML - probably this is a long, ugly HTTP error:
				AjaxForms.DisplayNotification("ErrorMessage", t.responseText, false)
				return
			}   
			
			//sResponse = t.responseXML.documentElement.innerText
			sResponse = t.responseXML.documentElement.childNodes.item(0).nodeValue        
		}
		else
			sResponse = t.responseText
		
        if(sResponse.indexOf("LOGIN:") == 0)
        {
            ///The system wants us to log in first:
			PostError("You are no longer logged into the system. Please log in to continue");
            url = sResponse.substring(("LOGIN:").length)
            document.location = url + "?targetUrl=" + encodeURIComponent(document.location)
        }
        else if(sResponse.indexOf("SUCCESS:") == 0)
        {
			sResponse = sResponse.substr("SUCCESS:".length);
			AjaxForms.OnSuccess(AjaxForms.ParseReturnValue(sResponse));
        }
        else
        {
            ///The server has responded with a nice friendly error message we should show:
            AjaxForms.DisplayNotification("ErrorMessage", sResponse)
			
			///Call user-defined callback, if any:
			if(AjaxForms.OnAjaxFailure != null)
				AjaxForms.OnAjaxFailure()
        }
	};
	
	ajaxParams.onFailure = function(t)
	{
	    ///An HTTP or even lower level error occured. Let the user decide whether they want
	    ///to retry:
	    message = "The error '" + t.statusText + "' (" + t.status + ") occured. Details are shown below. Click OK to try again or Cancel to return to the form.\r\n" + t.responseText
	    if(confirm(message))
            new Ajax.Request( AjaxForms.AjaxUrl, AjaxForms.AjaxParams );
        else
		{
	        ///Get rid of the "please wait" masker and dialog:
            Tools.HideMask()
			
			///Call user-defined callback, if any:
			if(AjaxForms.OnAjaxFailure != null)
				AjaxForms.OnAjaxFailure()
		}
	};
	
	AjaxForms.AjaxUrl = url
	AjaxForms.AjaxParams = ajaxParams
	
    new Ajax.Request( AjaxForms.AjaxUrl, AjaxForms.AjaxParams );
}

AjaxForms.AjaxUrl = ""
AjaxForms.AjaxParams = ""

///Called when the iframe loads. Not necessarily when our form has finished submitting.
AjaxForms.OnIframeLoaded = function(id) {
	
	///Get the respnose body in a way that can work on firefox and IE:
	var i = document.getElementById(id);
	if (i.contentDocument) {
		var d = i.contentDocument;
	} else if (i.contentWindow) {
		var d = i.contentWindow.document;
	} else {
		var d = window.frames[id].document;
	}
	if (d.location.href == "about:blank") {
		return;
	}
	
	///Get rid of the "please wait" masker and dialog:
	Tools.HideMask()
	
	//sResponse = d.body.innerHTML; <-- fails if the response contains anything like HTML - firefox will rewrite it sometimes.
	try {
		sResponse = window.frames[id].getResponse();
	} catch(e) { 
		sResponse = window.frames[id].document.body.innerHTML;
		AjaxForms.DisplayError(sResponse)
		return;
	}

	response = AjaxForms.ParseReturnValue(sResponse)

	if(response == null) {
		//The server has not behaved properly. Show the response as an error message:
		AjaxForms.DisplayError(sResponse)
		return;
	}

	///Success.
	AjaxForms.OnSuccess(response);
}


AjaxForms.SubmitForm = function(progressMessage, onSuccess)
{
	///Configure to show a progress message while the form submits:
	if(typeof(progressMessage) != "undefined")
		Tools.SetProgress(progressMessage)

	///Call a user function upon success:
	if(typeof(onSuccess) != "undefined")
		AjaxForms.OnSuccess = onSuccess

    ///Do any client-side validation of the form. Cancel the operation if validation fails:
    if(AjaxForms.ValidateForm != null)
        if(!AjaxForms.ValidateForm())
            return

	///Create an iframe to submit into. We don't want to use ajax because that doesn't support file uploads:
	var iframeId = 'f' + Math.floor(Math.random() * 99999);
    var containerDiv = document.createElement('DIV');
	containerDiv.innerHTML = '<iframe style="display:none" src="about:blank" id="'+iframeId+'" name="'+iframeId+'" onload="AjaxForms.OnIframeLoaded(\''+iframeId+'\')"></iframe>';
	document.body.appendChild(containerDiv);
	var iframe = document.getElementById(iframeId);
	
	///Have the form submit to the iframe:
	$('AjaxForm').setAttribute('target', iframeId);

	///Show a "loading..." masker over the page to avoid the user resubmiting or otherwise clicking things:
	Tools.ShowMask();
	
	///Have the form submit into the iframe:
	document.getElementById("AjaxForm").submit();
}

///By default post forms to a URL derived from the querystring -
AjaxForms.PostUrl = document.location


///Schedule a confirmation message to appear on the NEXT page load:
AjaxForms.PostInfo = function(message)
{
	AjaxForms.PostNotification("InfoMessage", message);
}

///Schedule a confirmation or error message to appear on the NEXT page load:
AjaxForms.PostNotification = function(className, message)
{
	Tools.SetCookie("NotifyClass", className)
	Tools.SetCookie("Notification", message)
}

///Call this once when the page loads to initialize the notification system:
AjaxForms.DisplayNotifications = function() {
	
	///If there is a message related to the last page operation, always display that first:
	if(Tools.GetCookie("Notification") != "") {
		$("Notification").innerHTML = Tools.GetCookie("Notification");
		$("Notification").className = Tools.GetCookie("NotifyClass");
		
		Tools.DeleteCookie("Notification");
		Tools.DeleteCookie("NotifyClass");
	}

	///If there is any message to display initalially on the page, display it:
	if(AjaxForms.EnterNotification != null) {
		///This really only makes sense as an error message:
		$("Notification2").innerHTML = AjaxForms.EnterNotification;
		$("Notification2").className = "ErrorMessage";
	}
}

///An optional error message to show when this page loads. Could remind user of a current problem on the
///screen they should fix, for example.
AjaxForms.EnterNotification = null

///Display a new notification IN HTML FORMAT, usually when an input validation error occurs on submit:
AjaxForms.DisplayNotification = function(className, message)
{
	///Clear any initial message being displayed:
	$("Notification2").innerHTML = "";
	$("Notification2").className = "";

	$("Notification").innerHTML = message;
    $("Notification").className = className;

	///Scroll to the top of the page so they can see the new message:
	elem = document.getElementById("Notification");
	window.scrollTo(elem.scrollLeft, elem.scrollTop);
}

AjaxForms.ClearNotification = function() {
	$("Notification").innerHTML = "";
	$("Notification").className = "";
	$("Notification2").innerHTML = "";
	$("Notification2").className = "";
}

AjaxForms.onLoad = function() {
	Ext.onReady(AjaxForms.captureInitialValues);
}

AjaxForms.captureInitialValues = function() {
	newHtml = document.createElement("div");
	for(index in $("AjaxForm").elements) {
		if(index == "item" || index == "namedItem" || index == "length") { continue; }
		
		element = $("AjaxForm").elements[index];
		
		if(element.type == "radio" && !element.checked) { continue; }
		
		if(element.type == "checkbox" && !element.checked) {
			continue;
		}
		
		prevId = "prev_" + element.name;
		if($("AjaxForm").elements[prevId] != null) {
			//already exists. Allows special inputs (like date picker) to properly handle transformations between
			//displayed and actual values.
			continue;
		}
		
		input = document.createElement("input");
		input.type = "hidden";
		input.name = prevId;
		input.value = element.value;
		newHtml.appendChild(input);
	}
	
	$("AjaxFormPrev").innerHTML += newHtml.innerHTML;
}

AjaxForms.DisplayError = function(message) {
	AjaxForms.DisplayNotification("ErrorMessage", message);
}

AjaxForms.DisplayInfo = function(message) {
	AjaxForms.DisplayNotification("InfoMessage", message);
}



