/**
 * JS class for feedslider
 * 
 * requires Prototype 1.6.1
 * 
 * @copyright  (c)2010 Spion Media GmbH
 * @author     Uwe Mesecke <um@spion-media.eu>
 */

if (typeof FeedSlider == "undefined") {
	var FeedSlider = {};
}

/****************************************************************************************
 * Controller
 */

FeedSlider.Controller = Class.create();

FeedSlider.Controller.prototype = {
	initialize: function(element, timeout) {
		this.carousel = new UI.Carousel(element, {animationDuration: 1});
		
		if (timeout > 0) {
			this.setupAutoscroll(timeout);
		}
	},
	
	setupAutoscroll: function(timeout) {
		this.timeout = timeout;
		
		this.carousel.observe("scroll:started", function(event) {
			this.disableAutoscroll();
		}.bind(this));
		this.carousel.observe("scroll:ended", function(event) {
			this.resetAutoscroll();
		}.bind(this));
		
		this.resetAutoscroll();
	},
	
	disableAutoscroll: function() {
		if (this.autoscroller) {
			this.autoscroller.stop();
			delete this.autoscroller;
		}
	},
	
	resetAutoscroll: function() {
		if (this.autoscroller) {
			this.disableAutoscroll();
		}
		
		this.autoscroller = new PeriodicalExecuter(function() {
			this.doAutoscroll();
		}.bind(this), this.timeout);
	},
	
	doAutoscroll: function() {
		var numElements = this.carousel.elements.length;
		var curElement = this.carousel.currentIndex();
		
		if (curElement >= numElements - 1) {
			var nextElement = 0;
		} else {
			var nextElement = curElement + 1;
		}
		
		this.carousel.scrollTo(nextElement);
	}
};


