// JavaScript Document
function ImageRotator() {
	args=$A(arguments);	
	this.targetEl=document.getElementById(args.shift());
	
	// Create an overlay image so we can fade between the two.
	var newEl=document.createElement('img');
	newEl.style.position="absolute";
	newEl.style.zIndex=2;
	this.overlayEl=this.targetEl.parentNode.insertBefore(newEl, this.targetEl.nextSibling);
	this.overlayEl.width=this.targetEl.width;
	this.overlayEl.height=this.targetEl.height;
	this.overlayEl.style.left=this.targetEl.style.left;
	this.overlayEl.style.top=this.targetEl.style.top;
	
	this.rotationType=args.shift().toString().toLowerCase();
	this.delay=args.shift();
	if (this.delay<5000) {
		this.delay=5000;
	}
	this.images=args;
	this.currentImage=0;
	this.targetEl.ImageRotator=this;
	
	// PreCache the images for smoother transitions
	this.imageCache=[];
	for (i=0; i<this.images.length; i++) {
		this.imageCache[i]=new Image();
		this.imageCache[i].src=this.images[i];
	}
	
	this.lastComplete=true;
	
	this.rotate();
}

ImageRotator.prototype.rotate=function() {
	// Skip this rotation if the last one isn't fully finished yet.
	var _that=this;
	if (!this.lastComplete) {
		setTimeout(function() {
			_that.rotate();
		}, this.delay);
	}
	
	// Put up the incomplete flag
	this.lastComplete=false;
	
	// Select the next image
	if (this.rotationType=="random") {
		isNew=false;
		while (!isNew) {
			nextImg=Math.floor(Math.random()*this.images.length);
			if ((this.images.length<2) || (nextImg!=this.currentImg)) {
				isNew=true;
			}
		}
		this.currentImg=nextImg;
	} else {
		this.currentImg=(this.currentImg+1) % this.images.length;
	}
	
	// Figure out what the new image is going to be.
	this.newImg=this.images[this.currentImg];
	
	// Ensure the overlay is transparent so it doesn't show the image loading.
	$(this.overlayEl).setOpacity(0);
	
	// Load the new image in to the overlay
	this.overlayEl.src=this.newImg;
	
	// Call PartII (used to wait for the image to load first)
	this.rotatePartII();
}

ImageRotator.prototype.rotatePartII=function() {
	var _that=this;
	
	// If the overlay hasn't loaded in yet, try again in another 0.1 seconds
	if (!this.overlayEl.complete) {
		setTimeout(function() {
			_that.rotatePartII();
		}, 100);
		return;
	}
	
	// Start the transition animation
	new Effect.Fade($(this.overlayEl), {
		duration: 1.0, 
		from: 0.01, 
		to: 0.99,
		afterFinish: function() {
			// Once done
			// Attempt to swap out the underneath image
			_that.targetEl.src=_that.newImg;
			// Wait for it before hiding the overlay
			_that.waitForImage();
		}
	});
}

ImageRotator.prototype.waitForImage=function() {
	var _that=this;
	if (this.targetEl.complete) {
		$(this.overlayEl).setOpacity(0);
		this.lastComplete=true;
		setTimeout(function() {
			_that.rotate();
		}, this.delay);
	} else {
		setTimeout(function() {
			_that.waitForImage();
		}, 100);
	}
}
