///////////-------- OLD: --------///////////
function SendRequest(RequestPage, ContentContainer)
{
    var objAjax = CreateAjaxObj();
	
	if(ContentContainer)
	{
	    // only Request content not allready fetched
	    if (ContentContainer.innerHTML == "") {
			// set the call back
		    objAjax.onreadystatechange = function() { if (objAjax.readyState == 4) { ProcessResponse(objAjax, ContentContainer); } }; 
			objAjax.open("GET", RequestPage, true);
			objAjax.setRequestHeader("Content-type", "text/xml");
			objAjax.send(null);
        }
	}
	else
	{//No callback needed
		objAjax.open("GET", RequestPage, true);
		objAjax.setRequestHeader("Content-type", "text/xml");
		objAjax.send(null);
	}
}

function ProcessResponse(objAjax, ContentContainer)
{
	//alert('function ProcessResponse(' + objAjax.responseText + ', ' + ContentContainer.innerHTML +')');
	//alert(objAjax.responseText);
	ContentContainer.innerHTML = objAjax.responseText;
	objAjax = null;
}

///////////-------- NEW: --------///////////

//////////////////////////////////////////////////////////////////////
//	function CreateAjaxObj()
//////////////////////////////////////////////////////////////////////
function CreateAjaxObj()
{
	var objAjax;	
	// for Mozilla, Firefox, Safari, and Netscape
    try
    {
        if (window.XMLHttpRequest) 
        {
            objAjax = new XMLHttpRequest();
        }
        else
        {
            objAjax = new ActiveXObject("microsoft.xmlhttp");
        }
        return objAjax;
    }
    catch(e)
    {
        alert("Your browser does not support AJAX!");
        return null;
    }
}

//////////////////////////////////////////////////////////////////////
//	function PostAjaxRequest()
//////////////////////////////////////////////////////////////////////
function PostAjaxRequest(pURL, pAsync, pHandler, pHandlerParms, pPostParms) {

    var objAjax = CreateAjaxObj();

    if (pHandler) {
        var bComplete = false;
        // set the call back
        objAjax.onreadystatechange = function() { if (objAjax.readyState == 4) { bComplete = true; pHandler(objAjax, pHandlerParms); } };
        objAjax.open("POST", pURL, pAsync);
        objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        objAjax.send(pPostParms);
        /**
        * Firefox <= 2.0.0 doesn't fire onreadystatechange for synchronous requests.
        * See http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/
        */
        var isGecko = (document.addEventListener) ? true : false;
        try {
            if (!pAsync && isGecko && !bComplete) {
                pHandler(objAjax, pHandlerParms);
            }
        } catch (e) { }
    }
    else {//No callback needed
        objAjax.open("POST", pURL, pAsync);
        objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        objAjax.send(pPostParms);
    }
}


//////////////////////////////////////////////////////////////////////
//	function SendAjaxRequest()
//////////////////////////////////////////////////////////////////////
function SendAjaxRequest(pURL, pAsync, pHandler, pHandlerParms)
{
//alert('function SendRequest(' + RequestPage + ', ' + ContentContainer.id + ')');
	var objAjax = CreateAjaxObj();

	if(pHandler)
	{
	    var bComplete = false;
	    // set the call back
	    objAjax.onreadystatechange = function() { if (objAjax.readyState == 4) { bComplete = true; pHandler(objAjax, pHandlerParms); } };
		objAjax.open("GET", pURL, pAsync);
		objAjax.setRequestHeader("Content-type", "application/xml");
		objAjax.setRequestHeader("If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT");
		objAjax.setRequestHeader("Cache-Control", "no-cache");
		objAjax.send(null);
		/**
		* Firefox <= 2.0.0 doesn't fire onreadystatechange for synchronous requests.
		* See http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/
		*/
		var isGecko = (document.addEventListener) ? true : false;
		try {
		    if (!pAsync && isGecko && !bComplete) {
		        pHandler(objAjax, pHandlerParms);
		    }
		} catch (e) { }
	}
	else
	{//No callback needed
		objAjax.open("GET", pURL, pAsync);
		objAjax.setRequestHeader("Content-type", "application/xml");
		objAjax.setRequestHeader("If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT");
		objAjax.setRequestHeader("Cache-Control", "no-cache");
		objAjax.send(null);
		if (pHandler) pHandler(objAjax, pHandlerParms);
    }
}

//////////////////////////////////////////////////////////////////////
//	function ValidateAjaxResponse()
//////////////////////////////////////////////////////////////////////
function ValidateAjaxResponse(pObjAjax)
{
//alert('function ValidateAjaxResponse();
	try
	{
		if (pObjAjax)
		{
			if(pObjAjax.status != 200)
			{//Something failed in the AJAX call when processing the request page
				//window.open("about:blank").document.write(pObjAjax.responseText);
				throw new Error('AJAX call failed:\nStatus=' + pObjAjax.status + '\nStatusText:\n' + pObjAjax.statusText+ '\n\nServer response text:\n' + pObjAjax.responseText);
				//throw new Error('AJAX call failed:\nStatus=' + pObjAjax.status + '\nStatusText:\n' + pObjAjax.statusText);
				return pObjAjax.status;
			}
		}
		else
		{//pObjAjax is invalid (null?)
			//throw new Exception('AJAX response object is invalid:\n' + pObjAjax);
			throw new Error('AJAX response object is invalid:\n' + pObjAjax);
			//throw 'AJAX response object is invalid:\n' + pObjAjax;
		}
	}
	catch(ex)
	{//Erh, what to do?
		//throw new Error('AJAX response object could not be validated:\n' + ex.message);
		throw ex;
	}
}

//////////////////////////////////////////////////////////////////////
//	function ValidateAjaxXMLResponse()
//////////////////////////////////////////////////////////////////////
function ValidateAjaxXMLResponse(pObjAjax)
{
//alert('function ValidateAjaxXMLResponse()');
	try
	{
		ValidateAjaxResponse(pObjAjax); //Will raise error if pObjAjax indicates error state
		
		//If ValidateAjaxResponse was OK then try to validate the XML
		if(pObjAjax.responseXML.parseError.errorCode != 0)
		{//The AJAX call may have went well, but the XML parser says there's something wrong with the XML
			//alert('XML parser error:\nErrorCode=' + pObjAjax.responseXML.parseError.errorCode + '\nReason:\n' + pObjAjax.responseXML.parseError.reason + '\nResponseText:\n' + pObjAjax.responseText);
			//alert('XML parser error:\nErrorCode=' + pObjAjax.responseXML.parseError.errorCode + '\nReason:\n' + pObjAjax.responseXML.parseError.reason);
			throw new Error('XML parser error:\nErrorCode=' + pObjAjax.responseXML.parseError.errorCode + '\nReason:\n' + pObjAjax.responseXML.parseError.reason);
			return pObjAjax.responseXML.parseError.errorCode;
		}
		else
		{//The AJAX call has went well and the XML parser says the XML is fine
			return 0; //Everything is OK
		}
	}
	catch(ex)
	{//Ajax response invalid
		throw ex; //Forward the exception to the caller
	}
}

//////////////////////////////////////////////////////////////////////
//	function GetDocumentElementFromAjaxXMLResponse()
//////////////////////////////////////////////////////////////////////
function GetDocumentElementFromAjaxXMLResponse(pObjAjax)
{
//alert('function GetDocumentElementFromAjaxXMLResponse()');
	try
	{
		ValidateAjaxXMLResponse(pObjAjax); //Throw error if validation fails

		return pObjAjax.responseXML.documentElement;
	}
	catch(ex)
	{
		alert(ex.message);
	}
	finally
	{
		pObjAjax = null;
	}
}

//////////////////////////////////////////////////////////////////////
//	function SetInnerHTMLFromAjaxRequest()
//////////////////////////////////////////////////////////////////////
function SetInnerHTMLFromAjaxRequest(pURL, pAsync, pElm, pOptionalCallbackMethod)
{
//alert('function SetInnerHTMLFromAjaxRequest(' + pURL + ', ' + pAsync + ', ' + pElm.id + ')');
	var objAjax = CreateAjaxObj();

	if(pElm)
	{
		SendAjaxRequest(pURL, pAsync, SetInnerHTMLFromAjaxRequestCallback, new Array(pElm, pOptionalCallbackMethod));
	}
	else
	{//Not a valid pElmID
	}
}
//////////////////////////////////////////////////////////////////////
//	function SetInnerHTMLFromAjaxRequestCallback()
//////////////////////////////////////////////////////////////////////
function SetInnerHTMLFromAjaxRequestCallback(pObjAjax, pParms)
{
	try
	{
		var tmpElm = pParms[0];

		ValidateAjaxResponse(pObjAjax); //Throw error if validation fails

		//RegistrerScriptBlocks(pObjAjax.responseText)
		tmpElm.innerHTML = pObjAjax.responseText;

		var handler = pParms[1];
		if (handler) {
			handler();
		}
	}
	catch(ex)
	{
		//alert(ex.message);
		tmpElm.innerHTML = ex.message;
	}
	finally
	{
		pObjAjax = null;
	}
}

/*
Finde an script tags in a string 
- intended for use in IE and setInnerHTML which stripts script tags
*/
function RegistrerScriptBlocks(string) {
    try {

        var re = new RegExp("(<script[^>]*/>)|(<script[^>]*>[\s\S]*?</script>)", "g");
        var matches = string.match(re);
        for (i = 0; i < matches.length; i++) {
            //alert(matches[i]);
        }
    }
    catch (e) {
    }

}


///////////-------- TESTING: --------///////////

//////////////////////////////////////////////////////////////////////
//	function TestProcessAjaxResponse()
//////////////////////////////////////////////////////////////////////
function TestProcessAjaxResponse(pObjAjax)
{
//alert('function TestProcessAjaxResponse()');
	try
	{
		var objXML, docXML;
		var i, j, tmpRowNode, tmpNode, iNodeCount, nlNodes, sMsg=""
		
		ValidateAjaxXMLResponse(pObjAjax); //Throw error if validation fails

		objXML = pObjAjax.responseXML;
		docXML = objXML.documentElement;
		
		nlNodes = docXML.getElementsByTagName("row");
		iNodeCount = nlNodes.length;
		
		sMsg = "The query:\n" + docXML.selectSingleNode("src").firstChild.nodeValue;
		sMsg += "\nproduced " + iNodeCount + " rows:\n\n";
		
		tmpRowNode = nlNodes.nextNode;
		while (tmpRowNode)
		{
			tmpNode = tmpRowNode.firstChild;
			while (tmpNode)
			{
				//alert(tmpNode.nodeName + ': ' + tmpNode.firstChild.nodeValue);
				sMsg += tmpNode.firstChild.nodeValue + "\t";
				tmpNode = tmpNode.nextSibling;
			}
			sMsg += "\n";
			tmpRowNode = nlNodes.nextNode;
		}
		alert(sMsg);
		var hWnd = window.open('about:blank');
		hWnd.document.write("<?xml version='1.0' encoding='utf-8'?>");
		hWnd.document.write(unescape(docXML.xml.replace(/\+/g," ")));
	}
	catch(ex)
	{
		alert(ex.message);
	}
	finally
	{
		pObjAjax = null;
		objXML = null;
		docXML = null;
		tmpRowNode = null;
		tmpNode = null;
	}
}

