
Preloader = new Class({
	
	initialize : function(images) {
		this.images = images ? images : [];
		if (this.onImageLoad) {
			this.addEvent('onImageLoad', this.onImageLoad);
		}
		this.load(this.getNext());
	},

	load : function(i) {
		var image = this.images[i];
		if (image) {
			image.element = new Asset.image(image.path, {
				onload : this.loaded.bind(this, [i]),
				onerror : this.failed.bind(this, [i])
			});
		}
	},

	failed : function(i) {
		this.fireEvent('onImageFail', [i, this.images[i].path]);
		this.load.delay(100, this, [this.getNext(i)]);
	},

	loaded : function(i) {
		//fix bug in FF where mootools calls onload twice
		if (this.images[i].loaded) {
			return;	
		}
		this.images[i].loaded = true;
		var image = this.images[i];
		if (image) {
			var size = { x : image.element.width, y : image.element.height };
			this.fireEvent('onImageLoad', [i, this.images[i].path, size]);
		}
		this.load.delay(100, this, [this.getNext(i)]);
	},
	
	getNext : function(i) {
		return (i ? i : 0) + 1;
	}

});
Preloader.implement(new Events);

