/**
 * A single AjaxClient instance can be used to do multiple XmlHttp requests.
 */
function AjaxClient() // Asynchronous JavaScript and XML Client
{
  var count = 0;
  var onDebug = null;
  var onError = null;

  function prv_debug(cnt,message)
  {
    if (onDebug == null) return;
    onDebug("[XMLHttp"+cnt+"] "+message);
  }

  /**
   * Send the Ajax HttpRequest. If callbackFunc is ommited, the call is
   * done synchronously and the resulting xmlHttp object is returned.
   * If a callbackFunc is provided the call is done asynchronously and
   * null is returned. The resulting xmlHttp object will be passed to the
   * specified callbackFunc. The optional userData is passed as a second
   * parameter to the callbackFunc.
   */
  this.sendHttpRequest = function(method,url,callbackFunc,userData)
  {
    return this.sendHttpRequestWithBody(method,url,null,callbackFunc,userData);
  }

  this.sendHttpRequestWithBody = function(method,url,body,callbackFunc,userData)
  {
    var xmlHttp = null;
    var reqCount = ++count;

    function stateChangeHandler()
    {
      prv_debug(reqCount,"readyState="+xmlHttp.readyState);
      if (xmlHttp.readyState == 4)
      {
        if (xmlHttp.status == 200)
        {
          prv_debug(reqCount,"OK");
          if (callbackFunc != null) callbackFunc(xmlHttp,userData);
        }
        else
        {
          prv_debug(reqCount,"Error: "+xmlHttp.status+" "+xmlHttp.statusText);
          if (onError != null) onError(xmlHttp);
        }
      }
    }

    // Get an XMLHttp Object
    if (window.ActiveXObject)
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
      xmlHttp = new XMLHttpRequest();
    else
    {
      alert("Your browser does not support the XMLHttp object");
      return;
    }
    if (callbackFunc == null) // synchronous
    {
      prv_debug(reqCount,"Sending synchronous request");
      xmlHttp.open(method,url,false);
      xmlHttp.send(body);
      return xmlHttp;
    }
    else // asynchronous
    {
      prv_debug(reqCount,"Sending asynchronous request");
      xmlHttp.open(method,url,true);
      xmlHttp.onreadystatechange = stateChangeHandler;
      xmlHttp.send(body);
    }
  }

  this.setDebugHandler = function(func)
  {
    onDebug = func;
  }

  this.setErrorHandler = function(func)
  {
    onError = func;
  }

}

function trim(string)
{
  if (string == null) return null;
  string = string.replace(/^\s*/,""); // cut leading spaces
  return string.replace(/\s*$/,""); // cut trailing spaces
}

function makeCData(string)
{
  return "<![CDATA["+string+"]]>";
}

