$(document).ready(function() {
  // Building Left column category list via jquery; only showing current category tree - old: SidebarCategoryList
  var url = $("#sidebarCatsWorkarea li.current a").attr("href");
  if (url) {
    updateCategoryColumn(url, false);
  } else {
    // Hitting product detail page directly; no "current" menu item 'cause session is not set
    // Or, possibly hitting a rewritten URL for either a category page or product detail page
    url = $("#breadcrumbs a.bcItem:last").attr("href");
    if (!url) {
      url = location.pathname;
      // New: special case for gift certificates
      if ( url.indexOf('/gift-certificate-') > -1 ) {
        url = '/gift-certificates';
      }
    }
    $('#sidebarCatsWorkarea').empty();
    pixelsilk2.renderSkin({skin: '[' + '[StoreLeftCategoryFallback]' + ']', path: ""}, function(html) {
      $('#sidebarCatsWorkarea').append(html);
      updateCategoryColumn(url, true);
    });
  }
});

function updateCategoryColumn(url, addCurrent) {
  if ( $("#sidebarCatsWorkarea li a[href$='" + url + "']").length ) {
    var depth = 1;
  
    // Climb the tree to figure out what branch we're on
    var li = $("#sidebarCatsWorkarea li a[href$='" + url + "']").parent();
    //while (li.parent().get(0).className != "topCategory") {
    while ( !li.parent().hasClass("topCategory") ) {
      li = li.parent().parent();
      depth++;
    }
  
    // "li" now contains the top-level menu we're in
    if (addCurrent) { // Coming in with ALL store cats in #sidebarCatsWorkArea, need to extract current branch
      if (depth == 1) {
        li.find("> ul > li > ul").remove();
      } else {
        li.find("> ul > li > ul").each(function() {
          var html = $(this).html();
          if ( html.indexOf(url) == -1 ) {
            $(this).remove();
          }
        });
      }
    }
    $("#categoryColumn").prepend('<ul><li>' + li.html() + '</li></ul>');
  
    $("#categoryColumn li a[href$='" + url + "']").wrapInner("<strong></strong>");
    if (depth > 1) {
      li = $("#categoryColumn li a[href$='" + url + "']").parent();
      for (i = depth-1; i > 0; i--) {
        li = li.parent().parent();
        li.find("a:first").wrapInner("<strong></strong>");
      }
    }
    
    $("#categoryColumn li:first").css("border-top", "0px");
    $("#categoryColumn li:last").css("border-bottom", "1px #D2CFCA solid");
  }
}
