jQuery(function($) {

  if($("body").hasClass('topic')) makeTabs('#essentials');
  
  $("img[src$=.png]").addClass('png');
  
  $("#nav ul").superfish({
    autoArrows: false,
    dropShadows: false,
    speed: 0
  });
  
  /* Toggle the list of resources */
  if($('body').hasClass('resource_list')) {
    $resources = $('ul.resources');
    $controls = $('#view_controls');
    
    $('#view-grid').click(function() {
      $.cookie("view", "grid", { expires: 30 });
      $resources.removeClass('view-list').addClass('view-grid').find('>li:nth-child(3n+1)').attr('style','clear: left');
      selectItem($(this),$controls);
    });
    $('#view-list').click(function() {
      $.cookie("view", "list", { expires: 30 });
      $resources.removeClass('view-grid').addClass('view-list');
      selectItem($(this),$controls);
    });
    
    if ($.cookie("view") == 'grid') { $('#view-grid').click(); }
  }
});

/* remove a selected class from a sibling and make this selected */
function selectItem($item, $container) {
  $container.find('.selected').removeClass('selected');
  $item.addClass('selected');
}


/* Creates tabs to be used by jQuery Tools
*  Expects the following structure:
*  <div id="foo">
*    <h2>Title</h2>
*    <ul class="panes">
*      <li>
*        <h3 title="Tab Title(optional)">Pane Title</h3>
*        <div>content</div>
*      </li>
*      ...
*    </ul>
*  </div>
*/
function makeTabs(container) {
  $container = $(container);
  $content_items = $container.find('.panes > li')
  
  // Create an empty UL for the tabs
  $tabs = $container.find('h2')
                    .after('<ul class="tabs"></ul>')
                    .next('ul.tabs');
  
  // Clone the headers for each pane and add them to the tabs UL
  $tab_headers = $container.find('ul.panes h3')
                           .clone()
                           .wrapInner('<a href="#"></a>')
                           .appendTo($tabs)
                           .wrap('<li>');

  // If the header has a title, use it as the tab text
  $tab_headers.each(function() {
    var $this = $(this);
    var $a = $this.find('a');
    var tab_title = $this.attr('title');
    //$a.click(function() { return false; });
    if(tab_title != '') $a.text(tab_title);
  });      
  
  // Invoke the jQuery tools tabs
  $tabs.tabs($content_items, { effect: 'fade' });
}
