jQuery(function($){
	$.fn.waitload = function(onload, progress){
		var coda=this.filter("img");
		var setup=false;
		var m=coda.length;
		
		var deq = function(e) {
			var n=0;
			
			coda=coda.not($(this));
			n=m-coda.length;

			coda.each(function(){
				if ($(this).attr("complete"))
					n++;
			});
			$(this).unbind("load");
			$(this).unbind("error");

			if ($.isFunction(progress))
				progress.apply(self,[n,m]);

			if (n < m)
				return;

			if ($.isFunction(onload)) {
				onload.call(self);
				onload=null;
			}
		};

		coda.each(function(){
			if (!$(this).attr("complete")) {
				setup=true;
				$(this).load(deq).error(deq).attr({
					src: $(this).attr("src")
				});
			}
		});

		if (!setup) {
			if ($.isFunction(progress))
				progress.apply(self,[m,m]);
			if ($.isFunction(onload))
				onload.call(self);
		}
		
		return this;
		
	};
});
