$(function () {
    $('ul.sidebar').fade_sidebar();
});

(function ($) {
    
$.fn.fade_sidebar = function (limit, interval) {
    limit = limit || 5;
    interval = interval || 8000;
    
    return this.each(function () {
        // Initialisation
            // on met en cache tous les items
        var $list = $(this),
            items = [], // non initialisé
            currentItem = limit,
            total = 0,
            height = $list.find('> li:first').height();
            
        // Prend le cache
        $list.find('> li').each(function () {
            items.push('<li>' + $(this).html() + '</li>');
        });
        
        total = items.length;
        
        $list.wrap('<div class="sidebar_wrapper" />').parent().css({ height : height * limit });
        
        $list.find('> li').filter(':gt(' + (limit - 1) + ')').remove();

        // 2. Effet 
        function fade() {
            // Insert une nouvel item avec une opacity et height à 0
            var $insert = $(items[currentItem]).css({
                height : 0,
                opacity : 0,
                display : 'none'
            }).prependTo($list);
                        
            // Fade sur le dernier item
            $list.find('> li:last').animate({ opacity : 0}, 1000, function () {
                // Incrémentation sur l'effet
                $insert.animate({ height : height }, 1000).animate({ opacity : 1 }, 1000);
                    $(this).remove();
            });
            
            currentItem++;
            if (currentItem >= total) {
                currentItem = 0;
            }
            
            setTimeout(fade, interval)
        }
        
        fade();
    });
};
    
})(jQuery);