// $Id: nice_primary_menus.js,v 1.1.2.6 2007/11/28 22:15:06 douggreen Exp $

if (Drupal.jsEnabled) {
  var last_active_mid = 0;
  var timeout_id = 0;
  var in_switch = 0;

  function jqueryMenuSelector(mid) {
    return $('.links-menu li#menu-link-' + mid + ', .links-menu li#menu-link-' + mid + ' a');
  }

  function switchMenus(mid) {
    // handle things differently while processing the switch (jquery can be slow)
    in_switch ++;
    // change the primary menus first
    if (last_active_mid) {
      jqueryMenuSelector(last_active_mid).removeClass('active');
    }
    jqueryMenuSelector(mid).addClass('active');
    last_active_mid = mid;
    // change the secondary menus next
    $('.nice-primary-menu').hide();
    $('#nice-primary-menu-' + mid).show();
    // clear the timeout
    timeout_id = 0;
    in_switch --;
  }

  $(document).ready(function () {
    // get the initial active mid
    last_active_mid = active_mid();
    // get the top level selector
    // setup the menu li hover functions
    $('ul.links-menu li').hover( function() { 
      var mid = this.id.split('-').pop();
      // only hide this menu if there is a new menu to show
      if ($('#nice-primary-menu-' + mid).size()) {
        var wait = 0;
        if (in_switch) {
          // TODO: how do we stop the current switch
          timeout_id = setTimeout("switchMenus(" + mid + ")", 0);
        }
        else {
          switch (wait) {
            case 0: wait = 100; break; // first time
            case 100: wait = 200; break; // second time
            case 200: wait = 300; break; // third time
            default: wait = 500; break; // never wait more than half a second
          }
          timeout_id = setTimeout("switchMenus(" + mid + ")", wait);
        }
      }
    }, function() { 
      if (timeout_id) {
        clearTimeout(timeout_id)
      }
    } );
    // setup the menu ul hover functions
    $('ul.links-menu').hover( function() {
    }, function() {
      if (timeout_id) {
        clearTimeout(timeout_id)
      }
      setTimeout("switchMenus(" + active_mid() + ")", 15000);
    } );
  }); 
}
