/*
	Rotating Images
	Dave Brown <dave@anticlockwise.com.au>
*/

var RotatingImages = {

	init: function(options){
		this.options = $extend({
			fadeDuration: 300,
			containerId: 'rotatingimages'
		}, options || {});
		
		this.images = [];
		this.currentImageNum = -1;
		
		this.container = $(this.options.containerId);
		
		this.hreftarget = new Element('a',{'href':'#','styles':{'display':'block'}});
		this.hreftarget.injectInside(this.container);	
		
		this.fx = {
			image: this.container.effect('opacity', {duration: 1000, onComplete:this.fadeIn.bind(this)})
		}
		this.fx.image.set(0);
		this.getImages();
	},

	getImages: function(){

		//this.fx.image.hide();
		//this.center.className = 'ubLoading';
		
		// start XHR call to content
		var rootLayouts = new Json.Remote("/direct/Mod_RotatingImages/getImages", {onComplete: this.processImages.bind(this)}).send();
	},

	processImages: function(req){
		this.images = req;
		this.nextImage();
		this.nextImage.periodical(6500,this);
	},
	
	loadImage: function(){
		this.preload = new Image();
		this.preload.onload = this.showImage.bind(this);
		this.preload.src = this.images[this.currentImageNum][0];
	},
	
	showImage: function(){
			this.fx.image.start(0);
	},
	
	fadeIn: function()
	{
		if (this.preload)
		{
			this.container.style.backgroundImage = 'url('+this.images[this.currentImageNum][0]+')';
			this.hreftarget.href = '';
			if (this.images[this.currentImageNum][1] != '')
			{
				this.hreftarget.href = this.images[this.currentImageNum][1];
			}
			this.hreftarget.style.width = this.container.style.width = this.preload.width+'px';
			this.hreftarget.style.height = this.container.style.height = this.preload.height+'px';
			this.fx.image.start(1);
			// clear the preloader
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		
	},
	nextImage: function(){
		this.currentImageNum = this.nextImageIndex();
		this.loadImage();
	},
	
	nextImageIndex: function()
	{
		var nextNum = this.currentImageNum + 1;
		if (nextNum == this.images.length) nextNum = 0;
		return nextNum;
	}
};

window.addEvent('domready', RotatingImages.init.bind(RotatingImages));