// Sets up the accordion navigation in either jQuery or Prototype depending on which
// the page has.  We are migrating from Prototype (1.5 is currently on every page
// generated by the SSI system) to jQuery (used in the CMS).

// ----- jQuery -----
if (typeof jQuery == 'function'){
  $("#navigation > ul > li").each(function(i) {
    // Wrap any initial text nodes in dummy links
    if ( jQuery.trim(jQuery(this).contents()[0].nodeValue) != "" ) {
      jQuery(jQuery(this).contents()[0]).wrap('<a href="#" />')
    }
  
    // Mark submenus
    jQuery(this).find("ul").parent().addClass("submenu");
  });

  var accordionNavs = $("#navigation > ul").accordion({
    active: false,
    header: 'li.submenu > a',
    navigation: true,
    collapsible: true,
    autoHeight: false,
    navigationFilter: function() {
      var linkHref = this.href.toLowerCase();
      var currentHref = location.href.toLowerCase();
      return (linkHref == currentHref) || (linkHref + '/' == currentHref);
    }
  });


  // Check the links against the path and set the navigation accordingly.
  var path = location.pathname;
  var nav = jQuery("#navigation > ul a").filter(accordionNavs.accordion('option', 'navigationFilter'));

  // Add the active class to the current path
  nav.addClass('active');
  
// ----- Prototype.js -----
} else if (typeof Prototype == 'object' ) {
  // If new.css applied the new look to the navigation
  if ($$('div#overlay div.nav_bar')[0].getStyle('display') == 'none') {
    // Skip wrapping initial text nodes in dummy links.  Aren't any on old pages.
  
    // Mark submenus
    $('navigation').getElementsBySelector('ul ul').each(function (s) {
      s.up('li').addClassName('submenu');
    });
  
    var accordionNav = new accordion('div#navigation', {
      classNames : {
        toggle : 'submenu',
        toggleActive : 'ui-state-active',
        content : 'accordion_content'
      }
    });
  
    function cleanPath(path) {
      return path.toLowerCase().replace(/index\.html$/, '').replace(/\.html$/, '').replace(/\/$/, '');
    }
  
    // Check the home link against the path and set the navigation accordingly.
    var path = location.pathname;
    $('navigation').getElementsBySelector('a').findAll(function(a) {
      return cleanPath(a.href).match(RegExp(cleanPath(path) + '$'));
    }).each(function(a) {
      // Add the active class to the current path
      a.addClassName('active');
      // Expand submenu if any
      var submenu = a.up('li.submenu');
      if (submenu) accordionNav.activate(submenu.down('a'));
    });
  }
}
