/* ajax.js
   
   This file is part of arena.

   arena is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 3 of the License or, at your
   option, any later version.

   arena is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLITY
   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
   License for more details.

   You should have received a copy of the GNU General Public License along
   with arena.  If not, see <http://www.gnu.org/licenses/>.
*/

/* This file defines a utility class for working with AJAX requests.
*/


// Generic HTTP request object; uses AJAX to make an HTTP request
AnAjaxRequest = function(method, mimeType) {
  // Establish properties
  this.method = method;
  this.url = "";
  this.queryString = "";
  this.callback = false;
  this.caller = false;

  // This object holds the HTTP request object
  this.request = false;
  if (mimeType == "") mimeType = "text/xml";

  // Create the HTTP request object (Mozilla, etc.)
  if (window.XMLHttpRequest) {
    this.request = new XMLHttpRequest();
    if (this.request.overrideMimeType) this.request.overrideMimeType(mimeType);
  }

  // Internet Explorer
  else if (window.ActiveXObject) {
    try {
      this.request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
      try {
        this.request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {}
    }
  }
  // If we were unable to construct the request object, return nothing
  if (!this.request) 
    return(false);
  return this;
}

subclass(AnAjaxRequest, AnObject);

// Sends the request; if 'blocking' is true, the call will block until the
// server responds; otherwise, communication is asynchronous.
AnAjaxRequest.prototype.send = function(blocking) {
  if ((this.url == "") || (this.method == "")) 
    return(false);

  // Make the request
  callback = this.callback;
  this.request.onreadystatechange = this.callback;
  if ((this.method == "GET") && (this.queryString != ""))
    this.url += "?" + encodeURI(this.queryString);

  this.request.open(this.method, this.url, (blocking != true));
  
  if (this.method == "POST") {
    this.request.setRequestHeader("Content-Type", 
      "application/x-www-form-urlencoded");
    this.request.send(this.queryString);
  }
  else 
    this.request.send(null);
  //alert("Sent: " + this.method + " " + this.url);
  return(true);
}

