$(document).ready(function(){

  var COOKIE_NAME = 'sub-menu';
  var expandedIndex = $.cookie(COOKIE_NAME);
  
  //initially hide all the sub menu items
  $('#block-menu-secondary-links li.sub-menu').hide();

  //no index to retrieve
  if(expandedIndex != null){
    var listItem = $('#block-menu-secondary-links li:eq(' + expandedIndex + ')');
    listItem.show();
  }
  
  //add a class to color our list items when active page
  var highlightItem = $('a.active').parent('li');  
  highlightItem.addClass('active');
  //don't let the parent li be the active color
  $('li.sub-menu').prev('li').removeClass('active');
  
  //when a main item is clicked, expand it's sub, if a sub
  $('#block-menu-secondary-links li:not(.sub-menu, .top-menu) a').click(function(){
  //$('#block-menu-secondary-links li:not(.sub-menu, .top-menu) a').hover(function(){
  
    //get the <li> of the clicked <a>
    var listItem = $(this).parents('li:first');
    
    //see if their is a sub-menu
    var subMenu = listItem.next('li');
    if (subMenu.hasClass('sub-menu')){
    
      subMenu.children('a').removeClass('active');
    
      //get the number of sub items
      var subItems = subMenu.children('ul').children('li');

      //if there is only one drop down items, then allow the parent to take the user to the first child's destination
      if (subItems.size() == 1){
        var location = subItems.children('a').attr('href');
        window.location = location;
        return false;
      }  
    
      //expand the sub-menu
      
      
      //set or clear the expanded cookie
      if(subMenu.is(':visible')){
        subMenu.slideUp(500);
        $.cookie(COOKIE_NAME, 0);
        
      }
      else {
        $('#block-menu-secondary-links li.sub-menu').slideUp();
        subMenu.slideDown(500);
        expandedIndex = $('#block-menu-secondary-links li').index(subMenu);
        $.cookie(COOKIE_NAME, expandedIndex);
      }
      
      //cancel the normal href operation of the clicked <a>  
      return false;
            
    }
  })
  	 //
     // BUGFIX - ST - 5/14/09:
     // Fixed bug that retains the cookie after a menu has
     // been clicked on that has no child elements to slide up
     // the other menu items.  So instead of recursively looking
     // up what does and does not have a child, we clear the cookie
     // at the end of the function call
     //
     $.cookie(COOKIE_NAME, 0);
});
