/*
 * asynchttp.js
 *
 * Javascript for asynchronous HTTP calls
 *
 * Usage:
 * Create a new ServerRequest object, providing it the appropriate arguments.
 * Then invoke the send() method on the object.
 */

var net = new Object();

net.READY_STATE_COMPLETE = 4;

/**
 * url: url to which to send http request
 * method: GET or POST
 * params: request parameters as name/value string
 * onload: callback method to process the response
 * onerror: optional callback method to handle an error
 */
net.ServerRequest = function (url, method, params, onload, onerror)
{
  this.req = null;
  this.url = url;
  this.method = method;
  this.params = params;
  this.onload = onload;
  this.onerror = (onerror) ? onerror : this.defaultError;
}

net.ServerRequest.prototype.send = function()
{
  if (! this.url || !this.method) {this.onerror.call(this)};

  if (window.XMLHttpRequest) {
    this.req = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    this.req = new ActiveXObject("Microsoft.XMLHTTP");
  }

  if (this.req) {
    try {
      // this.req.onreadystatechange = net.ServerRequest.processState;  //doesn't seem to work
      var loader = this;  //seems necessary; won't work if I use 'this' in next statement
      this.req.onreadystatechange = function(){loader.processState.call(loader);};
      this.req.open(this.method, this.url, true);
      if (this.method=='POST')
        this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      this.req.send(this.params);
    }
    catch (err) {
      this.onerror.call(this);
    }
  }
}

net.ServerRequest.prototype.processState = function()
{
  var ready = this.req.readyState;
  if (ready == net.READY_STATE_COMPLETE) {
    var httpStatus = this.req.status;
    if (httpStatus == 200 || httpStatus == 0) {
      var data = this.req.responseText;
      this.onload.call(this, data);
    }
    else {
      this.onerror.call(this);
    }
  }
}

net.ServerRequest.prototype.defaultError = function()
{
  // do nothing
  //alert("error fetching data.\n"
  //      + "readyState: "+this.req.readyState+"\n"
  //      + "status: "+this.req.status+"\n"
  //      + "headers: "+this.req.getAllResponseHeaders());
}
