// From http://developer.apple.com/internet/webcontent/xmlhttpreq.html (thank you Apple)
function getXMLHttpRequest()
{
  var o = false;
  if (window.XMLHttpRequest)
  {
    // branch for native XMLHttpRequest object
    try
    {  o = new XMLHttpRequest();  }
    catch(e)
    {  o = false;  }
  }
  else
  {
    // branch for IE/Windows ActiveX version
    if (window.ActiveXObject)
    {
      try
      {  o = new ActiveXObject("Msxml2.XMLHTTP");  }
      catch(e)
      {
        try
        {  o = new ActiveXObject("Microsoft.XMLHTTP");  }
        catch(e)
        {  o = false;  }
      }
    }
  }
  if (o)
  {
    try
    {  o.overrideMimeType('text/xml');  }
    catch (e)
    {  }
  }
  return o;
}


/* *** My background request class *** */

function BGRequest(s)
{
  this.globalName=s
  this.xmlhttp=false;
  this.timeoutInterval=10000;
  this.timeoutCheckInterval=500;
  this.rqStarted=0;
  this.intervalID=false;
  this.normalHandler=function(txt,xml) { };
  this.timeoutHandler=function() { };
  this.errorHandler=function(status) { };
  this.reentrantHandler=function() { };
  this.noXMLHttpHandler=function() { };
  return;
}

BGRequest.prototype.stopTimeoutCheck=function()
{
  if (this.intervalID)
  {
    clearInterval(this.intervalID);
    this.intervalID=false;
  }
}
  
BGRequest.prototype.checkIfTimedout=function()
{
  if (this.rqStarted>0)
  {
    if (((new Date()).getTime()-this.rqStarted)<this.timeoutInterval)
      return;
    this.stopTimeoutCheck();
    this.rqStarted=0;
    this.timeoutHandler();
    return;
  }
  this.stopTimeoutCheck();
}

BGRequest.prototype.performRequest=function(theMethod,theURL,isAsync,theData, contentType)
{
  if (this.rqStarted > 0)
  {
    this.reentrantHandler();
    return;
  }
  if (!this.xmlhttp)
    this.xmlhttp = getXMLHttpRequest();
  if (!this.xmlhttp)
  {
    this.noXMLHttpHandler();
    return;
  }
  this.xmlhttp.open(theMethod, theURL, isAsync);
  if (contentType)
  {
    if ((typeof contentType) != 'string')
      contentType = 'application/x-www-form-urlencoded';
    try
    {  this.xmlhttp.setRequestHeader('Content-Type', contentType);  }
    catch (e)
    {  }
  }
  var o = this;
  this.xmlhttp.onreadystatechange = function()
  {
    if (!o.xmlhttp)
      return;
    if (o.xmlhttp.readyState != 4)
      return;
    o.stopTimeoutCheck();
    o.rqStarted = 0;
    if (o.xmlhttp.status != 200)
    {
      o.errorHandler(o.xmlhttp.status);
      return;
    }
    o.normalHandler(o.xmlhttp.responseText,o.xmlhttp.responseXML);
    return;
  };
  this.rqStarted = (new Date()).getTime();
  this.intervalID = setInterval(this.globalName+'.checkIfTimedout()', this.timeoutCheckInterval);
  this.xmlhttp.send(theData);
  return;
}

