// jquery.ticker.js
// 2010-05-28, www.deitron.de

(function($) {

    $.fn.ticker = function() {

        return this.each(function() {   

            $.ticker(this);
        });
    };

    $.ticker = function(container) {

		var elements = $(container).children().sort(function() { return 0.5 - Math.random(); });
		var length   = elements.length;
		var height   = $(container).css('height');
		var i        = 0;

		$.ticker.init = function() {
			
			elements.css({ top: height });
			
			elements.eq(i).css({ top: '0' });
			
			setTimeout(function() { $.ticker.next(); }, 5000, null);		
		};

		$.ticker.prev = function() {

			var current = elements.eq(i);
			var prev    = elements.eq(i = (i == 0) ? length - 1 : i - 1);

			current.animate({ top: height }, 1000, function() {

				current.css({ top: '-' + height });
			});
			
			prev.animate({ top: '0' }, 1000, function() {
			
				setTimeout(function() { $.ticker.prev(); }, 5000, null);					
			});			
		};
		
		$.ticker.next = function() {

			var current = elements.eq(i);
			var next    = elements.eq(i = (i == length - 1) ? 0 : i + 1);

			current.animate({ top: '-' + height }, 1000, function() {

				current.css({ top: height });
			});
			
			next.animate({ top: '0' }, 1000, function() {
			
				setTimeout(function() { $.ticker.next(); }, 5000, null);					
			});			
		};
		
		if (length > 0) {
			
			$.ticker.init();
		}
	};

})(jQuery);
