$(function() {

  // Load content on hash change
  $(window).hashchange( function() {
    var hash = location.hash;
    var content = hash.replace(/^#/, '');
    if (content.length > 0) {

      var parts = content.split(":");
      var context = parts[0];
      var id = parts[1];

      var paramStr = window.location.href.slice(window.location.href.indexOf('?') + 1);
      var url = "index.php?context=" + context + "&id=" + id + "&" + paramStr;
      loadContent(url);
      window.scrollTo(0, 0);
    }
    else {
      replaceText($("#left").html());
    }
  })
  
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).hashchange();  
});

/**
 * Load 
 */
function loadContent(url) {
  showLoading("text");
  $.ajax({
    url: url,
    success: function(content) {
      replaceText(content);
      
      // call the loadCallback function if it is defined
      if (loadCallback instanceof Function) {
        loadCallback();
      }
    }
  });
}

function replaceText(content) {
  $("#left").after('<div id="left">'+content+'</div>').remove(); 
}

function showLoading() {
  replaceText('Loading...');
}

function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}
