/** Web root directory of the project. */
var webRoot = "";

/**
 * Perform an XMLHttpRequest using the given parameters.
 *
 * @param url         Request URI.
 * @param func        Function to call during the request.
 * @param httpMethod  HTTP method to use, "GET", "POST" or "HEAD".
 * @param body        HTTP method parameters.
 * @param headers     HTTP headers to be set.
 * @param sync        ?
 *
 * @todo              Finish documentation.
 */
ajaxRequest = function(url, func, httpMethod, body, headers, sync)
{
  this.url      = url;
  this.wState   = func       || function() { };
  this.method   = httpMethod || "GET";
  this.body     = body       || null;
  this.headers  = headers    || false;
  this.sync     = sync       || true;
  this.abortReq = false;

  this.req = (window.XMLHttpRequest)
    ? new XMLHttpRequest()
    : ((window.ActiveXObject)
      ?  new ActiveXObject("Microsoft.XMLHTTP")
      : false);

  // TODO: What does this do?
  this.doRequest = function()
  {
    this.req.open(this.method,this.url,this.sync);
    if (this.headers)
    {
      for (var i = 0; i < this.headers.length; i += 2)
      {
        this.req.setRequestHeader(
            this.headers[i],this.headers[i + 1]
        );
      }
    }

    this.req.onreadystatechange = this.wState;
    (!this.abortReq) ? this.req.send(this.body) : this.req.abort();
  }
}

/**
 * Wrapper function for ajaxRequest.
 *
 * @code
 * ajaxRequestFunc("ajaxtest.html", function(response) { alert(response); });
 * @endcode
 *
 * @param url        Request URI without the web root (added automatically).
 * @param readyFunc  Function to call when the request has been completed,
 *                   passing the responseText as the only parameter.
 * @param query      HTTP method parameters.
 * @param method     HTTP method, default: "POST".
 * @param headers    HTTP headers, default:
 *                   ["Content-Type","application/x-www-form-urlencoded"]
 * @param sync       No clue, see ajaxRequest().
 */
function ajaxRequestFunc(url, readyFunc, query, method, headers, sync)
{
  var xmlhttp = new ajaxRequest(
    webRoot + "/" + url,
    !readyFunc ? null : function()
    {
      var r = xmlhttp.req;

      // if the request is completed
      if (r.readyState == 4)
        readyFunc(r.responseText);
    },
    method ? method : "POST",
    query,
    headers ? headers : ["Content-Type","application/x-www-form-urlencoded"],
    sync
  );

  xmlhttp.doRequest();
}
