﻿(function ($) {

    /// Rotates items by keeping a maximum of [max, default = 3] of items 
    /// and displaying new ones every [time, default = 5] seconds
    $.fn.rotateActivity = function (time, max, highlight) {
        if (max == undefined) { max = 8; }
        if (time == undefined) { time = 2; }
        if (highlight == undefined) { highlight = "highlight"; }

        if (this.length <= max) { return; }
        this.hide(); // hide all children

        // display the initial items
        // starting at the bottom
        var len = this.length - 1;

        var bucket = new Array();
        var bucket_ix = 0;
        for (var i = len; i > len - max; i = i - 1) {
            $(this[i]).show();
            bucket.splice(0, 0, this[i]); // reverse add
            bucket_ix = i;
        }
        var children = this;

        setInterval(function () {
            bucket_ix = bucket_ix - 1; // advance by one
            if (bucket_ix < 0) {
                bucket_ix = len; // cycle back
            }

            var haystack = $(bucket.pop());
            var needle = $(children[bucket_ix]);
            $(bucket[0]).before(needle);
            haystack.hide();
            bucket.splice(0, 0, needle);

            needle.addClass(highlight);
            needle.fadeIn('slow', function () {
                needle.removeClass(highlight);
            });
        }, time * 1000);
    };
})(jQuery);
