var SlideShowFade = null;
var SlideShowFade = Class.create({
	initialize: function(element, options) {
		this.element = $(element);
		this.options = Object.extend({
			autoStart: true,
			duration: 0.5,
			delay: 7,
			callback: {
				onChange: function(previous, next){},
				onChanged: function(previous, next){}
			}
		}, options || {});

		if (Element.childElements(this.element).size()<=1) throw('Slide Show Element should have more than 1 childs');
		Element.childElements(this.element).first().show().nextSiblings().invoke('hide');
		
		this.EffectExecuter = new PeriodicalExecuter(this.next.bind(this), this.options.delay);
		if (!this.options.autoStart) this.EffectExecuter.stop();
	},
	start: function() {
		this.EffectExecuter.registerCallback();
		return this;
	},
	stop: function() {
		this.EffectExecuter.stop();
		return this;
	},
	next: function() {
		
		var current = Element.childElements(this.element).find(function(f) { return Element.visible(f); });
		if (current==Element.childElements(this.element).last()) var next = Element.childElements(this.element).first()
		else var next = Element.next(current);
		return this.transit(current, next);
	},
	previous: function() {
		var current = Element.childElements(this.element).find(function(f) { return Element.visible(f); });
		if (current==Element.childElements(this.element).first())  var next = Element.childElements(this.element).last()
		else var next = Element.previous(current);
		return this.transit(current, next);
	},
	switchTo: function(next) {
		var current = Element.childElements(this.element).find(function(f) { return Element.visible(f); });
		return this.transit(current, next);
	},
	transit: function(current, next) {
		this.stop();
		this.options.callback.onChange(current, next);
		new Effect.Parallel([
			new Effect.Fade(current, {sync:true}),
			new Effect.Appear(next, {sync:true})
		], {
			duration: 2,
			queue: {
				position: 'end',
				scope: 'TestScope',
				limit: 2
			},
			afterFinish: function(c, n) {
				this.options.callback.onChanged(c, n);
			}.bind(this, current, next)
		});
		this.start();
		return this;
	}
});
