(function($) {
    $.clientWidget = {
        _running: true,
        _interval: 5000,
        _el: null,
        _size: null,
        _idx: 0
    };

    $.clientWidget._move = function(n) {
        var w = $.clientWidget;
        var finish = function() {
            $('ul li', w._el).hide();
            w._idx = (w._idx + n) % w._size;
            if (w._idx < 0) w._idx = w._size - 1;
            $('ul li:eq(' + w._idx + ')', w._el).fadeIn('fast');
            $('.client-status .current').text(w._idx + 1);
        };
        $('ul li:eq(' + w._idx + ')', w._el).fadeOut('fast', finish);
    };

    $.clientWidget._step = function() {
        var f = function() {
            if ($.clientWidget._running) {
                $.clientWidget._move(1);
            }
            $.clientWidget._step();
        };
        setTimeout(f, $.clientWidget._interval);
    };

    $.fn.clientWidget = function(opts) {
        var w = $.clientWidget;
        w._el = this;
        if (typeof opts !== "undefined") {
            if (typeof opts.slideshow !== "undefined"
                && opts.slideshow != null) {
                w._running = opts.slideshow;
            }
            if (typeof opts.interval !== "undefined"
                && opts.interval != null) {
                w._interval = opts.interval;
            }
        }

        var clients = $('ul li', this);
        clients.hide();
        var size = w._size = clients.length;

        var prev = $('<span class="client-prev" title="Previous">&#160;</span>');
        prev.bind('click', function(event) {
            w._move(-1);
        });
        $(this).append(prev);

        var status = $('<span class="client-status"><span class="current">1</span> / ' + size + '</span>');
        $(this).append(status);

        var next = $('<span class="client-next" title="Next">&#160;</span>');
        next.bind('click', function(event) {
            w._move(1);            
        });
        $(this).append(next);

        $(this).bind('mouseover', function(event) {
            w._running = false;
        });

        $(this).bind('mouseout', function(event) {
            w._running = true;
        });

        w._move(0);
        if (w._running) {
            w._step();
        };
    };
})(jQuery);

