/*
 * ImageRotation v0.1
 * Alex Panayotopoulos, Copyright (C) 2009 VisitScotland.com
 * 
 * Set up rotation of a set of images via the Prototype/script.aculo.us libraries
 * This script refers to 'images'; however, it can alse be applied to arbitrary elements, even those without
 * any image content at all. Notably, it can be applied to anchor tags which *contain* images, thus providing
 * a relevant link address for each image in a slideshow sequence.
 * 
 * flipTime: time (in milliseonnds) that each image is displayed for
 * fadeTime: time (in milliseconds) that an image takes to fade away
 * cssSelector: denotes the images to be rotated (e.g. '.slide', '#slideshow img')
 */
function ImageRotation(flipTime, fadeTime, cssSelector) {
	this.flipMs		= flipTime;
	this.fadeMs		= fadeTime;
	this.fadeSec	= fadeTime / 1000.0;
	
	this.images = $$(cssSelector);
	this.imgIndex = 0;
	
	/* Hide all but the first */
	for (var i = 1; i < this.images.length; i++) {
		new Effect.Opacity(this.images[i], {from: 1, to: 0, duration: 0});
		this.images[i].setStyle({zIndex: 0});
		this.images[i].hide();		// IE hack
	}
	
	/* Rotate from current to next image */
	this.rotateImage = function() {
		// Fade out old image
		var oldImgIndex = this.imgIndex;
		new Effect.Opacity(this.images[oldImgIndex], {from: 1, to: 0, duration: this.fadeSec});
		
		// Fade in new image
		var newImgIndex = (this.imgIndex + 1) % this.images.length;
		new Effect.Opacity(this.images[newImgIndex], {from: 0, to: 1, duration: this.fadeSec});
		
		// Schedule next rotation
		var self = this;
		setTimeout(function() { self.rotateImage(); }, this.flipMs);
		setTimeout(function() { self.raiseLowerAds(oldImgIndex, newImgIndex); }, this.fadeMs);
		
		this.images[newImgIndex].show();		// IE hack
		this.imgIndex = newImgIndex;
	}
	
	/* Raise new image over old (necessary for anchor tags) */
	this.raiseLowerAds = function(oldIndex, newIndex) {
		this.images[oldIndex].setStyle({zIndex: 0});
		this.images[oldIndex].hide();		// IE hack
		this.images[newIndex].setStyle({zIndex: 1});
	}
	
	/* Start image rotation */
	if (this.images.length > 1) {
		var self = this;
		setTimeout(function() { self.rotateImage(); }, this.flipMs);
	}
}