/*
  ImagePreloadQueue - Controls the loading order of images in HTML documents

      This code is released under the GPL
      see preloader.txt for details and documentation

  March 3rd 2007
*/

function ImagePreloadQueue() {
	this.loadedImageUrls = new Array();
	this.imageQueue = new Array();
	this.busy = false;
	this.currentImageUrl = null;
}

ImagePreloadQueue.prototype.removeFromQueue = function( imageObj ) {
	for( var i = 0; i < this.imageQueue.length; i++ ) {
		if( this.imageQueue[i].src == imageObj.src ) {
			return( this.imageQueue.splice( i, 1 )[0] );
		}
	}
}

ImagePreloadQueue.prototype.addToQueue = function( imageObj, adder ) {
	if( !this.isLoaded( imageObj ) ) {
		this.removeFromQueue( imageObj ); // if the image is already in the queue remove it.
		adder.call( this.imageQueue, imageObj );
		if( !this.busy )
			this.loadNext();
	}
}

ImagePreloadQueue.prototype.addToFront = function( imageObj ) {
	this.addToQueue( imageObj, Array.prototype.unshift );
}

ImagePreloadQueue.prototype.addToBack = function( imageObj ) {
	this.addToQueue( imageObj, Array.prototype.push );
}

ImagePreloadQueue.prototype.addArrayToBack = function( imageObjArray ) {
	for( var i = 0; i < imageObjArray.length; i++ ) {
		this.addToBack( imageObjArray[i] );
	}
}

ImagePreloadQueue.prototype.isLoaded = function( imageObj ) {
	// check if the image is being loaded right now
	if( this.currentImageUrl == imageObj.src ) {
		return true;
	}

	// check if the image was already loaded
	for( var i = 0; i < this.loadedImageUrls.length; i++ ) {
		if( this.loadedImageUrls[i] == imageObj.src ) {
			return true;
		}
	}
	
	return false;
}

ImagePreloadQueue.prototype.loadNext = function() {
	if( this.imageQueue.length == 0 ) {
		this.busy = false;
		return;
	}
	this.currentImageUrl = this.imageQueue[0].src;
	this.busy = true;
	var pseudoImage = this.imageQueue.shift();
	var realImage = new Image();
	var scope = this;
	realImage.onload = function() {
		this.onload = null;
		if( pseudoImage.onload )
			pseudoImage.onload();
		scope.loadedImageUrls[scope.loadedImageUrls.length] = pseudoImage.src;
		scope.currentImageUrl = null;
		scope.loadNext();
	}
	realImage.onerror = function() {
		realImage.onerror = null;
		if( pseudoImage.onerror )
			pseudoImage.onerror();
		scope.loadNext();
	}
	realImage.onabort = function() {
		realImage.onabort = null;
		if( pseudoImage.onabort )
			pseudoImage.onabort();
		scope.loadNext();
	}
	realImage.src = pseudoImage.src;
}

ImagePreloadQueue.prototype.backgroundReplacer = function( el, imageUrl ) {	return( {
		src: imageUrl,
		onload: function () {el.style.backgroundImage = "url('" + imageUrl + "')";
		}
	} );

}
