var request = null;
/*
 * Wrapper function for constructing a request object
 * parameters:
 * reqType:  HTTP request type (GET or POST)
 * url: URL to fetch
 * asynch: Whether to send the request asynchronously or not
 * respHandle:  Name of the function that will handle the response
 * Any fifth parameters, represented as arguments[4] are the data a POST request is
 * deisgned to take,
 */

function httpRequest(reqType, url, asynch, respHandle) {
  // Mozilla based browsers
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    if (!request) {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }

  // very unlikelu, but for completeness test for a null result
  if (request) {
    // if the reqType is post, the 5th args are POSTed data
    if (reqType.toLowerCase() != "post") {
      initReq(reqType, url, asynch, respHandle);
    }
    else {
      var args = arguments[4];
      if (args != null && args.length > 0) {
          initReq(reqType, url, asynch, respHandle, args);
      }
    }
  }
  else {
    alert("Your browser does not allow the use of the features on this page");
  }
}


/* Initialise a request object that is already constructed. */

function initReq(reqType, url, bool, respHandle) {
  try {
    /* specify the function that will handle the HTTP response */
    request.onreadystatechange=respHandle;
    request.open(reqType, url, bool);
    // If the reqType is POST then the 5th argument is the POSTed data
    if (reqType.toLowerCase() == "post") {
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      request.send(arguments[4]);
    } else {
      request.send(null);
    }
  } catch (err) {
    alert("The application cannot contact the server:" + err.message);
  }
}

