/**
 * Created By: Peter CICMAN, Divio GmbH
 *
 * provides simple image rotation with effect
 * requires:
 *  div element on page with id as first constructor param	
 * 	array of images as second parameter for constructor function
 */

var RBox = Class.create();
RBox.prototype = {
	animationSpeed: 1,

	images: [],
	lastImage: "",
	inForeward: 0,

	
	initialize: function(target_div_id, image_set) {	
		this.images = image_set;
		this.target_div = $(target_div_id);
		if (this.images.length > 1) {
			this.prepareImages();
			new PeriodicalExecuter(this.switchImage.bind(this), 5);
		}
	},

	getRandomImage: function() {
		do {
			var rnd = Math.floor(Math.random() * (this.images.length));
			var newImage = this.images[rnd];
		} while (newImage == this.lastImage && this.images.length > 0);
		return newImage;
	},

	prepareImages: function() {
		this.target_div.innerHTML = "";
		for (i=0; i<=1; i++) {
			this["target_" + i] = document.createElement("img");
			this["target_" + i].setAttribute("id", "rotator_" + i);
			this.target_div.appendChild(this["target_" + i]);	
			this["target_" + i].style['position'] = 'absolute';
		}
		this.target_0.src = this.target_1.src = this.getRandomImage();
	},
	
	switchImage: function(pe) {
		var newF = 1 - this.inForeward;
		this.lastImage = this["target_" + (newF)].src = this.getRandomImage();;
		this["target_" + (this.inForeward)].style['zIndex'] = 1;
		new Effect.Opacity("rotator_" + this.inForeward, { duration: this.animationSpeed, from: 1, to: 0.0 });
		new Effect.Opacity("rotator_" + newF, { duration: this.animationSpeed, from: 0, to: 1.0 });
		this.inForeward = newF;
	}
}

function initRBox() { myRBox = new RBox("rotatehere", rbox); }
Event.observe(window, 'load', initRBox, false);
