window.addEvent("domready", function()
{
	var gallery = new slideGallery($("gallery"), {duration: 4000, autoplay: true, width: 657, slider: "ul", slider_el: "li"});
});

var slideGallery = new Class(
{
	Implements: [Options],
	options: {
    	duration: 10000,
		autoplay: true,
		width: 500,
		slider: "ul",
		slider_el: "li",
		thumbnails: ".thumbs li a",
		prev_slide: ".btn-prev",
		next_slide: ".btn-next",
		pause: ".btn-pause",
		play: ".btn-play"
	},
	initialize: function(gallery, options)
	{
		this.gallery = gallery;
		this.setOptions(options);
		this.slide = this.gallery.getElement(this.options.slider);
		this.slide_number = this.slide.getElements(this.options.slider_el).length;
		this.current = this.slide_number - 1;
		this.gallery.fx = new Fx.Morph(this.slide, {duration: 600, transition: Fx.Transitions.Sine.easeOut});
		this.bound = { rotate: this.rotate.bind(this) }
		this.next = this.gallery.getElement(this.options.next_slide);
		this.prev = this.gallery.getElement(this.options.prev_slide);
		this.pause = this.gallery.getElement(this.options.pause);
		this.start = this.gallery.getElement(this.options.play);
		this.tabs = this.gallery.getElements(this.options.thumbnails);
		if(this.options.duration < 1000) this.options.duration = 1000;
		
		this.slide.setStyles({'margin-left': - (this.slide_number-1) * this.options.width});
		
		if(this.next)
		{
			this.next.addEvent('click', function()
			{
				if(++this.current >= this.slide_number)
					this.current=0;
				this.play();
			}.bind(this));
		}
		
		if(this.prev)
		{
			this.prev.addEvent('click', function()
			{
				if(--this.current < 0)
					this.current = this.slide_number-1;
				this.play();
			}.bind(this));
		}
		
		if(this.start)
		{
			this.start.addEvent('click', function()
			{
				if(!this.options.autoplay)
				{
					this.options.autoplay = true;
					this.timer = this.bound.rotate.delay(this.options.duration);
				}
			}.bind(this));
		}
		
		if(this.pause)
		{
			this.pause.addEvent('click', function()
			{
				this.options.autoplay = false;
			}.bind(this));
		}

		if(this.tabs)
		{
			this.tabs.each(function(el, i)
			{
				el.addEvent('click', function()
				{
					this.current = i;
					this.play();
				}.bind(this));
			}.bind(this));
		}

		if(this.options.autoplay)
		{
			this.timer = this.bound.rotate.delay(this.options.duration);
		}
	},
	play: function()
	{
		if(this.tabs.length > 0)
		{
			this.tabs.removeClass("active");
			this.tabs[this.current].addClass("active");
		}
		this.gallery.fx.cancel();
		this.gallery.fx.start({'margin-left': -this.current * this.options.width});
	},
	rotate : function()
	{
		if(this.options.autoplay)
		{
			if(--this.current < 0)
					this.current = this.slide_number-1;
			this.play();
			this.timer = this.bound.rotate.delay(this.options.duration);
		}
	}
});