//NOTE: Requires Mootools 1.2 (http://mootools.net)

var Carousel = new Class({
	
	//User settings
	timeBetweenTransitions: 7000,
	transitionSpeed: 1000,
	requestUrl: '/ajax/get_carousel_promos/',
	carouselId: 'carousel',
	
	//Class vars
	promos: {},
	currentPromoNum: 0,
	
	//Constructor
	initialize: function(dbKey)
	{		
		//Get list of promos
		var url = this.requestUrl + dbKey;
		var request = new Request.JSON({url: url});
		request.addEvent('onComplete', this.onPromosRequestCompleted.bind(this));
		request.get();
	},
	
	//AJAX callback - handles returned list of promos
	onPromosRequestCompleted: function(promos)
	{
		//Store promo info
		this.promos = promos;
		
		//Exit if there aren't any other carousels to switch between
		if (this.promos.length <= 1) return;
		
		//Preload images
		var images = new Array();
		for (var i = 0; i < this.promos.length; i++)
		{
			var imgUrl = this.promos[i]._images.main.Url;
			images.push(imgUrl);
		}
		new Asset.images(images);
		
		//Start animation timers when DOM is ready
		window.addEvent('domready', this.initTransitions.bind(this));
	},
	
	//Sets up main interval timer
	initTransitions: function()
	{
		setInterval(this.startTransition.bind(this), this.timeBetweenTransitions);
	},
	
	//Begins carousel transition with fade out
	startTransition: function()
	{
		var fadeOut = new Fx.Tween(this.carouselId, {property: 'opacity', duration: this.transitionSpeed, transition: 'quad:out', onComplete: this.changePromo.bind(this)});
		fadeOut.start(1,0);
	},
	
	//Changes contents of DOM elements and fades in to view
	changePromo: function()
	{
		//Get the promo we'll be switching to
		this.currentPromoNum = this.currentPromoNum < this.promos.length - 1 ? this.currentPromoNum + 1 : 0;
		var newPromo = this.promos[this.currentPromoNum];
			
		//Change the content of the carousel DOM elements
		$$('#carousel img').set('src', newPromo._images.main.Url);
		$$('#carousel .section').set('text', newPromo.Header);
		$$('#carousel .header').set('text', newPromo.Text1);
		$$('#carousel .subheader').set('text', newPromo.Text2);
		$$('#carousel a').set('href', newPromo.LinkUrl);
		$$('#carousel .text').removeEvents('click'); //Remove previous click events (for IE)
		$$('#carousel .text').addEvent('click', function(){ document.location = newPromo.LinkUrl; });
		
		//Fade in
		var fadeIn = new Fx.Tween(this.carouselId, {property: 'opacity', duration: this.transitionSpeed, transition: 'quad:in'});
		fadeIn.start(0, 1);
	}
	
});