/**
 * based on the preloader found at 
 * http://www.webreference.com/programming/javascript/gr/column3
 */
 
function ImagePreloader(options){
	// store the oncomplete
	this.onupdate = options.onupdate;
	this.oncomplete = options.oncomplete;
	// initialize internal state.
	this.nLoaded = 0;
	this.nProcessed = 0;
	this.aImages = [];
	
	// record the number of images.	
	this.nImages = options.images.length;
	this.cancel = false;
	
	// for each image, call preload()
	for ( var i = 0; i < options.images.length; i++ ){
		this.preload(options.images[i]);
	}
}

ImagePreloader.prototype.preload = function(image){
	// create new Image object and add to array
	var oImage = new Image();
	this.aImages.push(oImage);
	
	// set up event handlers for the Image object
	oImage.onload = ImagePreloader.prototype.onload;
	oImage.onerror = ImagePreloader.prototype.onerror;
	oImage.onabort = ImagePreloader.prototype.onabort;
	
	// assign pointer back to this.
	oImage.oImagePreloader = this;
	oImage.bLoaded = false;
	
	// assign the .src property of the Image object
	oImage.src = image;
}

ImagePreloader.prototype.onComplete = function(){
	if(this.cancel){
		return;
	}
	this.nProcessed++;
	if(typeof this.onupdate == "function"){
		this.onupdate(this.nLoaded, this.aImages.length);
	}
	if (this.nProcessed == this.nImages && typeof this.oncomplete == "function"){
		this.oncomplete(this.aImages, this.nLoaded);
	}
}

ImagePreloader.prototype.onload = function(){
	this.bLoaded = true;
	this.oImagePreloader.nLoaded++;
	this.oImagePreloader.onComplete();
}

ImagePreloader.prototype.onerror = function(){
	//console.log("error");
	this.bError = true;
	this.oImagePreloader.onComplete();
}

ImagePreloader.prototype.onabort = function(){
	//console.log("abort");
	this.bAbort = true;
	this.oImagePreloader.onComplete();
}
 
ImagePreloader.prototype.cancelPreload = function(){
	this.cancel = true;
	for(var i = 0; i < this.nImages; i++){
		this.aImages[i].src = "";
	}
}
