$(document).ready(function(){
    var timer = '';
    var nav_list = $('#nav-list');
    var main_links = $('li.main-links', nav_list);
    var current_menu = $("li.active", nav_list);
    var current_sub_menu = $("ul.sub-links", current_menu);
    current_menu.addClass('current_sub');
    var not_yet = false;
    var temp_background = current_menu.css('background');
    // Move out all submenus that aren't the active one
    $('li.main-links:not(.active) ul', nav_list).css('top', '-9999px');
    
    nav_list.mouseover(function(){
        not_yet = true
        //current_menu.removeClass('active')
    }).mouseout(function(){
        not_yet = false
        //current_menu.addClass('active')
    });
    main_links.hoverIntent({
        timeout: 300,
        interval: 300,
        over: function(){
            clearTimeout(timer)
            el = $(this)
            sub_menu = $('ul', el)
            if (sub_menu.length)
            {
                el.addClass('top-nav-hover');
                if (current_sub_menu.css('top') == '91px')
                {
                    // Don't want it to run if it's visible and it's the active submenu
                    if (el.hasClass('current_sub'))
                        return false
                    current_sub_menu.animate({top: 101, opacity: 0.0}, 300, function(){
                        sub_menu.css('top', '101px').animate({top: 91, opacity: 1.0}, 300).css('z-index', 200)
                        current_sub_menu.css('top', '-9999px');
                    });
                }
                else
                {
                    sub_menu.css('top', '101px').animate({top: 91, opacity: 1.0}, 300)
                }
            }
            else
            {
                if (current_sub_menu.css('top') == '91px')
                {
                    current_sub_menu.animate({opacity: 0.0}, 300, function(){
                        current_sub_menu.css('top', '-9999px')
                    })
                }
            }
        },
        out: function(){
            clearTimeout(timer)
            el = $(this)
            sub_menu = el.children('ul');
            if (sub_menu.html() != current_sub_menu.html())
            {
                el.removeClass('top-nav-hover');
                sub_menu.animate({top: 91, opacity: 0.0}, 300, function() {
                    sub_menu.css('top', '-9999px');
                })
                timer = setTimeout(function(){
                    if (current_sub_menu.css('opacity') == '0' && ! not_yet)
                    {
                        current_sub_menu.css('top', '91px').animate({opacity: 1.0}, 1000)
                    }                
                }, 1000)
            }
        }
    });
});