

Rotator = Class.create({
	upperimg: null,
	lowerimg: null,
	images: null,
	currentImage: 0,
	duration: 2.5,
	pause: 6500,
	waitCount: 0,

	initialize: function(img)
	{
		// Check if image already has a rotator
		if (img.rotator != undefined) return false;
		
		// Add rotator to image, to prevent multiple rotators working on the same image
		img.rotator = this;
		
		// Set reference to upper image
		this.upperimg = img;
		
		// Absolutize image
		this.upperimg.absolutize();
		
		// Add 1 to z-index, so we can put an image behind
		// Get
		zIndex = this.upperimg.getStyle('z-index');
		if (zIndex == null) zIndex = 1;
	
		// Set +1
		this.upperimg.setStyle({zIndex: zIndex+1})
		
		// Setup lower image
		this.lowerimg = new Element('img', { src: ''}).setStyle({
			position: 'absolute',
			zIndex: zIndex,
			left: '0px',
			top: '0px'
		});
		this.lowerimg.hide()
		
		// Add to same container as upper image
		this.upperimg.getOffsetParent().insert(this.lowerimg);
		
		// Clone postion
		this.lowerimg.clonePosition(this.upperimg);
		
		this.lowerimg.setStyle({
			left: this.upperimg.getStyle('left'),
			top: this.upperimg.getStyle('top')
		});
		
		// Init image array
		this.images = new Array;
	
		// Add current image
		this.addImage(this.upperimg.src);
	},
	
	addImage: function(src)
	{
		img = new Element('img', {src: src});
		this.images.push(img);
	},
	
	cb: function(event)
	{
		alert(this.src + ' loaded' + this.complete);
	},
	
	rotate: function(increment)
	{
		if (increment != false)
		{
			// Get next index 
			if (++this.currentImage >= this.images.length) this.currentImage = 0;
		}
		
		// Get next image
		nextimg = this.images[this.currentImage];

		// Wait until image is loaded
		// Todo: if waited for longer then x seconds, skip to next image; maybe even remove faulty image from array
		if (!nextimg.complete)
		{
			if (this.waitCount++ > 25)
			{
				alert("Wait too long for: " + nextimg.src);
				this.rotate();
				return;
			}
			setTimeout("$('"+ this.upperimg.id +"').rotator.rotate(false)", 200); 
			return;
		}
		
		// Do another rotate after this.pause miliseconds
		setTimeout("$('"+ this.upperimg.id +"').rotator.rotate()", this.pause);

		// Set new image
		if (this.upperimg.visible())
		{
			this.lowerimg.src = nextimg.src;
			this.lowerimg.show();
			this.upperimg.fade({duration: this.duration});
		} else
		{
			this.upperimg.src = nextimg.src;
			this.upperimg.appear({duration: this.duration});
		}
	}	
});

function initRotators()
{
	rotators = $$('img.rotator');
	
	rotators.each(function(item) {
	  item.rotator.rotate();
	});
	
	new Effect.Appear($('banner_textbox'));
}

Event.observe(window, 'load', initRotators, false);