/**
 * Necessairy HTML structure:
 *	<div class="ifader">
 *		<ul class="ifader-nav">
 *			<li>nav item</li>
 *			<li>nav item</li>
 *		</ul>
 *		<div class="ifader-item">content</div>
 *		<div class="ifader-item">content</div>
 *	</div>
 *
 * @version		1.0
 * @date		2010-05-25
 * @copyright	2010 iWink BV
 * @author		Timo Schinkel
 */
var iFader = Class.create({
 
	container	: null,
	items 		: [],
	links		: [],
	active 		: 0,
	pe		: null,
	timer		: 8,
 
	initialize : function ( container , options ) {
 
		this.container	= container;
		this.items		= this.container.select('.ifader-item');
		if ( this.container.down('ul.ifader-nav') )
			this.links	= this.container.down('ul.ifader-nav').select('a');
 
		if ( options && options.timer )
			this.timer	= options.timer;
 
		if ( this.items.size() > 1 ) {
			this._selectActiveItems();
			this.startPeriodicalExecutor();
			this.addObservers();
		}
	},
 
	_selectActiveItems		: function () {
		if ( this.container.down('ul.ifader-nav a.active' ) )	//	Er is een actieve link gevonden, dan gaan we daar verder
			this.active	= this.links.indexOf( this.container.down('ul.ifader-nav a.active' ) );
 
		this.items[this.active].setStyle({zIndex: '1' });
		if ( this.links[this.active] )
			this.links[this.active].addClassName( 'active' );		
	} ,
 
	startPeriodicalExecutor : function () {
		var pe 	= new PeriodicalExecuter( function(pe) {this.next();}.bind(this) , this.timer );
		this.pe	= pe;
	},
 
	addObservers : function () {
		this.links.each( function( a ) {
			a.observe( 'click' , this.linkClicked.bind(this) );
		}.bind(this));
	},
 
	linkClicked : function ( event ) {
		if ( event )
			event.stop();
 
		var a	= event.element();
		for( i = 0 ; i < this.links.size() ; i++ ) {
			if ( a == this.links[i] && i != this.active ) {
				this.goToIndex(i);
				if ( this.pe ) {
					this.pe.stop();
					this.startPeriodicalExecutor();
				}
			}
		}
 
	},
 
	next : function (pe) {
		var next	= ( this.active + 1 ) % this.items.size();
		this.goToIndex( next );
	},
 
	goToIndex : function( index ) {
		//	Fade-out, fade-in:
		for( i = 0 ; i < this.items.size() ; i++ )						//	Alle items, die niet active zijn helemaal naar achter!
			if ( i != this.active )
				this.items[i].setStyle({zIndex: '0'});
		this.items[this.active].setStyle({zIndex: '1'});				//	active naar achter plaatsen:
		this.items[index].setStyle({zIndex: '2' , opacity: '0.0'});	//	volgende naar voren plaatsen:
 
		this.items[index].fade({duration: 1.0, from: 0, to: 1});		//	volgende infaden
 
		//	Links op active zetten:
		this.links.each( function( a ) {
			a.removeClassName( 'active' );
		});
		if ( this.links[index] )
			this.links[index].addClassName( 'active' );
 
		//	Administratie bijwerken:
		this.active		= index;
	}
 
});
