var Showreel = new Class({
	Implements: [Options, Chain],
	
	options: {
		widePanelSelector: 'ul',
		itemSelector: 'ul li',
		nextSelector: '.next',
		viewport: '.viewport',
		initialDelay: 4000,
		duration: 1000,
		interval: 5000
	},
	
	initialize: function(viewport, options) {
		this.setOptions(options);
		this.nextButton = viewport.getElement(this.options.nextSelector);
		this.viewport = viewport.getElement(this.options.viewport) || viewport;

		this.fx = new Fx.Scroll(this.viewport, {wheelStops: false, duration: this.options.duration, onComplete: this.callChain.bind(this)});
		
		var images = this.viewport.getElements('img');
		images = images.filter(function(image) {return !image.complete}); // Remove images already loaded
		
		images.length ? new Group(images).addEvent('load', this.onReady.bind(this)) : this.onReady();
	},
	
	onReady: function() {
		this.timer = this.start.delay(this.options.initialDelay, this);
		if (this.nextButton) this.nextButton.addEvent('click', this.start.bind(this));
	},
	
	start: function(e) {
		if (e) e.preventDefault();
		$clear(this.timer);
		
		this.chain([
			function() {
				this.running = true;
				$clear(this.timer);
				var next = this.viewport.getElements(this.options.itemSelector)[1];
				!next || this.fx.toElement(next);
			},
			function() {
				var items = this.viewport.getElements(this.options.itemSelector);
				items[0].inject(items[items.length-1], 'after');
				this.fx.set(0,0);
				this.timer = this.start.delay(this.options.interval, this);
				this.moving = false;
	
				this.running = false;
				this.callChain();
			}
			
		]);
		
		if (!this.running) this.callChain();
	}
});