


var MediaSlider = Class.create({
	slider: null,
	options: null,
	panelDimentions: null,
	nbPanels: 0,
	currentPanelIndex: 0,
	
	initialize: function( slider, options )
	{
		this.slider = $(slider);
		
		this.options = Object.extend({
			direction: 'horizontal',
			duration: 1,
			onNextLimit: function() {},
			onPreviousLimit: function() {},
			onNoLimit: function() {}
		}, options || {});
		
		this.panelDimentions = this.slider.down().down().getDimensions();
		this.nbPanels = this.slider.down().childElements().length;
		this.currentPanelIndex = 0;
		
		this.options.onPreviousLimit();
		if ( this.nbPanels < 2 )
			this.options.onNextLimit();
		
		// URL Anchors
		if ( window.location.hash.match(/^#m_/) )
		{
			var media = $( window.location.hash.substring(1) );
			if ( media )
			{
				var panelIndex = this.slider.down().childElements().indexOf(media.up());
				this.slideTo(panelIndex);
			}
		}
	},
	
	getCleanIndex: function( index )
	{
		if ( index < 0 ) return 0;
		else if ( index >= this.nbPanels ) return this.nbPanels-1;
		else return index;
	},
	
	slideTo: function( index )
	{
		index = this.getCleanIndex(index);
		if ( index == this.currentPanelIndex )
			return false;
			
		if ( index == 0 )
		{
			this.options.onPreviousLimit();
			if ( this.currentPanelIndex == this.nbPanels-1 )
				this.options.onNoLimit('fromNext');
		}
		else if ( index == this.nbPanels-1 )
		{
			this.options.onNextLimit();
			if (this.currentPanelIndex == 0 )
				this.options.onNoLimit('fromPrevious');
		}
		else
		{
			if (this.currentPanelIndex == 0 )
				this.options.onNoLimit('fromPrevious');
			else if ( this.currentPanelIndex == this.nbPanels-1 )
				this.options.onNoLimit('fromNext');
		}
		
		if ( this.options.direction == 'horizontal' )
		{
			new Effect.ScrollHorizontal( this.slider, {
				to: ( index * this.panelDimentions.width ),
				duration: this.options.duration
			});
		}
		else
		{
			new Effect.ScrollVertical( this.slider, {
				to: ( index * this.panelDimentions.height ),
				duration: this.options.duration
			});
		}
		this.currentPanelIndex = index;
	},
	
	next: function()
	{
		this.slideTo( this.currentPanelIndex+1 );
	},
	
	previous: function()
	{
		this.slideTo( this.currentPanelIndex-1 );
	}
});

var Slider;
Event.observe( window, 'load', function() {
	Slider = new MediaSlider('medias', {
		direction: 'horizontal',
		onNextLimit: function() {
			$$('a.next').invoke('addClassName','inactive');
		},
		onPreviousLimit: function() {
			$$('a.previous').invoke('addClassName','inactive');
		},
		onNoLimit: function(from) {
			if ( from == 'fromPrevious' )
				$$('a.previous').invoke('removeClassName','inactive');
			else
				$$('a.next').invoke('removeClassName','inactive');
		}
	});
});