var ContentScroller = new Class({
	options: {
		slides: [],
		slideDuration: 4000,
		fadeDuration: 1000,
		controlContainer: null,
		direction: 'forward'
	},

	initialize: function(options) {
		this.setOptions(options);
		this.current = 0;
		this.slides = [];
		this.addSlides(this.options.slides);
	},

	addSlides: function(slides) {
		$$(slides).each(function(el) {
			this.addSlide(el);
		}, this);
	},

	addSlide: function(slide) {
		var s = new Fx.Tween(slide, { property: 'opacity', duration: this.options.fadeDuration, link: 'cancel' });
		this.slides.push(s);

		if (this.slides.length > 1 && !this.initialisedControls) {
			this.setupControls();
		}
	},

	nextSlide: function() {
		var nextElement = (this.current + (this.options.direction == 'forward' ? 1 : -1) + this.slides.length) % this.slides.length;

		this.slides[this.current].start(0);
		this.slides[nextElement].start(1);

		this.current = nextElement;
	},

	setupControls: function() {
		var controlContainer = $(this.options.controlContainer);

		if (!this.initialisedControls && controlContainer) {
			var controls = new Element('div', { 'class': 'controls' }).inject(controlContainer);

			controls.adopt(new Element('a', { id: 'prevLink', href: '#', text: 'Previous Slide' }).addEvent('click', function(e) {
				e.stop();

				this.options.direction = 'backward';
				this.nextSlide();
			}.bindWithEvent(this)));

			controls.adopt(new Element('a', { id: 'nextLink', href: '#', text: 'Next Slide' }).addEvent('click', function(e) {
				e.stop();

				this.options.direction = 'forward';
				this.nextSlide();
			}.bindWithEvent(this)));

			this.initialisedControls = true;
		}
	},

	start: function() {
		if (this.slides.length > 1) {
			$each(this.slides, function(slide, i) { slide.set(i > 0 ? 0 : 1); });
			this.nextSlide.periodical(this.options.slideDuration, this);
		}
	}
});

ContentScroller.implement(new Options, new Events);
