(function($){
  $(document).ready(function(){
    
    // Deal with collapsable panels.
    $(':not(.accordion) > .panel.collapsable').each(function(){
      var panel = $(this);
      var header = panel.find('.header')
      header.prepend('<span class="ui-icon expand"></span>');
      var icon = header.find('.ui-icon');
      icon.show();
      header.click(function(event){
        icon.addClass('ui-collapsed');
        var body = panel.find('.body');
        if(body.is(':visible')){
          body.slideUp();
          icon.removeClass('collapse');
          icon.addClass('expand');
          if (document.location.hash != '') document.location.hash = "#_";  // Prevents page jumping
        }
        else{
          body.slideDown();
          icon.removeClass('expand');
          icon.addClass('collapse');
          
          var anchor = panel.prev('a');
          if (anchor.length > 0) {
            // Create an anchor tag link for the opened panel
            var anchorName = anchor.attr('name');
            anchor.attr('name', anchorName + '-temp'); // Prevents page jumping
            document.location.hash = "#" + anchorName;
            anchor.attr('name', anchorName);
          }
        }
      });
    });
    
    // Handle links to anchor tags
    if(window.location.hash){
      $('a[name="' + window.location.hash.substring(1) + '"]')
        .next()
          .addClass('blue')
          .find('.body')
            .show();
    }
  });
  
})(jQuery);