/**
 * Copyright 2009 iWink BV
 */
var ImageFader = Class.create({
	
	container	: null,
	items 		: [],
	links		: [],
	active 		: 0,
	pe			: null,

	initialize : function ( container ) {
	
		this.container	= container;
		this.items		= this.container.select('div.imagefader-item');
		if ( this.container.down('ul') )
			this.links	= this.container.down('ul').select('a');
		
		if ( this.items.size() > 1 ) {			
			this.startPeriodicalExecutor();
			this.addObservers();
		}
	},
	
	startPeriodicalExecutor : function () {
		var pe 	= new PeriodicalExecuter( function(pe) { this.next(); }.bind(this) , 8 );
		this.pe	= pe;
	},
	
	addObservers : function () {
		this.links.each( function( a ) {
			a.observe( 'click' , function( event ) {
				this.linkClicked( event );
			}.bind(this));
		}.bind(this));
	},
	
	linkClicked : function ( 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;		
	}

});

//	Starten maar!
document.observe("dom:loaded", function(event) {
	var fader	= new ImageFader($('header'));
});