/*
 * Http Client
 * -----------
 * Adapted from JBEL, the JavaScript Browser Extension Library.
 * Copyright (c) 2004-2005 Tim Vasil.  All rights reserved.
 * Licensed to Active Retention LLC.
 */

HttpClient.prototype.getAsText = HttpClient_getAsText;
HttpClient.prototype.getAsXml = HttpClient_getAsXml;
HttpClient.prototype._onAsyncLoad = HttpClient__onAsyncLoad;
HttpClient.prototype._sendRequest = HttpClient__sendRequest;

if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
};

function HttpClient(fAsyncLoadHandler)
{
    var objClient = this;

    this._httpObj = new XMLHttpRequest();
    this.asyncLoadHandler = fAsyncLoadHandler;
    this._httpObj.onreadystatechange = function() { objClient._onAsyncLoad(); };
    this._isXmlRequest = false;
    this.noCache = true;
    this.allowAsync = true;
    this.callbackResult = null;
}

function HttpClient__onAsyncLoad()
{
    if (this.asyncLoadHandler && this._httpObj.readyState == 4)
    {
        this.callbackResult = this.asyncLoadHandler((this._isXmlRequest) ? new XmlDoc(this._httpObj.responseXML) : this._httpObj.responseText);
    } 
}

function HttpClient_getAsText(sUri, sPayload)
{
    this._isXmlRequest = false;
    return (this._sendRequest(sUri, sPayload)) ? this._httpObj.responseText : null;
}

function HttpClient_getAsXml(sUri, sPayload)
{
    this._isXmlRequest = true;
    return (this._sendRequest(sUri, sPayload)) ? new XmlDoc(this._httpObj.responseXML) : null;
}

function HttpClient__sendRequest(sUri, sPayload)
{
	if (this.noCache)
	{
		sUri += ((sUri.indexOf('?') < 0) ? '?' : '&') + "_rand=" + CoreLib_getUniqueNumber();
	}

    with (this._httpObj)
    {
	    try
	    {
	        open((sPayload) ? 'POST' : 'GET', sUri, (this.asyncLoadHandler && this.allowAsync) ? true : false);
	        setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	        send((sPayload) ? sPayload : null);
	        return (this.asyncLoadHandler && this.allowAsync) ? false : true;
        }
        catch (e)
        {
            // Make sure the async handler gets called, even on failure (it may have cleanup processing to do)
            if (this.asyncLoadHandler) { this.callbackResult = this.asyncLoadHandler(null); }
            return false;
        }
	}
}

function defaultAsyncHandler()
{
}
