
$(function () {

    var $mainContent = $('#MainContent');
    var $activeMenu, $activeNav;

    // setup top navigation
    $('#menu li').each(function () {

        var $this = $(this);
        var $innerNav = $this.find('.innerNav');
        
        // store original innerNav heights
        $innerNav.data('height', $innerNav.height()).height(0).hide();

        $this.bind('click', function () {
            // 1. collapse any active dropdown
            // 2. open new dropdown if it is different than the previously active dropdown
            if ($activeMenu && $activeNav) {
                // hide active dropdown
                $activeNav.animate({ height: '0px', 'padding-top': '0px', 'padding-bottom': '0px' }, 300, function () {
                    $activeNav.hide();
                    $activeMenu.removeClass('active');
                });
                // push content up
                $mainContent.animate({ 'margin-top': '0px' }, 300, function () {
                    if (!($this === $activeMenu)) {
                        // show new dropdown and push content down
                        var height = $innerNav.data('height');
                        $innerNav.show().animate({ height: height + 'px', 'padding-top': '10px', 'padding-bottom': '10px' }, 300, function () { });
                        $this.addClass('active');
                        $mainContent.animate({ 'margin-top': (height + 10) + 'px' }, 300, function () { });
                        $activeMenu = $this;
                        $activeNav = $innerNav;
                    } else {
                        $activeMenu = null;
                        $activeNav = null;
                    }
                });
            } else {
                if (!($this === $activeMenu)) {
                    // show new dropdown and push content down
                    var height = $innerNav.data('height');
                    $innerNav.show().animate({ height: height + 'px', 'padding-top': '10px', 'padding-bottom': '10px' }, 300, function () { });
                    $this.addClass('active');
                    $mainContent.animate({ 'margin-top': (height + 10) + 'px' }, 300, function () { });
                    $activeMenu = $this;
                    $activeNav = $innerNav;
                } else {
                    $activeMenu = null;
                    $activeNav = null;
                }
            }
        });
    });
});
