////////////////////////////////////////////////////////////////////////////////

function preload_image( url ) {
	var image = new Image();
	image.src = url;
}

////////////////////////////////////////////////////////////////////////////////

function random_int( range ) {
	return Math.floor( Math.random() * range );
}

////////////////////////////////////////////////////////////////////////////////

function ImageSlot( div ) {
	var obj = this;

	this.div = $( div );

	this.anchor = $( "a", this.div );
	this.anchor.append( '<img class="image-fade" />' );
	this.base_image = $( "img.image-base", this.anchor );
	this.fade_image = $( "img.image-fade", this.anchor );
}

ImageSlot.prototype.fade_to = function( image_url, fade_time, link_url ) {
	var obj = this;

	this.image_url = image_url;
	this.link_url = link_url;

	this.fade_image.hide();
	this.fade_image.attr( "src", this.image_url );
	this.fade_image.fadeIn( fade_time, function() {
		obj.base_image.attr( "src", obj.image_url );
		obj.fade_image.hide();
		obj.anchor.attr( "href", obj.link_url );
	} );
};

////////////////////////////////////////////////////////////////////////////////

function RotatingImage( image_slot, image_list ) {

	this.image_slot = image_slot;
	this.image_list = image_list;
	this.current_index = 0;

	this.preload_images();

	this.update();
}

RotatingImage.prototype.preload_images = function() {

	this.images = new Array();
	for( var i = 0; i < this.image_list.length; i++ ) {
		var url = this.image_list[ i ].image_url;
		this.images[i] = new Image();
		this.images[i].src = url;
	}
}

RotatingImage.prototype.update = function() {

	var next_image  = this.image_list[ this.current_index ];

	this.image_slot.fade_to( next_image.image_url, 2000, next_image.link_url );
}

RotatingImage.prototype.rotate = function() {

	if( this.image_list.length < 1 ) { return; }

	// move to the next image in the list
	var next_index = (this.current_index + 1) % this.image_list.length;

	// only rotate to the next image if it has been loaded
	if( this.images[next_index].complete ) {
		this.current_index = next_index;
		this.update();
	}
}

////////////////////////////////////////////////////////////////////////////////

