var SlideShow = Class.create ({
	index: null,
	pe: null,
	initialize: function(images, interval, duration, callback)
	{
		this.images	= images;
		this.length	= this.images.size();
		this.interval	= interval;
		this.duration	= duration;
		this.callback	= callback;

		this.length > 0 && this.init();

		return this;
	},
	init: function(index)
	{
		this.index = null;

		this.images.each(function(element) { element.hide(); element.setOpacity(0); });

		this.show(index);

		this.length > 1 && this.start();
	},
	show: function(index)
	{
		var morph = this.index !== null;

                this.index = (index == undefined ? (morph ? ++this.index%this.length : 0) : index);

		this.images[this.index].show();

		morph && new Effect.Opacity(this.images[(this.length + this.index - 1)%this.length], { from: 1.0, to: 0.0, duration: this.duration, afterFinish: function(effect) { effect.element.hide(); } });

		new Effect.Opacity(this.images[this.index], { from: 0.0, to: 1.0, duration: morph ? this.duration : 0 });

		this.callback && this.callback(this.index);
	},
	start: function ()
	{
		this.pe = new PeriodicalExecuter (function () { this.show (); }.bind (this), this.interval);
	},
	stop: function ()
	{
		this.pe && this.pe.stop ();
	},
	goto: function (index)
	{
		this.pe && this.pe.stop ();

		this.init (index);
	}
});

Module.Image = Class.create ({
	initialize : function ()
	{
		this.container = null;
		this.slideshow = null;
	},
	parse : function ()
	{
		var counter;

		if ($$('.imageDefault'))
		{
			this.container = $$('.imageDefault').shift ();

			this.slideshow = new SlideShow (this.container.select ('.list .item'), 5, 0.25);

			this.container.select ('.list .item').each (function (element) {
				counter = 0;
				element.select ('.navigation .bullet').each (function (bullet) {
					bullet.observe ('click', this.onClick.bind (this, counter));
					counter ++;
				}.bind (this));
			}.bind (this));
		}
	},
	onClick : function (counter, element)
	{
		if (counter != this.slideshow.index)
		{
			this.slideshow.show (counter);

			this.slideshow.stop ();
		}
	}
});

var moduleImage = new Module.Image ();
document.observe ('dom:loaded', function (event) { moduleImage.parse (); });
