var CycleSlides = new Class({
	Implements: [Options, Events],
	
	options: {
		slides: [],
		startIndex: 0,
		wrap: true,
		automatic: false
		//onShow: $empty
	},
	
	initialize: function(options) {
		this.setOptions(options);
		this.addSlides(this.options.slides);
		if (this.slides.length) {
			this.showSlide(this.options.startIndex);
		}
	},
	
	slides: [],
	
	addSlides: function(slides) {
		$$(slides).each(function(slide, i) {
			if (i != 0) {
				$(slide).setStyle('display', 'none');
			}
			
			this.slides.include($(slide));
			
			if (this.options.automatic) {
				this.automatic();
			} else {
				slide.addEvent('click', this.cycleForward.bind(this));
			}
		}, this);
	},
	
	addSlide: function(slide) {
		this.addSlides($splat($(slide)));
	},
	
	cycleForward: function(){
		if($chk(this.now) && this.now < this.slides.length - 1) {
			this.showSlide(this.now + 1);
		} else if ((this.now) && this.options.wrap) {
			this.showSlide(0);
		} else if (!defined(this.now)) {
			this.showSlide(this.options.startIndex);
		}
	},
	
	cycleBack: function(){
		if (this.now > 0) {
			this.showSlide(this.now - 1);
		} else if (this.options.wrap) {
			this.showSlide(this.slides.length - 1);
		}
	},
	
	showSlide: function(slideToShow) {
		if (this.fading) {
			return;
		}
		
		var now = this.now;
		var currentSlide = this.slides[now];
		var slide = this.slides[slideToShow];
		
		var fadeIn = function(s) {
			this.fading = true;
			s.setStyles({
				display: 'block',
				visibility: 'visible',
				opacity: 0
			});
			s.get('tween').start('opacity', 1).chain(function(){
				this.fading = false;
				this.fireEvent('onShow', [slide, slideToShow]);
			}.bind(this));
		}.bind(this);
		
		if (slide) {
			if ($chk(now) && now != slideToShow) {
				this.fading = true;
				currentSlide.get('tween').start('opacity', 0).chain(function(){
					currentSlide.setStyle('display', 'none');
				}.bind(this));
				fadeIn(slide);
			} else {
				fadeIn(slide);
			}
			
			this.now = slideToShow;
		}
	},
	
	automatic: function() {
		this.cycleForward.bind(this).periodical(10000);
	}
});

var ImageCycleSlides = new Class({
	Extends: CycleSlides,
	options: {
		imgUrls: [],
		container: false
	},
	initialize: function(options){
		this.parent(options);
		this.container = $(this.options.container);
		
		if (!this.container) {
			return;
		}
		
		this.options.imgUrls.each(this.addImg.bind(this));
		
		this.showSlide(this.options.startIndex);
	},
	
	addImg: function(url){
		var img = new Element('img', {
			src: url,
			styles: {
				display: 'none'
			}
		}).inject($(this.options.container));
		
		this.addSlide(img);
	}
});