/* ahah.js - Asynchronous HTML over HTTP requests (AHAH)
 * $Id: ahah.js 2920 2010-01-19 13:32:42Z dave $
 *
 * Usage: ahah(url, target)
 * Where: 'url' is the URL from which to dynamically load content.
 *        'target' is the DOM node in which to insert content from 'url'.
 *
 * Requirements: Some styling for class=ahah-loading and class=ahah-error.
 *
 * Source: http://microformats.org/wiki/rest/ahah
 * Modified: Dylan Muir <dylan@ini.phys.ethz.ch>
 */

var ahahOnLoadFunction = new Function("return false;");

function ahah(url, target) {
  target.innerHTML = '<div class=ahah-loading><\/div>';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      target.innerHTML = req.responseText;
      ahahOnLoadFunction();
      /*      document.body.appendChild(document.createTextNode('Hungry'));;*/
    } else {
      target.innerHTML='<div class=ahah-error>AHAH Error:\n'+ req.status + '\n' + req.statusText + '<\/div>';
    }
  }
}

/* based on AddLoadEvent written by Simon Willson */

function addAhahLoadEvent(func) {
  var oldonload = ahahOnLoadFunction;
  if (typeof ahahOnLoadFunction != 'function') {
    ahahOnLoadFunction = func;
  } else {
    ahahOnLoadFunction = function() {
      if (oldonload) {
	oldonload();
      }
      func();
    }
  }
}

