$(function()
{
  $("ul#sections").customMenu();
});

jQuery.fn.customMenu = function()
{
  if (jQuery.fn.customMenu.instance != null)
    return jQuery.fn.customMenu.instance;
    
  jQuery.fn.customMenu.instance = this;
  this.selected = null;
  this.opened = true;
  
  this.normalize = function()
  {
    if (this.opened)
      window.setTimeout("jQuery.fn.customMenu.instance.normalize()", 2000);
    else
      this.closeSubMenu();
  }
  
  this.closeSubMenu = function()
  {
    this.showSubMenu(this.selected);
  }

  this.showSubMenu = function(parent)
  {
    var container = $("#sub-section-container");
    if (parent == null)
    {
      container.empty();
      return;
    }
    var sub = parent.find(".sub-sections");
    if (sub.size() > 0)
      container.html("<ul class='sub-sections'>" + sub.html() + "</ul>");
    else
      container.empty();
    this.open();  
    $('li', '#sub-section-container').hover(
      this.open,
      this.close
    );
  }
  
  this.open = function()
  {
    jQuery.fn.customMenu.instance.opened = true;
  }
  
  this.close = function()
  {
    jQuery.fn.customMenu.instance.opened = false;
  }
  
  /**
   * Constructor
   */
  this.children("li").each(function(i)
  {
    var $this = $(this);
    if ($this.is('.selected'))
      jQuery.fn.customMenu.instance.selected = $this;
    else if (jQuery.fn.customMenu.instance.selected == null)
      jQuery.fn.customMenu.instance.selected = $this;
      
    var anchor = $this.children('a');
    anchor.hover(
      customMenu_onover,
      customMenu_onout);
  }); 
  this.showSubMenu(this.selected);
  
  return this;
}
jQuery.fn.customMenu.instance = null;

function customMenu_onover()
{
  jQuery.fn.customMenu.instance.showSubMenu($(this).parent());
}

function customMenu_onout()
{
  jQuery.fn.customMenu.instance.close();
  window.setTimeout("jQuery.fn.customMenu.instance.normalize()", 1000);
}
