//Global  Variables
var m_gcRequestStatusPendingExecution = "PE";
var m_gcRequestStatusExecuting = "EX";
var m_gcRquestStatusComplete = "CO";
var STATUS_COMPLETE	= 4;
var m_gcErrorStatusText = "Error";
var m_aWritableRequests=new Array();
var m_iId=1;
var m_errWindow = null;

//Class Constructor
function clientHttpHandler()
{	// NOTE: change to use prototype
	this.processRequest = processRequest;
	this.request = request;
	this.doPost = doPost;
	this.requestReturned = requestReturned;
	this.displayError = true;
	this.processing = false;	
	this.initialiseInputXML = initialiseInputXML;
	this.buildInputXML = buildInputXML;
	this.finishInputXML = finishInputXML;
	
	function request(sUrl, httpMethod, sXml, bReadOnly, bAsynchronous,  fOnReturn, oHandler)
	{	this.id=m_iId++;
		this.url = sUrl;
		this.httpMethod = httpMethod;
		this.async = bAsynchronous;
		this.readonly = bReadOnly;
		this.callbackFunction = fOnReturn;
		this.status = m_gcRequestStatusPendingExecution;
		this.xmlHttp = null;
		this.handler = oHandler;				
		this.errorText = null;
		this.hasErrors = false;
		this.input = sXml;	
		this.alertError = null;	
		this.result = null;
	}
	
	function processRequest(sUrl, httpMethod, sXml, bReadOnly, bAsynchronous,  fOnReturn)
	{
		var oRequest = new request(sUrl, httpMethod, sXml, bReadOnly, bAsynchronous,  fOnReturn,this)
		// if writable transaction then we need to check for existing writable transactions that are still 
		// processing otherwise activity in use errors would occur
		if (!oRequest.readOnly)
		{	
			if(oRequest.async)
			{ 
				oRequest.handler.processing = true;
				m_aWritableRequests.push(oRequest)	
				processQueuedCalls();
			}
			else
			{
				if(this.processing == false) 
				{
					//then process call and return result
					doPost(oRequest);
					validateResponse(oRequest);					
					if(oRequest.hasErrors) 
					{
						returnError(oRequest);
						return false;
					}
					else 
					{						
						 requestReturned(oRequest);
					}
				}
				else
				{
					//raise an error
					alert("The Client Http Request Handler is currently processing!\n" +
						   "Please check the Processing property before initiating a Synchronous call")
				}
			}
		}
		else	// readonly call
		{	
			//NOTE: The readonly functionality will need to be implemented once Readonly activities
			//have been created.
		}
	}
	
	function processQueuedCalls()
	{
		if (m_aWritableRequests && m_aWritableRequests.length>0)
		{	// get the first instance awaiting processing...
			var oReqInstance=m_aWritableRequests[0];
			// ...and process it
			if (oReqInstance)
			{
				if(oReqInstance.status == m_gcRequestStatusPendingExecution) oReqInstance.handler.doPost(oReqInstance)
			}	
		}
		return;	
	}
	
	function returnError(oRequest)
	{
		launchErrorWindow(oRequest.xmlHttp.responseText)
		return;
	}
	
	function requestReturned(oRequest)
	{	
		oRequest.status = m_gcRquestStatusComplete;
		validateResponse(oRequest)
		if(oRequest.hasErrors) 
		{
			if(oRequest.handler.displayError == true) returnError(oRequest)
		}
		else 
		{
			//var resultText = oRequest.xmlHttp.responseText;
			oRequest.result = oRequest.xmlHttp.responseText;
			//oRequest.callbackFunction(oRequest)
		}
		
		oRequest.callbackFunction(oRequest)
		m_aWritableRequests.shift();
		processQueuedCalls();
		oRequest.handler.processing = false;
		return;
	}
	
	function validateResponse(oRequest)
	{
		if (oRequest.xmlHttp.responseText.length==0)
		{	//oRequest.errorText="No response was received from " + oRequest.url;
			//oRequest.hasErrors=true;
			//oRequest.alertError=true;
		}
		else if(oRequest.xmlHttp.StatusText == m_gcErrorStatusText)
		{	oRequest.errorText=oRequest.xmlHttp.responseText;
			oRequest.hasErrors=true;
		}
		return;
	}
	
	function doPost(oRequest)
	{		
		oRequest.status = m_gcRequestStatusExecuting;
		// prefix post page with / if not there already
		if (oRequest.url && oRequest.url.substring(0,1)!="/")
		{	oRequest.url="/" + oRequest.url;
		}
		
		// post to the page passing the parameters in the xml dom				
		//oRequest.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");	
		if (window.ActiveXObject)
		{			
			oRequest.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");	
			//oRequest.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");	
		}
		else if (window.XMLHttpRequest)
		{
			oRequest.xmlHttp = new XMLHttpRequest();
		}			
		oRequest.xmlHttp.open("POST", getApplicationUrl() + oRequest.url, oRequest.async);				
		oRequest.xmlHttp.send(oRequest.input);	
		// if this is an asynchronous call...		
		if (oRequest.async && oRequest.status!=m_gcRquestStatusComplete)
		if (oRequest.async)
		{	
			if (window.ActiveXObject)
			{		
				oRequest.xmlHttp.onReadyStateChange=new Function("handleStateChange(" + oRequest.id + ")");
			}
			else if (window.XMLHttpRequest)
			{
				oRequest.onload = handleStateChange(oRequest.id);
			}	
			
			return true;
		}
		else
		{
			return oRequest.xmlHttp.responseText;
		}
		return;
	}
	
	function initialiseInputXML(sXMLSearchString)
	{
		return("<?xml version='1.0' ?><input>");
	}

	function finishInputXML(sXMLSearchString)
	{
		sXMLSearchString+="</input>";
		var oParamXML;
		if (window.ActiveXObject)
		{
			oParamXML = new ActiveXObject("Microsoft.XMLDOM");
			oParamXML.loadXML(sXMLSearchString);
			return oParamXML;			
		}
		// code for Mozilla, etc.
		else if (document.implementation &&	document.implementation.createDocument)
		{
			var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(sXMLSearchString, 'application/xml' );
			return xmlDocument;
		}
		else
		{
			alert('Your browser cannot handle this script');
		}
				
	}

	function buildInputXML(sXMLSearchString, sSearchValue, sXMLelement)
	{
		sXMLSearchString += "<" + sXMLelement + ">" + sSearchValue + "</" + sXMLelement + ">";
		return (sXMLSearchString);
	}
}

//function getApplicationUrl()
//{	
//	if (window.location.pathname.substr(0,23) == "/GLOBET_SPORTSBOOK_HOST")
//	{
//	    if (window.location.port)
//	    {
//	        return window.location.protocol + "//" + window.location.host + "/GLOBET_SPORTSBOOK_HOST";
//	    }
//		return window.location.protocol + "//" + window.location.hostname + "/GLOBET_SPORTSBOOK_HOST";
//	}
//	else
//	{
//		return window.location.protocol + "//" + window.location.hostname;
//	}
//}

function handleStateChange(iId)
{	
	for (var i=0;i<m_aWritableRequests.length;i++)
	{	
		if (m_aWritableRequests[i].id==iId)
		{	
			var oRequest=m_aWritableRequests[i];
			if (oRequest.xmlHttp)
			{	
				if (oRequest.xmlHttp.readyState == STATUS_COMPLETE)
				{	// get the results
					oRequest.handler.requestReturned(oRequest);
					return;
				}
			}
		}
	}
	return;
}

function launchErrorWindow(sText)
{
//see if we can load the Text into a xmldom and see if we have a redirect link
	var oXML =loadXmlDom(sText);
	
	if (oXML.getElementsByTagName("Redirect").Text != "")
	{
		var sRedirect = oXML.getElementsByTagName("Redirect")[0].text;
		if (typeof(window.opener) != "undefined")
		{
				window.opener.parent.navigate(sRedirect);
				window.close();
		}
		else
		{
			window.document.location.href = sRedirect;
		}
	}		
	else
	{
		//an error has occured! 
	}
}
