j$(function () {
    j$('ul.spy').simpleSpy();
});

(function ($) {
    
$.fn.simpleSpy = function (limit, interval) {
    //limit = limit || 5;
    limit = limit || 6;
    interval = interval || 5000;
    
    return this.each(function () {
        // 1. setup
            // capture a cache of all the list items
            // chomp the list down to limit li elements
        var $list = j$(this),
            items = [], // uninitialised
            currentItem = limit,
            total = 0, // initialise later on
            width = $list.find('> li:first').width();
            
        // capture the cache
        $list.find('> li').each(function () {
            items.push('<li style="float:left">' + j$(this).html() + '</li>');
        });
        //alert(items);
        total = items.length;
        
        $list.wrap('<div class="spyWrapper" />').parent().css({ width : width * limit });
        
        //$list.find('> li').filter(':gt(' + (limit - 1) + ')').remove(); // removeしないとそのまま押し出される形になる。
        $list.find('> li').filter(':gt(' + (limit - 1) + ')');

        // 2. effect        
        function spy() {
            // insert a new item with opacity and height of zero
            var $insert = j$(items[currentItem]).css({
                width : 0,
                opacity : 0,
                display : 'none'
            }).prependTo($list);
                        
            // fade the LAST item out
            $list.find('> li:last').animate({ opacity : 0}, 1, function () {
                // increase the height of the NEW first item
                $insert.animate({ width : width }, 500).animate({ opacity : 1 }, 500);
                
                // AND at the same time - decrease the height of the LAST item
                // j$(this).animate({ height : 0 }, 1000, function () {
                    // finally fade the first item in (and we can remove the last)
                    j$(this).remove();
                // });
            });
            
            currentItem++;
            if (currentItem >= total) {
                currentItem = 0;

            }
            
            setTimeout(spy, interval)
        }
        
        spy();
    });
};
    
})(jQuery);

