


FadeableViewer = Class.create({
	initialize: function(container,options){
		
		
		
		this.container = $$('ul.'+container)[0];
		this.collection = [];
	
		if(typeof(this.container) == "undefined") { return false; throw "FadeableViewer must have a container to work properly. In this case, nothing was found !"; }
		
		// make this work on IE on elements without 'layout'
		/*
		if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
			this.container.setStyle({zoom: 1});
		/**/

		this.collection = $$('ul.'+container+' li');
		if( this.collection.length < 2 ) { throw "FadeableViewer must have a container with 2 sub items or more to work properly."; }
		
		// Ensure we have only one selected item as current element (displayed at once)
		this.current = $$('ul.'+container+' li.current')[0] || 'undefined';
		this.collection.each(function(item,idx){
			item.removeClassName('current');
		});
		if( this.current == 'undefined' ) { $(this.collection[0]).addClassName('current'); this.current = this.collection[0]; }
		else{ this.current.addClassName('current'); }
		
		
		this.options = Object.extend({
			duration: 1.8,
			delay: 3.5,
			randomized: true
		},options || {});
		this.animate();
	},
	
	animate: function(){
		do{
			next = this.pickupNewItem();
		}
		while( this.collection[next] == this.current )
		
		this.doTransition();
	},
	
	doTransition: function(){
		
		this.current.setStyle({zIndex:this.collection.length});
		this.collection[next].setStyle({zIndex:(this.collection.length-1)});
		this.collection[next].addClassName('current');
		this.current.show();
		this.collection[next].hide();
		new Effect.Parallel([
			Effect.Fade(this.current, { sync: true, transition: Effect.Transitions.linear }),
			Effect.Appear(this.collection[next], { sync: true, transition: Effect.Transitions.linear })
		],{
			duration: 1.8,
			delay: 3.5,
			afterFinish:function(){
				this.collection[next].setStyle({zIndex:this.collection.length});				
				this.current.setStyle({zIndex:(this.collection.length-1)});
				this.current.removeClassName('current');
			this.collection[next].show();
			this.current.hide();
				this.current = this.collection[next];
				this.animate();
			}.bind(this)
		});
		
	},
	
	pickupNewItem: function(){
		idx = Math.round(Math.random() * (this.collection.length-1));
		return idx;
	}

});
