var MainSlider = Class.create ({
	
	initialize: function(container, time)
	{
		this.time = time; //time in seconds betwen sliding
		this.container = container;
		this.numItems = this.container.select('div.sliderItem').size();
		this.currentPos = 0;
		
		if (!this.container)
		{
			return false;
		}
		this.addControls();
		this.updateControls();
		
		this.timer = new PeriodicalExecuter(this.timedMove.bind(this), this.time);
	},
	
	addControls: function()
	{	
		this.container.select('a').each(function(container)
		{
			if (container.hasClassName('displayNone')) 
			{
				container.removeClassName('displayNone');
				container.addClassName('displayBlock');
			}
		});
		
		this.container.select('div').each(function(container)
		{
			if (container.hasClassName('displayNone')) 
			{
				container.removeClassName('displayNone');
				container.addClassName('displayBlock');
			}
		});
		
		this.container.select('div.sliderItem').each(function(container, index)
		{
			if(index == 0)
			{
				container.setStyle({display: "block"});
			}
			else
			{
				container.setStyle({display: "none"});
			}
		});
		
		this.container.select('a.quick').each(function(container, index)
		{
			container.store('page', index);
		});	
		
		this.container.select('a.quick').each(function(link){
			link.observe("click", this.quickclicked.bind(this));
		}.bind(this));
	},
	
	quickclicked: function(event)
	{
		if(!event)
		{
			return false;
		}
		
		event.stop();
		this.restartTimer();
		
		this.doMove(event.element().retrieve('page'), true);
	},
	
	updateControls: function()
	{		
		this.container.select('li').each(function(container)
		{
			if (container.hasClassName('selected'))
			{
				container.removeClassName('selected');
			}
		});	
		
		if(this.container.select('li')[this.currentPos])
		{
			this.container.select('li')[this.currentPos].addClassName('selected');
		}
	},
	
	doMove: function(toIndex, quickClicked)
	{	
		new Effect.Fade(this.container.select('div.sliderItem')[this.currentPos], { duration: 0.5 });
		
		if(toIndex == this.numItems)
		{
			toIndex = 0;
		}
		
		new Effect.Appear(this.container.select('div.sliderItem')[toIndex], { duration: 0.5 });
		
		if(!quickClicked)
		{
			this.currentPos = this.currentPos + 1;
		}
		else
		{
			this.currentPos = toIndex;
		}
		
		if(this.currentPos == this.numItems)
		{
			this.currentPos = 0;
		}
		
		this.updateControls();
	},
	
	restartTimer: function()
	{
		this.timer.stop();
		this.timer = new PeriodicalExecuter(this.timedMove.bind(this), this.time)
	},
	
	timedMove: function()
	{
		this.doMove(this.currentPos+1, false);
	}
});


document.observe('dom:loaded', function()
{	
	if ($("sliderBox"))
	{
		new MainSlider($('sliderBox'), 6);
	}
});
