// Animate the menu indicator when the page loads:
$(document).ready(function() {    
    // Start by positioning it to the active menu item:
    var active_item = $('ul#navigation li a.current');
    var indicator   = $('#menu-indicator');
    var on_indicator = false;
    var active_menu = null;
    
    // Only handle if there's an current item:
    if(active_item.length < 1)
        indicator.hide();
    else
    {
        var left_pos    = active_item.offset().left;

        indicator.mouseenter(function() { on_indicator = true; }).mouseleave(function() { on_indicator = false; });
        
        // Calculate the top we need:
        var top_pos     = (active_item.offset().top + active_item.outerHeight()) - indicator.outerHeight();
        indicator.css({ left: left_pos, top: top_pos });
        
        // If they click on it, set the left position as this element's left:
        $('ul#navigation li a').click(function() { left_pos = $(this).offset().left });
        
        // When they enter one, move it:
        $('ul#navigation > li > a').mouseenter(function() {
            // Get the left:
            var new_left_pos = $(this).offset().left;
            var the_link = $(this);
            indicator.animate({ left: new_left_pos }, 'fast');
            if(active_menu != null)
                active_menu.slideUp();
            
            var this_child_menu = the_link.parents('li').children('ul.child');
            // If it has a child, animate it:
            if(this_child_menu.length > 0)
            {
                // Hide any child if there is one:
                this_child_menu.mouseleave(function() { $(this).slideUp(); });
                
                // If it's visible, don't do it:
                if(!this_child_menu.is(':visible'))
                {
                    active_menu = this_child_menu;
                    this_child_menu.slideDown();
                }
            }
        });
        
        // If they haven't clicked anything, we need to return it to the current:
        $('ul#navigation').mouseleave(function() { if(!on_indicator) indicator.animate({ left: left_pos }, 'fast'); });
    }
});
