// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{ 
  // this should work for all browsers except IE6 and older
  try {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e) {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
      try { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }

  if (!xmlHttp) return false;
  else return xmlHttp;
}

function loadView(url, view, id, nav_id) {
  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)) {
    var query = url+"&ajax="+view;
    xmlHttp.open("GET", query, true);
    xmlHttp.onreadystatechange = function() { return handleViewLoad(url, view, id, nav_id); };
    xmlHttp.send(null);
  }
}

function handleViewLoad(url, view, id, nav_id) {
  // when readyState is 4, we read the server response
  if (xmlHttp.readyState == 4) {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) {    
      // read the response
      response = xmlHttp.responseText;
      if(response.length == 0) {
        // try the slow way if we got nothing
        document.location=url;
        return;
      }

      // display the data
      var view_div = document.getElementById(id);
      if(view_div) {
        view_div.innerHTML = response;
        SA_scrollToElementById(id); // scroll to the top of the div
        enableAjaxLinks(nav_id, id, view);
      }
    } 
    else {
      // try the slow way if we failed
      document.location=url;
      return;
    }
  } 
}

function enableAjaxLinks(nav_id, id, view) {
  if(!xmlHttp) return;

  nav_el = document.getElementById(nav_id);
  if(nav_el) {
    // change all the links for the nav element
    var anchors = nav_el.getElementsByTagName("a");
    for(var i = 0; i<anchors.length; i++) {
        anchors[i].href="javascript:loadView('"+anchors[i].href+"','"+view+"','"+id+"','"+nav_id+"')";
    }
  }
}
