/**
 * AJAX communication methods.
 * Copyright 2007 by Hallwyl Software Engineering.
 * http://www.hse.dk/
 */

/**
 * Performs a HTTP POST requst to the given URL with
 * the given form-urlencoded data and lets the 
 * responseHandler handle the result.
 * If the browser does not support AJAX nothing will happen.
 */
function postRequest(url, data, responseHandler) {
  var httpRequest = getXMLHttpRequest();
  if (httpRequest == null) return;
  httpRequest.open('POST', url, true);
  httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  httpRequest.onreadystatechange = function() { requestHandler(httpRequest, responseHandler); };
  httpRequest.send(data);
}

/**
 * Performs a HTTP GET requst to the given URL
 * and lets the responseHandler handle the result.
 * If the browser does not support AJAX nothing will happen.
 */
function getRequest(url, responseHandler) {
  var httpRequest = getXMLHttpRequest();
  if (httpRequest == null) { return;}
  httpRequest.onreadystatechange = function() { requestHandler(httpRequest, responseHandler); };
  httpRequest.open('GET', url, true);
  httpRequest.send(null);      
}

/**
 * Gets the XMLHttpRequest object suitable for 
 * the client web browser.
 * Returns null, if the browser does not support XMLHttpRequest.
 */   
function getXMLHttpRequest() {
  var httpRequest = null;

  if (window.XMLHttpRequest) {
    // IE7, Mozilla, Safari, others...
    httpRequest = new XMLHttpRequest();
    
  } else if (window.ActiveXObject) { 
    // Microsoft Internet Explorer 6, 5
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    //httpRequest.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
  } 
  return httpRequest;
}

/**
 * Handles the request and calls the responseHandler if
 * all turns out well.
 */
function requestHandler(httpRequest, responseHandler) {

  // If not ready yet, just return
  if (httpRequest.readyState != 4) {
    return;
  }
  
  // If status is "200 OK" invoke responseHandler
  // else alert error code to user.
  if (httpRequest.status == 200) {
    responseHandler(httpRequest.responseXML);
  } else {
     alert('HTTP Error code' + httpRequest.status + '.');
  }
}




