j$(function () {
  j$('ul.popular-spy').popularsimpleSpy();
});

(function ($) {
  $.fn.popularsimpleSpy = function (limit, interval) {
    limit = limit || 5;
    interval = interval || 5000;
    checkEachCnt = 0;

    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:right">' + j$(this).html() + '</li>');
        });

        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;
            }

            if (checkEachCnt <= 1) {
                interval = 0;
                checkEachCnt = checkEachCnt + 1;
            } else {
                interval = 5000;
            }

            setTimeout(spy, interval)
        }

        spy();
    });
  };

})(jQuery);

