(function() {
	var log = function() { console && console.log.apply(null, arguments); }
	var Scroller = function(c) {
		var container = $(c), init_height = 0, total_items, show, delay, 
		initialized = false, started = false, paused = false,
		current_height = function() {
			var t = 0;
			container.children().slice(0,show).each(function(i,c) {	t += $(c).outerHeight(); });
			return t - 15;
		};
		return {
			init: function(opts) {
				show = (opts && opts.show) || 4;
				init_height = current_height();
				total = container.children().size();
				initialized = true;			
				return this;
			},		
			reverse_children: function() {
				container = container || this.init();
				children = container.children().get().reverse();
				container.append(children);
				return this;		
			},
			start: function(opts) {
				initialized || this.init(opts);
				var self = this, t = container.height(), tid = null; 
				if (started) { if (paused) { self.resume(); } return self; } started = true;
				delay = (opts && opts.delay) || 2;
				container.height(init_height).css({'overflow':'hidden'});
				
				container.append(container.children().slice(show,total_items).get()).scrollTop(0);				
				var init_top = t - init_height;				
				var next = function() {
					if (paused) return;
					var last = container.children().last();
					var last_height = last.outerHeight();
					container.prepend(last).scrollTop(last_height);
					tid = setTimeout(animate, delay * 1000); // start
				},				
				animate = function() {
					container.animate({'scroll-top':0,'height':current_height()}, 'slow', next);
				};				
				this.stop = this.pause = function() { paused = true; clearTimeout(tid);  return self; }
				this.resume = function() { if (paused) { paused = false; next(); } return self; }
				this.toggle = function() { if (paused) { self.resume() } else { self.stop() } return self; }
							
				next(); // trigger it once
				return self;
			}			
		}
	}		
	$(document).ready(function(){
		var scroller = (new Scroller('body#index .bodytext .description')).start({show:4,delay:6});
		// once started, you can stop and resume anytime
		// usage: scroller.stop();
		// setTimeout(function() { scroller.resume() }, 15000) // resume after a while 
	});
})();
