$(function()
{

    var $sectionMenus = $('.topNav_menu > li > .topNav_dropDown');
    var LastSectionMenuIndex = $sectionMenus.size() - 1;
    $sectionMenus.each(function(index)
    {
        var horizontalPos = index < LastSectionMenuIndex ? 'left' : 'right';
        var pos = {
            my: horizontalPos + ' top',
            at: horizontalPos + ' bottom',
            of: $(this).closest('li').children()[0],
            collision: 'fit'
        };
        $(this).position(pos).data('pos', pos);
    });
    var $subMenus = $sectionMenus.find('.topNav_dropDown');
    $subMenus.each(function()
    {
        var pos = {
            my: 'left top',
            at: 'right top',
            of: $(this).closest('li').children()[0],
            collision: 'flip'
        };
        $(this).position(pos).data('pos', pos)
            .hide(); // the hide below should be enough, and is for all reasonable browsers,
        // but in ie6&7 it is not enough for hiding the sub menus, they are still
        // visible when you open a main menu. adding a hide here on the sub menus
        // fixes it...
    });

    //$('.topNav_dropDown').hide();
    //$('.topNav_dropDown ul').hide();

    $("ul.topNav_menu li:has(ul)").hover(function()
    {
        var _this = this;
        if ($(this).data('timeout'))
        {
            clearTimeout($(this).data('timeout'));
        }
        $(this).data('timeout', setTimeout(function()
        {
            $(_this).addClass("hover");
            $('span:first', _this).addClass("hover");
            var $subMenu = $('ul:first', _this);
            if ($.browser.msie && $.browser.version.substr(0, 1) < 7)
            {
                // ie6 won't show the submenus with animation, but it works with just show/hide.
                $subMenu.show();
            }
            else
            {
                $subMenu.stop(true, true).slideDown('fast');
            }
            $subMenu.position($subMenu.data('pos'));
        }, 200));
    }, function()
    {
        var _this = this;
        if ($(this).data('timeout'))
        {
            clearTimeout($(this).data('timeout'));
        }
        $(this).data('timeout', setTimeout(function()
        {
            $(_this).removeClass("hover");
            $('span:first', _this).removeClass("hover");
            var $subMenu = $('ul:first', _this);
            if ($.browser.msie && $.browser.version.substr(0, 1) < 7)
            {
                $subMenu.hide();
            }
            else
            {
                $subMenu.stop(true, true).slideUp('fast');
            }
        }, 200));
    });

});
