
/* loads page content dynamically. Expects page_path to be 
 * the hash with the "#" symbol stripped out 
 */
function get_page(page_path) {

  // handles anchors
  var args = page_path.split("/");
  var page_to_load = page_path;

  // handles anchors
  // anchors are formatted as "anchor/<page name>/<anchor number>"
  if (args[0] == "anchor") {
    page_to_load = args[1];
  }

  $('#main-content').css({opacity: 0.3});

  // loads page content asynchronously
  $.post('ajax/get_page.php', 
    {page:page_to_load}, function(result) {
      var data = eval('('+ result+')');

      $('#main-content').css({opacity: 1});

      // if an error occurs, display message and redirects to home
      // in a few seconds
      if (data.error != 0) {
        $('#main-content').html("<h2>" + data.error_msg + "</h2>");
        setTimeout(function(){ 
            window.location.hash = ""; 
            get_page("home");}, 2000);
      } else {

        // otherwise loads content 
        $('#main-content').html(data.content);

        // jumps to anchor, if appropriate
        if (document.getElementById(page_path) != undefined) {
          document.getElementById(page_path).scrollIntoView(true);
        } else {
          // otherwise scroll to top
          // may or may not be a good idea?
          window.scrollTo(0,0);
        }
      }
    }
  );
}

/* examines the current hash and calls get_page */
function hashChangeHandler() {
  var hash = window.location.hash;
  if (hash.length != 0 && hash != "#")
    hash = hash.substring(1);
  else
    hash = "home";

  get_page(hash);
}

function setupHashNavigation() {

  /* set up listener for hash changes for backbutton to work */
  $(window).bind('hashchange', hashChangeHandler);

  /* load default page the first time */
  hashChangeHandler();
 
}

