
var AjaxForms = new Object()

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

AjaxForms.OnSuccess = function(result){ }

AjaxForms.AlertOnErrors = false;

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()

		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)
        {
            ///The result was successful. Parse any return values:
			returnValues = sResponse.substring(("SUCCESS:").length)
			returnValues = returnValues.split("&")
			returnObject = new Object()
			for(var i=0; i < returnValues.length; i++)
			{
				returnValue = returnValues[i].split("=")
				returnObject[returnValue[0]] = decodeURIComponent(returnValue[1])
				
				///HACKHERE - PHP likes to convert spaces to '+' - ASPX/etc do not...
				returnObject[returnValue[0]] = returnObject[returnValue[0]].replace(/\+/g, " ")
			}

			AjaxForms.OnSuccess(returnObject)
        }
        else
        {
            ///The server has responded with a nice friendly error message we should show:
			if(AjaxForms.AlertOnErrors)
				alert(sResponse);
            AjaxForms.DisplayNotification("ErrorMessage", sResponse, false)
			
			///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 = ""

AjaxForms.SubmitForm = function(progressMessage, onSuccess)
{
	if(typeof(progressMessage) != "undefined")
		Tools.SetProgress(progressMessage)

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

    ///Client-side validation of the form:
    if(AjaxForms.ValidateForm != null)
        if(!AjaxForms.ValidateForm())
            return
    
	if(document.getElementById("AjaxForm").enctype == "multipart/form-data")
	{
		///No good solution to posting files in this way! Will have to just submit the form.	
		Tools.ShowMask();
		document.getElementById("AjaxForm").submit();
		return;
	}
	
    ///Assemble the post:
    postBody = ""
    
    for(var i=0; i < document.getElementById("AjaxForm").elements.length; i++)
    {
        element = document.getElementById("AjaxForm").elements[i]

        ///Ignore ASP.NET automatic things:
        if(element.name == "__VIEWSTATE" || element.name == "__EVENTVALIDATION")
            continue
        
        if(element.type == "radio" && !element.checked)
            continue;
        
        if(postBody != "")
            postBody += "&"
        
        postBody += element.name + "="
        
        if(element.type == "text" || element.type == "hidden" || element.type == "password")
            postBody += escape(element.value)
        else if(element.type == "checkbox")
            postBody += (element.checked) ? "True" : "False"
        else if(element.type == "radio")
            postBody += escape(element.value)
        else
            postBody += escape(element.value)
    }

    AjaxForms.DoAjax(AjaxForms.PostUrl, postBody)
}

///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

	window.scrollTo(0, 0);
}

