function AjaxResponseParser(sPrmResponse) {
	var Response = {};
	Response.Status = "";
	Response.Title = "";
	Response.Message = "";
	Response.RowsAffected = 0;
	Response.NewId = 0;
	Response.Format = "html";
	
	this.Get = Get;
	this.Set = Set;
	this.Parse = Parse;
	
	Parse(sPrmResponse);
	
	function Parse(sPrmResponse) {
		var oXml = new imod.Xml.XmlDocument(sPrmResponse);
		var oBuffer = imod.Xml.GetFEValue("status", oXml);
		if (oBuffer != null)
			Response.Status = oBuffer;
		oBuffer = imod.Xml.GetFEValue("title", oXml);
		if (oBuffer != null)
			Response.Title = oBuffer;
		oBuffer = imod.Xml.GetFEValue("message", oXml);
		if (oBuffer != null)
			Response.Message = oBuffer;
		oBuffer = imod.Xml.GetFEValue("rowsaffected", oXml);
		if (oBuffer != null)
			Response.RowsAffected = imod.General.ParseInt(oBuffer);
		oBuffer = imod.Xml.GetFEValue("newid", oXml);
		if (oBuffer != null)
			Response.NewId = imod.General.ParseInt(oBuffer);
		oBuffer = imod.Xml.GetFEValue("format", oXml);
		if (oBuffer != null)
			Response.Format = oBuffer;
	}
	
	function Get(sPrmKey) {
		return Response[sPrmKey];
	}
	
	function Set(sPrmKey, oPrmValue) {
		Response[sPrmKey] = oPrmValue;
	}
	
	/*
	function FormatTitle() {
		switch (Response.Format) {
			case "text":
				return Response.Title.replace(/\n/gi, "<br />");
			case "html":
			default:
				return Response.Title;
		}
	}
	
	function FormatMessage() {
		switch (Response.Format) {
			case "text":
				return Response.Message.replace(/\n/gi, "<br />");
			case "html":
			default:
				return this.Message;
		}
	}
	*/
}

function imod_BuildFromHtml(sPrmHtml, sPrmWrapper, oPrmTarget, bPrmExecuteScripts) {
	var o = document.createElement(sPrmWrapper);
	oPrmTarget.appendChild(o);
	o.innerHTML = sPrmHtml;

	if (bPrmExecuteScripts)
		imod_ExecuteElementScripts(o);
}

function imod_ExecuteElementScripts(o, sPrmFrame) {
	var aryScripts = o.getElementsByTagName("script");
	for (var i = 0; i < aryScripts.length; i++) {
		if (aryScripts[i].src != null && aryScripts[i].src.length > 0)
			imod_ExecuteRemoteScript(aryScripts[i].src, sPrmFrame);
		else
			imod_ExecuteScript(aryScripts[i].text, sPrmFrame);
	}
}

function imod_ExecuteScript(sPrmText, sPrmFrame) {
	var scriptNew;
	if (sPrmFrame != null && sPrmFrame.length > 0)
		scriptNew = window.frames[sPrmFrame].document.createElement("script");
	else
		scriptNew = document.createElement("script");
	scriptNew.text = sPrmText;
	if (sPrmFrame != null && sPrmFrame.length > 0) {
		window.frames[sPrmFrame].document.body.appendChild(scriptNew);
		window.frames[sPrmFrame].document.body.removeChild(scriptNew);
	}
	else {
		document.body.appendChild(scriptNew);
		document.body.removeChild(scriptNew);
	}
}

function imod_ExecuteRemoteScript(sPrmUrl, sPrmFrame) {
	var ar = new AjaxRunner();
	ar.Asynchronous = false;
	ar.Url = sPrmUrl;
	var oResponse = ar.Execute();
	if (oResponse.status == 200)
		imod_ExecuteScript(oResponse.responseText, sPrmFrame);
}

function imod_CreateXMLDocument(sPrmXML) {
	var oReturn = null;
	try {
		if (window.DOMParser != null) {
			oReturn = (new DOMParser()).parseFromString(sPrmXML, "text/xml");
		}
		else if (window.ActiveXObject != null) {
			oReturn = new window.ActiveXObject("Microsoft.XMLDOM");
			oReturn.loadXML(sPrmXML);
		}
	}
	catch (E) {
		oReturn = null;
	}
	
	/*
	if (oReturn != null) {
		oReturn.GetFirstElementValueByTagName = function (sPrmTagName) {
			var oElements = this.getElementsByTagName(sPrmTagName);
			if (oElements != null && oElements.length > 0)
				if (oElements[0] != null && oElements[0].firstChild != null)
					return oElements[0].firstChild.nodeValue;
			return "asdf";
		}
	}
	*/
	//alert(oReturn.GetFirstElementValueByTagName("asdfdsaf"));

	return oReturn;
}

function GetFE(sPrmTagName, oPrmXmlDom) {
	return GetFirstElementByTagName(sPrmTagName, oPrmXmlDom);
}

function GetFirstElementByTagName(sPrmTagName, oPrmXmlDom) {
	var oElements = oPrmXmlDom.getElementsByTagName(sPrmTagName);
	if (oElements != null && oElements.length > 0)
		if (oElements[0] != null && oElements[0].firstChild != null)
			return oElements[0];
	return null;
}

function GetFirstElementDateByTagName(sPrmTagName, oPrmXmlDom) {
	var n = GetFirstElementByTagName(sPrmTagName, oPrmXmlDom);
	if (n != null) {
		var iMonth = n.getAttribute("month");
		var iDay = n.getAttribute("day");
		var iYear = n.getAttribute("year");
		var iHour = n.getAttribute("hour");
		var iMinute = n.getAttribute("minute");
		var iSecond = n.getAttribute("second");
		if (iMonth == 1 && iDay == 1 && iYear == 1)
			return null;
		if (iMonth > 0 && iDay > 0 && iYear > 0) {
			return new Date(iYear, iMonth - 1, iDay, iHour, iMinute, iSecond);
		}
	}
	return null;
}

function GetFEValue(sPrmTagName, oPrmXmlDom) {
	return GetFirstElementValueByTagName(sPrmTagName, oPrmXmlDom);
}

function GetFirstElementValueByTagName(sPrmTagName, oPrmXmlDom) {
	//alert(sPrmTagName);
	var oElements = oPrmXmlDom.getElementsByTagName(sPrmTagName);
	if (oElements != null && oElements.length > 0)
		if (oElements[0] != null && oElements[0].firstChild != null)
			return oElements[0].firstChild.nodeValue;
	return null;
}

function AjaxRunner() {
	this.Url = "";
	this.Querystring = "";
	this.FormValue = "";
	this.SubmitMethod = "GET";
	this.ForceNoCache = true;
	this.CacheEnabled = false;
	this.Cache = {};
	this.ContentOnly = false;
	this.Finished = false;
	this.Asynchronous = true;
	//this.EnvironmentVariables = {};
	
	this.OnOpen = null; //Called when the connection is opened
	this.OnSend = null; //Called when the data is sent
	this.OnReceivePartial = null; //Called whenever partial data is received
	this.OnSuccess = null; //Called when page is completely loaded with no errors, passes a string of the response text
	this.OnFailure = null; //Called when page loads with an error like 404, 500, etc....  Passes a string of the response text and integer that is the page error code
	this.OnNotSupported = null; //Called if a XmlHttp object could not be created
	this.OnPermissionDenied = null; //Called if an error occurred because a connection could not be established
	this.OnError = null; //Called if any JS error happens.  If OnPermissionDenied is set this is event is not fired for permission denied errors.
	this.OnFinished = null; //Called after OnSuccess, OnFailure, OnError, and OnPermissionDenied. (Only one of these will fire, this is good if they all need to do the same thing like clean up an object).
	
	this.Execute = Execute;
	this.AddFormValue = AddFormValue;
		
	function Execute(sPrmKey, oPrmEventArgs) {
		//sPrmKey: if CacheEnabled then this is used to store and find cached values
		//oPrmEventArgs:  A custom object that will be passed to every event method.  This is so you can give the events access to data easily.
		//	an easy to way to use this is ArrayRunner.Execute("", {"var1": "value1", "var2": "value2"})
		//  it will always contain the object AjaxData which will encapsulate basic stuff about the AjaxRunner object at the point execute was ran
		this.Finished = false;
		var bDoIt = true;
		if (oPrmEventArgs == null)
			oPrmEventArgs = {};
		oPrmEventArgs.AjaxData = {};
		oPrmEventArgs.AjaxData.Url = this.Url;
		oPrmEventArgs.AjaxData.Querystring = this.Querystring;
		oPrmEventArgs.AjaxData.Cached = false;
		oPrmEventArgs.AjaxData.CacheKey = sPrmKey;
		if (this.CacheEnabled) {
			if (sPrmKey != null && sPrmKey.length > 0) {
				if (this.Cache[sPrmKey] != null && this.OnSuccess != null) {
					oPrmEventArgs.AjaxData.Cached = true;
					this.OnSuccess(this.Cache[sPrmKey], oPrmEventArgs);
					bDoIt = false;
					this.Finished = true;
				}
			}
		}
		if (bDoIt)
			return AjaxPost(this, sPrmKey, oPrmEventArgs, this.Asynchronous);
		return null;
	}
	
	function AddFormValue(sPrmKey, sPrmValue) {
		if (this.FormValue == null)
			this.FormValue == "";
		this.FormValue += "&" + sPrmKey + "=" + window.escape(sPrmValue);
		this.SubmitMethod = "POST";
	}
}

function AjaxPost(arData, sPrmKey, oPrmEventArgs, bPrmAsynchronous) {
	var oData = null;
	
	if (window.XMLHttpRequest) {
		//Create object for Firefox and other good browsers
		oData = new XMLHttpRequest();
	}
	else {
		//Try to create object for IE
		try {	
			oData = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) {
			oData = null;
		}
	}
	if (oData != null) {
		oData.onreadystatechange = function() {
			switch (oData.readyState) {
				case 0:  //object exists, open not called
					break;
				case 1: //open called, send not called
					if (arData.OnOpen != null)
						arData.OnOpen(oPrmEventArgs);
					break;
				case 2: //send called
					if (arData.OnSend != null)
						arData.OnSend(oPrmEventArgs);
					break;
				case 3: //partial data received
					if (arData.OnReceivePartialData != null)
						arData.OnReceievePartialData(oData.responseText, oPrmEventArgs);
					break;
				case 4: //data received
					/*
					alert(oData);
					try {
						alert(oData.status);
					}
					catch (E) {
						alert(E);
						alert(oData.responseText);
					}
					*/
					//alert("save move");
					if (oData.status == 200) {
						//alert("success");
						//Success
						var sResponseText = oData.responseText;
						if (arData.ContentOnly) {
							sResponseText = sResponseText.replace(/<form[\s\S]*?>/gi, "")
							sResponseText = sResponseText.replace(/<\/form>/gi, "");
							sResponseText = sResponseText.replace(/<input\s+[\s\S]*?name\s*=\s*"__EVENTTARGET"[\s\S]*?\/>/gi, "");
							sResponseText = sResponseText.replace(/<input\s+[\s\S]*?name\s*=\s*"__EVENTARGUMENT"[\s\S]*?\/>/gi, "");
							sResponseText = sResponseText.replace(/<input\s+[\s\S]*?name\s*=\s*"__VIEWSTATE"[\s\S]*?\/>/gi, "");
							sResponseText = sResponseText.replace(/<script\s+[\s\S]*?>\s*<!--\s*function\s+__doPostBack\(eventTarget,\s*eventArgument\)\s*\{[\s\S]*?\/\/\s*-->\s*<\/script>/gi, "");
							sResponseText = sResponseText.replace(/document.write\("[\s\S]*?"\);/gi, "");
						}
							
						if (arData.CacheEnabled && sPrmKey != null && sPrmKey.length > 0)
							arData.Cache[sPrmKey] = sResponseText;
						if (arData.OnSuccess != null) {
							arData.OnSuccess(sResponseText, oPrmEventArgs);
						}
					}
					else {
						//alert("failure");
						//Page errored
						if (arData.OnFailure != null)
							arData.OnFailure(oData.responseText, oData.status, oPrmEventArgs);
					}
					if (arData.OnFinished != null) {
						arData.OnFinished(oPrmEventArgs);
					}
					arData.Finished = true;
					//alert("end save move");
					break;
			}
		}
		try {
			var sUrl = arData.Url;
			if (arData.Querystring.length > 0) {
				sUrl += (sUrl.indexOf("?") > -1)? "&" : "?";
				sUrl += arData.Querystring;
			}
			if (arData.ForceNoCache) {
				sUrl += (sUrl.indexOf("?") > -1) ? "&" : "?";
				sUrl += Math.random();
			}
			//alert("Connecting: " + sUrl);
			oData.open(arData.SubmitMethod, sUrl, bPrmAsynchronous);
			if (arData.SubmitMethod != null && arData.SubmitMethod.toLowerCase() == "post")
				oData.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oData.send(arData.FormValue);
		}
		catch (E) {
			var sErrorMsg = (E.message) ? E.message : E;
			
			if (arData.OnPermissionDenied && sErrorMsg.indexOf("Permission denied") == 0) {
				arData.OnPermissionDenied(oPrmEventArgs);
			} 
			else {
				if (arData.OnError != null)
					arData.OnError(E, oPrmEventArgs);
				else
					throw E;
			}
			if (arData.OnFinished != null) {
				arData.OnFinished(oPrmEventArgs);
			}
			arData.Finished = true;
		}
	}
	return oData;
}


if (imod == null) imod = {};
if (imod.Xml == null) imod.Xml = {};
imod.Xml.XmlDocument = imod_CreateXMLDocument;
imod.Xml.GetFE = GetFE;
imod.Xml.GetFirstElementByTagName = GetFirstElementByTagName;
imod.Xml.GetFirstElementDateByTagName = GetFirstElementDateByTagName;
imod.Xml.GetFEValue = GetFEValue;
imod.Xml.GetFirstElementValueByTagName = GetFirstElementValueByTagName;

if (imod.Ajax == null) imod.Ajax = {};
imod.Ajax.AjaxRunner = AjaxRunner;
imod.Ajax.BuildFromHtml = imod_BuildFromHtml;
imod.Ajax.ExecuteElementScripts = imod_ExecuteElementScripts;
imod.Ajax.ExecuteScript = imod_ExecuteScript;
imod.Ajax.ExecuteRemoteScript = imod_ExecuteRemoteScript;
imod.Ajax.AjaxResponseParser = AjaxResponseParser;

/* Version 1 - no cache
function AjaxRunner() {
	this.Url = "";
	this.Querystring = "";
	this.FormValue = null;
	this.SubmitMethod = "GET";
	this.ForceNoCache = true;
	
	this.OnOpen = null; //Called when the connection is opened
	this.OnSend = null; //Called when the data is sent
	this.OnReceivePartial = null; //Called whenever partial data is received
	this.OnSuccess = null; //Called when page is completely loaded with no errors, passes a string of the response text
	this.OnFailure = null; //Called when page loads with an error like 404, 500, etc....  Passes a string of the response text and integer that is the page error code
	this.OnNotSupported = null; //Called if a XmlHttp object could not be created
	this.OnPermissionDenied = null; //Called if an error occurred because a connection could not be established
	this.OnError = null; //Called if any JS error happens.  If OnPermissionDenied is set this is event is not fired for permission denied errors.
	
	this.Execute = Execute;
	
	function Execute() {
		AjaxPost(this);
	}
}



function AjaxPost(arData) {
	var oData = null;
	if (window.XMLHttpRequest) {
		//Create object for Firefox and other good browsers
		oData = new XMLHttpRequest();
	}
	else {
		//Try to create object for IE
		try {
			oData = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) {
			oData = null;
		}
	}
	if (oData != null) {
		oData.onreadystatechange = function() {
			switch (oData.readyState) {
				case 0:  //object exists, open not called
					break;
				case 1: //open called, send not called
					if (arData.OnOpen != null)
						arData.OnOpen();
					break;
				case 2: //send called
					if (arData.OnSend != null)
						arData.OnSend();
					break;
				case 3: //partial data received
					if (arData.OnReceivePartialData != null)
						arData.OnReceievePartialData(oData.responseText);
					break;
				case 4: //data received
					if (oData.status == 200) {
						//Success
						if (arData.OnSuccess != null)
							arData.OnSuccess(oData.responseText);
					}
					else {
						//Page errored
						if (arData.OnFailure != null)
							arData.OnFailure(oData.responseText, oData.status);
					}
					break;
			}
		}
		try {
			var sUrl = arData.Url;
			if (arData.Querystring.length > 0) {
				sUrl += (sUrl.indexOf("?") > -1)? "&" : "?";
				sUrl += arData.Querystring;
			}
			if (arData.ForceNoCache) {
				sUrl += (sUrl.indexOf("?") > -1) ? "&" : "?";
				sUrl += Math.random();
			}
			oData.open(arData.SubmitMethod, sUrl, true);
			oData.send(arData.FormValue);
		}
		catch (E) {
			var sErrorMsg = (E.message) ? E.message : E;
			
			if (arData.OnPermissionDenied && sErrorMsg.indexOf("Permission denied") == 0) {
				arData.OnPermissionDenied();
			} 
			else {
				if (arData.OnError != null)
					arData.OnError(E);
				else
					throw E;
			}
		}
	}
}
*/

if (window.IModController) IModController.scriptLoadedNotification("/scripts/AjaxRunner.js");
