var ImagePreloader = function(name) {	
	if (typeof(name) != 'string') {
		alert('ImagePreloader: name required (constructor parameter).');
		return null;
	}

	this.name = name;
	this.stack = [];
	this.load = [];
	this.ready = 0;
	this.onLoadFunction = null;
}

ImagePreloader.prototype.setOnload = function(func) {
	this.onLoadFunction = func;
}

ImagePreloader.prototype.add = function(image) {
	if (this.exists(image)) return;
	this.stack.push(image);
}

ImagePreloader.prototype.remove = function(image) {
	var so = this.stack.length;
	var temp = [];
	for (var i = 0; i < so; i++) {
		if (this.stack[i] != image) temp.push(this.stack[i]);
	}
	this.stack = temp;
}

ImagePreloader.prototype.exists = function(image) {
	var so = this.stack.length;
	for (var i = 0; i < so; i++) {
		if (this.stack[i] == image) return true;
	}
	return false;
}

ImagePreloader.prototype.setReady = function() {
	//alert(this.ready +':'+ this.stack.length);
	this.ready++;
	if (this.ready == this.stack.length) this.onLoadFunction();
}

ImagePreloader.prototype.preload = function() {
	if (this.onLoadFunction === null) {
		alert('ImagePreloader: on load function required.');
		return;
	}
	this.ready = 0;
	var so = this.stack.length;
	if (!so) this.onLoadFunction();
	
	for (var i = 0; i < so; i++) {
		//alert(this.stack[i]);
		this.load[i] = new Image();
		this.load[i].id = i;
		this.load[i].parent = this.name;
		this.load[i].src = this.stack[i];
		if (this.load[i].complete) this.setReady();
		this.load[i].onerror = function() {
			var n = this.id;			
			if (window[this.parent]) window[this.parent].setReady();
		}
		this.load[i].onload = function() {			
			var n = this.id;			
			if (window[this.parent]) window[this.parent].setReady();
		}
	}	
}

