var Slides = new Class({
	
	Implements: Options,
	
	options: {
		container: 'slideshow',
		slide: '.slide',
		button: '.button',
		buttonActiveClass: 'button-active',
		startingSlide: 0,
		interval: 7000
	},
	
	interval: null,
	current: null,
	container: null,
	elements: [],
	buttons: [],
	effects: [],
	
	initialize: function(options){
		this.setOptions(options);
		this.container = document.id(this.options.container);
		if (!this.container) return;
		this.elements = this.container.getElements(this.options.slide);
		if (this.elements.length == 0) return;
		this.buttons = this.container.getElements(this.options.button);
		this.current = Math.min(Math.max(this.options.startingSlide, 0), this.elements.length - 1);
		this.elements.each(function(el, i){
			el.setStyles({
				'opacity': i == this.current ? 1 : 0,
				'visibility': 'visible'
			});
			this.effects[i] = new Fx.Tween(el, {
				property: 'opacity',
				duration: 1000,
				link: 'cancel'
			});
		}.bind(this));
		this.buttons.each(function(el, i){
			el.addEvent('click', function(e){
				e.stop();
				window.clearInterval(this.interval);
				this.changeSlide(i);
			}.bind(this));
			if (i == this.current) el.addClass(this.options.buttonActiveClass);
		}.bind(this));
		if (this.elements.length > 1) this.interval = this.changeSlide.periodical(this.options.interval, this);
	},
	
	changeSlide: function(i){
		if (this.current != i) {
			this.effects[this.current].start(0);
			var prev = this.elements[this.current];
			prev.setStyle('z-index', 0);
			this.current = (i == undefined) ? ((this.current + 1 < this.elements.length) ? this.current + 1 : 0) : i;
			var next = this.elements[this.current];
			next.setStyle('z-index', 1);
			this.effects[this.current].start(1);
			this.buttons.each(function(el, i){
				if (i == this.current) {
					if (!el.hasClass(this.options.buttonActiveClass)) el.addClass(this.options.buttonActiveClass);
				} else if (el.hasClass(this.options.buttonActiveClass)) el.removeClass(this.options.buttonActiveClass);
			}.bind(this));
		}
	}
	
});
