// © 2004-2006, Applied Geographics, Inc.  All rights reserved.

function ServerRequest() {
  this.xmlHttp = null;
  this.requestQueue = new Array();
  
  if (window.XMLHttpRequest) {
    try {
      this.xmlHttp = new XMLHttpRequest();
    } 
    catch (e) {}
  }
  else if (window.ActiveXObject) {
    try {
      this.xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
    }
    catch (e) {
      try {
        this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {}
    }
  }
}

ServerRequest.prototype.clearRequests = function() {
  this.requestQueue = new Array();
};

ServerRequest.prototype.processRequest = function() {
  if (this.requestQueue.length == 0) {
    return;
  }
  
  var request = this.requestQueue.shift();
  var target = this;
  
  try {
    if (request.data == null) {
      this.xmlHttp.open("GET", request.url, true);
      this.xmlHttp.onreadystatechange = function() {
        target.receiveResponse(request.errorFunction, request.responseFunction, request.responseArgument);
      };
      this.xmlHttp.send();
    }
    else {
      this.xmlHttp.open("POST", request.url, true);
      this.xmlHttp.onreadystatechange = function() {
        target.receiveResponse(request.errorFunction, request.responseFunction, request.responseArgument);
      };
      this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      this.xmlHttp.send(request.data);
    }
  }
  catch (e) {
    if (request.errorFunction != null) {
      request.errorFunction("Failed to send request via XMLHttpRequest", "Unable to communicate with server");
    }
    this.processRequest();
  }
};

ServerRequest.prototype.receiveResponse = function(errorFunction, responseFunction, responseArgument) {
  if (this.xmlHttp.readyState == 4) {
    if (this.xmlHttp.status == 200) {
      responseFunction(this.xmlHttp.responseText, responseArgument);
    }
    else if (errorFunction != null) {
      errorFunction(this.xmlHttp.statusText, this.xmlHttp.responseText, responseArgument)
    }
    
    this.processRequest();
  }
};

ServerRequest.prototype.send = function(url, data, errorFunction, responseFunction, responseArgument) {
  if (this.xmlHttp == null) {
    if (errorFunction != null) {
      errorFunction("XMLHttpRequest could not be instantiated", "Unable to communicate with server")
    }
    return;
  }
  
  this.requestQueue.push({url: url, data: data, errorFunction: errorFunction, responseFunction: responseFunction, responseArgument: responseArgument});

  if (this.xmlHttp.readyState == 0 || this.xmlHttp.readyState == 4) {
    this.processRequest();
  }
};

