/**
 * Returns a list of elements of a given class and type
 */
function getElementsByClass(searchClass,tag)
{
  var classElements = new Array() ;
  if ( tag == null ) {
    tag = '*' ;
  }
  var els = document.getElementsByTagName(tag) ;
  var elsLen = els.length ;
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)") ;
  for (i = 0, j = 0; i < elsLen; i++) {
    if ( pattern.test(els[i].className) ) {
      classElements[j] = els[i] ;
      j++ ;
    }
  }
  return classElements;
}

function init()
{
  //This function is called by default when a page loads
  if (xmlRequest()) { //die if we can't do AJAX
    //Rewrite all links in the ajax class to use the AJAXLoad function
    var AJAXLinks = getElementsByClass("ajax", "a");
    for(var i=0; i < AJAXLinks.length; i++) {
      var currentLink = AJAXLinks[i];
      var currentHref = currentLink.href;
      var currentId = currentLink.id;
      currentLink.href = "javascript:AJAXLoad('"+currentHref+".xml','"+currentId+"_target');";
    }
  }
}

function AJAXLoad(contentURL, targetID)
{
  var getRequest = new xmlRequest();
  getRequest.onreadystatechange=function() {
    var targetElement = document.getElementById(targetID);
    targetElement.innerHTML = "<img src='/static/throbber.gif' alt='loading...'>";
    if (getRequest.readyState==4) {  //request has finished
      if (getRequest.status==200) {  //request was OK
        targetElement.innerHTML=getRequest.responseText+"<p><a href='javascript:AJAXUnload(\""+targetID+"\");'>&laquo; hide</a>";
      } else {
        targetElement.innerHTML="<p>The requested resource failed to load.</p>";
      }
    }
  }
  getRequest.open("GET", contentURL, true); //load the target
  getRequest.send(null);
}

function AJAXUnload(targetID)
{
  var div = document.getElementById(targetID);
  div.innerHTML = '' ;
}

/**
 * Wrapper for XMLHttpRequest to cope with IE < 7
 */
function xmlRequest()
{
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    return false;
  }
}