var Marquee = new Class({
	Implements: [Events, Options],
	/**
	 * Default Options
	 * 
	 * transitionDuration: The duration of the animation between slides
	 * autoPlayDuration: The time between automatic slide transitions
	 * stop: HTML element used to stop autoplay
	 * play: HTML element used to start autoplay
	 */
	options: {
		transitionDuration: 1000,
		autoPlayDuration: 5000,
		stop: 'control-play',
		play: 'control-stop'
	},
	initialize: function(slides, thumbs, options){
		this.setOptions(options);
		
		this.slides = slides;
		// create effects for each
		this.slides.each(function(item){
			item.fx = new Fx.Tween(item, {
				property: 'opacity',
				link: 'cancel',
				duration: this.options.transitionDuration
			});
			item.fx.set(0);
		}.bind(this));
		this.thumbs = thumbs;
		
		// store controls
		this.playButton = $(this.options.play);
		this.stopButton = $(this.options.stop);
		
		this.currentIndex = 0;
		
		this.update();
		this.start();
		this.attach();
	},
	attach: function(){
		var self = this;
		
		// attach click events to thumbnails
		this.thumbs.addEvent('click', function(){
			self.currentIndex = self.thumbs.indexOf(this);
			self.update();
			// stop autoplay after a user has clicked on a thumbnail
			self.stop();
		});
		
		// events for controls.
		this.playButton.addEvent('click', this.stop.bind(this));
		this.stopButton.addEvent('click', this.start.bind(this));
	},
	/**
	 * stop - Stop autoplay
	 */
	stop: function(){
		this.stopButton.removeClass('hidden');
		this.playButton.addClass('hidden');
		$clear(this.interval);
	},
	/**
	 * start - Start autoplay
	 */
	start: function(){
		this.stopButton.addClass('hidden');
		this.playButton.removeClass('hidden');
		this.interval = this.cycle.periodical(this.options.autoPlayDuration, this);
	},
	/**
	 * cycle - Step through slide circularly will return to first at the end of the list
	 */
	cycle: function(){
		if(this.currentIndex != this.thumbs.length-1)
			this.currentIndex++;
		else
			this.currentIndex = 0;
		this.update();
	},
	update: function(){
		this.thumbs.removeClass('active');
		this.thumbs[this.currentIndex].addClass('active');
		
		this.slides.each(function(item, index){
			if(index == this.currentIndex)
				item.fx.start(1);
			else
				item.fx.start(0);
		}.bind(this));
	}
});