/**
*	Manage the homepage banners
*/
var homepageBanners = {

	/***  Settings/default properties  ***/

	delay: 4,
	currentIndex: 0,
	timer: false,


	/***  Main init function  ***/

	init: function ( options ) {

		//  Set defaults if nothing set
		options				= options || {};
		options.delay		= options.delay || 5;

		//  Get all the banners
		this.banners = $$( '.newOfferBanner' );

		//  Make banners moveable by setting their position to absolute and moving them to the default position
		this.banners.each( function ( banner ) {
			banner.setStyle({
				display: 'block',
				position: 'absolute'
			}).clonePosition( $('newOfferBannerWrapper'), { offset: $('newOfferBannerWrapper').getWidth(), onComplete: function () {} });
		});

		//  Default to last banner because of the way the browser lays
		this.currentIndex = this.banners.length - 1;

		this.startTimer( options.delay );

	},


	/***  Class methods  ***/

	changeImage: function ( i, position ) {

		var c = this.banners[this.currentIndex];	//  Current
		var n = this.banners[i];					//  New

		//  Get all the banners which are they current or new
		this.banners.findAll( function ( img, index ) {
			return ( index != i && index != this.currentIndex );
		}.bind( this )).each( function ( el ) {
			el.setStyle({ zIndex: 0 });
		}.bind( this ));

		//  Put the new banner on top of the current one
		n.setStyle({ zIndex: '3' });
		c.setStyle({ zIndex: '2' });

		//  Get the width of the current banner to work out the offset
		var w = n.getWidth();
		var h = n.getHeight();
		

		//  Position and move the new image
		switch ( position ) {

			case 'left':
				n.clonePosition( $('newOfferBannerWrapper'), { offsetLeft: -w });
				this.slide( n, {x:w} );
			break;

			case 'right':
				n.clonePosition( $('newOfferBannerWrapper'), { offsetLeft: w });
				this.slide( n, {x:-w} );
			break;

			case 'bottom':
				n.clonePosition( $('newOfferBannerWrapper'), { offsetTop: h });
				this.slide( n, {x:h} );
			break;
			
		}

	},

	goBack: function () {

		//  Get prev image index
		var i = ( this.currentIndex > 0 ) ? this.currentIndex - 1 : this.banners.length - 1;
		this.changeImage( i, 'left' );
		this.currentIndex = i;

	},

	goNext: function () {

		//  Get next image index
		var i = ( this.currentIndex < ( this.banners.length - 1 ) ) ? this.currentIndex + 1 : 0;
		this.changeImage( i, 'right' );
		this.currentIndex = i;

	},

	slide: function ( element, offset ) {
		
		offset.x = offset.x || 0;
		offset.y = offset.y || 0;
		
		new Effect.Move( element, { x: offset.x, y: offset.y, mode: 'relative', duration: 0.6 });
	},

	startTimer: function ( delay ) {
		delay = delay || this.delay;
		this.timer = new PeriodicalExecuter( this.goNext.bindAsEventListener( this ), delay );
	},

	stopTimer: function () {

		//  Stop the timer (probably a click on a manual link)
		if ( this.timer !== false ) {
			this.timer.stop();
			this.timer = false;
		}

	}
}