jQuery.fn.extend({
	charge_image: function(uo,lien) {
		var o = $.extend({
			maxWidth: 200,
			maxHeight: 200,
			background_color: '#fff',
			captify: false,
			resize: true
		}, uo);
		$(this).each(function() {
			var image = new Image();
			var img = $(this);
			
			// attacher les options directement a chaque element
			if (!img.data('charge_image_opt'))
			{
				img.data('charge_image_opt', o);
			}
			
			image.onerror = function()
			{
			  //alert("Erreur lors du chargement de l'image :\n" + src);
			  image.alt ="Erreur image";
			  image.title ="Erreur image";
			  image.src = "images/picto/indisponible_petit.png"
			}
			
			// une fois l'image chargée :
			image.onload = function()
			{
			  // si l'image doit etre redimensionnée
			  var reduction = 1;
			  if(o.maxWidth && o.maxHeight)
				 if(image.width > o.maxWidth || image.height > o.maxHeight)
					reduction = Math.max(image.width/o.maxWidth, image.height/o.maxHeight);
			
			  var largeur = Math.round(image.width / reduction);
			  var hauteur = Math.round(image.height / reduction);
			  // on affiche l'image
			  img.css("padding-top","");
			  img.css("padding-bottom","");
			  img.css("padding-left","");
			  img.css("padding-right","");
			  img.attr("src",image.src);
			  img.src = image.src;
			  img.attr("width",largeur);
			  img.attr("height",hauteur);
			  img.css("width",largeur + "px");
			  img.css("height",hauteur + "px");
			  
			  if(o.resize)
			  {
				  // on ajuste le padding bottom et top
				  if(hauteur<o.maxHeight)
				  {
					var marge_haut = Math.round((o.maxHeight-hauteur)/2);
					var marge_bas = o.maxHeight-(hauteur+marge_haut);
					img.css("padding-top",marge_haut+"px");
					img.css("padding-bottom",marge_bas+"px");
				  }
				  
				  // on ajuste le padding left et right
				  if(largeur<o.maxWidth)
				  {
					var marge_gauche = Math.round((o.maxWidth-largeur)/2);
					var marge_droite = o.maxWidth-(largeur+marge_gauche);
					img.css("padding-left",marge_gauche+"px");
					img.css("padding-right",marge_droite+"px");
				  }
				  
				  img.css("background-color",o.background_color);
			  }
			  
			  img.css("display","");
			  
			  if(o.captify)
			  	img.captify({hideDelay: 0});
			}
			
			if(lien!=null && lien !="")
				image.src = lien;//+"?"+new Date().getTime();
			else
				image.src = $(this).attr("src");
		});
	},
	
	// permet de changer une image
	change_image : function(lien){
		$(this).each(function(){
			if($(this).data('charge_image_opt'))
				$(this).charge_image($(this).data('charge_image_opt'),lien);
		});
	}
});
