document.observe('dom:loaded', function() {

    var navigation = $('contentLinks');
    var nestedNavigations = navigation.select('ul');
    var openedIndex = 0;
    var iddle = true;

    var expandNestedNavigation = function(nestedNavigation, nestedNavigationLink) {
        iddle = false;
        nestedNavigation.setStyle({display: 'block', height: 'auto'});
        var height = nestedNavigation.offsetHeight;
        nestedNavigation.setStyle({height: 0});
        nestedNavigationLink.removeClassName('closeFolderLev1');
        nestedNavigationLink.addClassName('openFolderLev1');

        nestedNavigation.morph('height: ' + height + 'px');
        nestedNavigation.select('li').each(function(nestedNavigationItem, nestedNavigationItemIndex) {
            nestedNavigationItem.setStyle({ opacity: 0 });
            (function() {
                nestedNavigationItem.visualEffect('opacity', {
                    from: 0,
                    to: 1,
                    afterFinish: function() {
                        iddle = true;
                    }
                });
            }).delay((nestedNavigationItemIndex + 1) / 5);
        });
    };

    var collapceNestedNavigation = function(nestedNavigation, nestedNavigationLink) {
        iddle = false;
        nestedNavigationLink.addClassName('closeFolderLev1');
        nestedNavigationLink.removeClassName('openFolderLev1');
        nestedNavigation.morph('height: ' + 0 + 'px', {
            duration: 0.5,
            afterFinish: function() {
                iddle = true;
                nestedNavigation.setStyle({ display: 'none' });
            }
        });
    };

    nestedNavigations.each(function(nestedNavigation) {

        var nestedNavigationLink = nestedNavigation.previous();

        nestedNavigation.hasClassName('openOnLoad') && (function() {
            expandNestedNavigation(nestedNavigation, nestedNavigationLink);
        }).delay((++ openedIndex) / 5);

        nestedNavigationLink.observe('click', function(event) {
            event.stop();
            if(!iddle) return false;
            if(!nestedNavigationLink.hasClassName('openFolderLev1')) {
                navigation.select('.openFolderLev1').each(function(openedNestedNavigationLink) {
                    collapceNestedNavigation(openedNestedNavigationLink.next(), openedNestedNavigationLink);
                });
                (function() {
                    expandNestedNavigation(nestedNavigation, nestedNavigationLink);
                }).delay(0.5);
            }
        });

    });

});