jQuery(function($) {
	$.fn.preload = function(load, progress){
		var imgs=[], preloaded=[];
		var self=this;
		
		this.filter("img").each(function(){
			imgs.push($(this).attr("src"));
		});

		var run = function() {
			var n = preloaded.length,m=imgs.length;

			if ($.isFunction(progress))
				progress.apply(self,[n,m]);
			
			var deq = function(e) {
				if (e.target.parentNode === null) {/* IE bug */
					$(this).unbind("error");
					$(this).unbind("load");
					setTimeout(function(){run.call(self)}, 200);
				}
			};
			if (n < m) {
				preloaded[n] = $("<img/>").load(deq).error(deq).attr({src:imgs[n]}); 
				return;
			}
			if ($.isFunction(load))
				load.call(self);
		};
		run();
		
		return this;
	};

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

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

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

			if (n < m)
				return;

			clearTimeout(h);
			if ($.isFunction(onload))
				onload.call(self);
		};

		var deqe = function(e) {
			console.log("Errore nel caricamento di "+$(this).attr("src"));
			return deq(e);
		};
		
		coda.each(function(){
			$("<img>").load(deq).error(deqe).attr({
				src: $(this).attr("src")
			});
		});
		
		h = setInterval(deq, 500);
		
		return this;
		
	};
});
