Event.observe( window, 'load', function () {

	homepageBanners.init();

});


var homepageBanners = {

	currentIndex: 0,
	isChanging: false,
	timer: false,

	init: function ( options ) {

		$('homeAdvertImages').style.display = 'block';
		
		this.banners 	= $$('#homeAdvertImages a' );

		this.banners.each( function ( banner ) {
			banner.setStyle({
				display:	'block',
				position: 	'absolute',
				zIndex:		'0'
			});
		});

		$$('#tabs a').invoke( 'observe', 'click', this.paginationClick.bind( this ) );

		//  Default to last banner because of the way the browser lays
		this.banners[ this.currentIndex ].setStyle({ zIndex: '5' });

		this.options 		= options || {};
		this.options.delay	= this.options.delay || 5;

		this.startTimer();

	},


	atLastImage: function () {

		return ( this.currentIndex == this.banners.length - 1 );

	},


	goNext: function () {

		var c 			= this.banners[ this.currentIndex ];						//  Current image
		var nextIndex 	= ( this.atLastImage() ) ? 0 : this.currentIndex + 1;		//  Next image's index
		var n		 	= this.banners[ nextIndex ];								//  Next image

        //  Reset z-index on images which aren't the current or next banners
		this.banners.findAll( function ( img, index ) {
			return ( index != nextIndex && index != this.currentIndex );
		}.bind( this )).each( function ( el ) {
			el.setStyle({ zIndex: 0 });
		}.bind( this ));

		//  Put the new banner below the current one
		n.setStyle({ zIndex: '2' });
		c.setStyle({ zIndex: '3' });

		//  Show banner so it fades in automatically
		$(n).show();

		this.isChanging = true;

		$(c).fade({
			duration:1.5,
			from:1,
			to:0,
			afterFinish: function () {
				this.isChanging = false;
				$$('#tabs  a')[ nextIndex ].addClassName( 'active' ).siblings().invoke( 'removeClassName', 'active' );
			}.bind( this )
		});

		this.currentIndex = nextIndex;

	},


	paginationClick: function ( ev ) {

		Event.stop( ev );

		this.stopTimer();

		el = ev.element();
		el.addClassName( 'active' ).siblings().invoke( 'removeClassName', 'active' ).each( function ( banner ) {
			banner.setStyle({
				zIndex: '0'
			});
		});

		this.banners.each( function ( banner ) {
			banner.setStyle({
				zIndex:		0
			});
		});
		
		this.banners[ $( el ).previousSiblings().length ].setStyle({zIndex:5}).show();

	},


	startTimer: function () {

		this.timer = new PeriodicalExecuter( this.goNext.bindAsEventListener( this ), this.options.delay );

	},


	stopTimer: function () {

    	//  Stop the timer (probably a click on a manual link)
		if ( this.timer !== false ) {
			this.timer.stop();
			this.timer = false;
		}

	}


}

