(function($) {
	$.fn.extend({ imgResizer:function(){
		return this.each(function(){
			var element=this;
			var rimg=document.createElement("img");
			var img=$("img",this).get(0);
			var imgL=document.createElement("img");
			var dHeight=parseInt($(element).css("height"));
			var dWidth=parseInt($(element).css("width"));

			$(element).css("position","relative");
			$(element).css("overflow","hidden");
			$(element).css("display","block");

			rimg.src=img.src;
			imgL.src=setLoader();
			$(img).css({opacity:0,display:"none"});
			$(imgL).css("top",(dHeight/2)-10);
			$(imgL).css("left",(dWidth/2)-10);
			$(imgL).css("position","absolute");
			$(imgL).appendTo($(img).parent());
			$(imgL).animate({opacity:1});
			loading();

			function setLoader(){
				var parentNode=element
				var rgb=0;
				while(parentNode!=$("body").get(0)){
					rgb=$(parentNode).css("background-color").match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
					if (rgb!=null) break;
					parentNode=parentNode.parentNode;
				}
				if (rgb==null)rgb=Array(0,255,255,255);
				if ((rgb[2]<rgb[3] && rgb[3]<250) || (rgb[1]<80 && rgb[2]<80) ) return "http://www.salutmentalondarasio.cat/img/loader_dark.gif";
				else return "http://www.salutmentalondarasio.cat/img/loader_light.gif";
			}
			
			function imgLoaded() {
				if (!rimg.complete)return false;
		    if (typeof rimg.naturalWidth != "undefined" && rimg.naturalWidth == 0)return false;
		    return true;
			}

			function loading(){
				if (imgLoaded()){
					$(imgL).animate({opacity:0},500,function(){$(imgL).css("display","none");});
					img.src=rimg.src;
				 	setTimeout(function(){loaded();},500);
				 	return;
				}
				setTimeout(function(){loading();},100);
			}
	
			function loaded(){
				$(img).css("opacity",0);
				$(img).css("display","block");
				img.src=rimg.src;

				var scale=rimg.height/rimg.width;
	
				var iWidth=dWidth;
				var iHeight=dWidth*scale;
		
				if (iHeight<dHeight){
						var rest=dHeight-iHeight;
						iHeight+=rest;
						iWidth+=rest/scale;
				}
				$(img).css("margin-top",0);
				$(img).css("margin-left",0);
				$(img).css({height:iHeight,width:iWidth});
				$(img).animate({opacity:1},2000);

			}
		});
	}});

})(jQuery);


