//TODO Add back button support

function hashFromHref(href){
  return "#"+href.match(/\/([^\.\/]+)\.html/)[1];
}

function loadAjax(href){
  $("#mainContent>div").hide()
  var t = $(hashFromHref(href))
  if(t.length>0){
    t.show();
  }else{
    //TODO Handle AJAX Errors
  $.ajax({ url: href, success: function(data) {
    var newContent = $("<div/>").append(data).find(".mod");
    $('#mainContent').append(newContent);
    if ($("#acm").length > 0) {
      if (usersignedin) { $('img.signUp').closest('a').attr('href', '../../auccom/createaccount.aspx'); $('#signup').attr('href', '../../auccom/createaccount.aspx'); }
      if (usersignedin && hasAucComStore) { $('img.signUp').hide(); }
    }
    else {
      if (usersignedin) $('img.signUp').hide();
    }
    //change the paths of images and links for external html pages
    $('#mainContent .mod:visible img').each(function() {
      $(this).attr('src', $(this).attr('src').replace(/^\.\.\//, ''));
    });
    $('#mainContent .mod:visible a').each(function() {
      $(this).attr('href', $(this).attr('href').replace(/^\.\.\//, ''));
      $(this).removeAttr('how');
    });
  }, error: function() {
    //if ajax fails load the target page
    document.location = href;
  }, type: "GET", dataType: "html", cache: false
  });
  }
}

function loadFirst(){
  var href = $("#featuresList a:visible").removeClass("active").eq(0).addClass('active').attr("href");
  loadAjax(href);
}

$(document).ready(function() {
  var $featuresLi = $("#featuresList li");
  
  //Load state from hash
  var hash = document.location.hash;
  if (hash.length > 1) {
    var section = hash.slice(1);
    var href = "pages/" + section + ".html";
    loadAjax(href);
    $('a[href*=' + section + ']').addClass('active');
  } else { //else load the first section
    loadFirst();
  }

  $('#featuresList a').click(function() {
    $('.active').removeClass('active');
    window.location.hash = hashFromHref(this.href);
    loadAjax(this.href);
    $(this).addClass('active');
    return false;
  });
  
  //click event for links in AJAX loaded pages that link to other products (simulate a click on that section's tab in the side nav)
  $('a.products-link').live('click', function() {
    var href = this.href.match(/pages\/.+/);
    $featuresLi.find('a[href=' + href + ']').click();
    return false;
  });

  //Filter navigation
  $("#featuresNav a").click(function(){
    $('#featuresNav li').removeClass('on');
    $(this).parent().addClass('on');
    $featuresLi.show();
    if(this.hash != "#showall"){
      $featuresLi.hide();
      $featuresLi.filter("."+this.hash.slice(1)).show();
    }
    loadFirst();
    return false;
  });
});