
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 {
		return sResponse.replace(/\n/g, "").evalJSON();
		//
		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
		
		retVal = AjaxForms.ParseReturnValue(sResponse);
		
        if(sResponse.indexOf("SUCCESS:") >= 0)
        {
			AjaxForms.OnSuccess(); //HACKHERE - lib is a bit messy, needs integration w/ newer projs...
        }
        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;
	}
	
	//sResponse = d.body.innerHTML;
	try {
		sResponse = window.frames[id].getResponse();
	} catch(e) { 
		sResponse = window.frames[id].document.body.innerHTML;
	}
	
	///Get rid of the "please wait" masker and dialog:
	Tools.HideMask()
	
	///Attempt to parse a json respnose:
	response = AjaxForms.ParseReturnValue(sResponse)
	
	isError = false;
	//HACKHERE - somehow, parsereturn value gives us XML when the server returns HTML... and status == xml in that case...
	if(response == null || typeof(response.status) == "undefined" || typeof(response.status) == "xml") {
		//The server has not behaved properly. Show the response as an error message:
		AjaxForms.DisplayNotification("ErrorMessage", sResponse)
		isError = true;
	} else if(response.status.match(/^error/)) {
		isError = true;
		///Valid json which represents an error occured:
		if(response.status == "error:validation") {
			///Seems the form submission failed validation. For now form a bulleted list of errors.
			///later we can insert little markers on the fields themselves a la ExtJs:
			if(response.errors.length == 1) {
				AjaxForms.DisplayNotification("ErrorMessage", response.errors[0].message);
			} else {
				message = "<ul>";
				for(var i=0; i < response.errors.length; i++) {
					message += "<li>" + response.errors[i].message + "</li>";
				}
				message += "</ul>";
				AjaxForms.DisplayNotification("ErrorMessage", message);
			}
		} else {
			///Some other error. Unfortunately just show it:
			AjaxForms.DisplayNotification("ErrorMessage", response.errorDetails);
		}
	} else if(response.status.match(/^success/)) {
		if(typeof(response.returnValue) == "undefined") {
			///Protocol errors:
			isError = true;
			AjaxForms.DisplayNotification("ErrorMessage", sResponse);
		} else {
			///Success.
			AjaxForms.OnSuccess(response);
		}
	}
	
	if(isError) {
		///Scroll to the top of the page so they can see the new message:
		elem = document.getElementById("Notification");
		window.scrollTo(elem.scrollLeft, elem.scrollTop);
		
		///Call user-defined callback, if any:
		if(AjaxForms.OnAjaxFailure != null)
			AjaxForms.OnAjaxFailure()
	}
}

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);
}

AjaxForms.ShowInfo = function(message)
{
	AjaxForms.DisplayNotification("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);
}



