﻿/* 
 * jQuery plugin - Preload And Resizing Image
 * Version 2.0
 * Copyright 2010 - Publication Fnac.com - Paris
 * Developped by Guillaume DIAS COELHO
 * More infos : integration@fnac.com
*/

(function($) {
	$.fn.preloadAndResize = function(options){
		var params = $.extend({}, $.fn.preloadAndResize.defaults, options);
        if (params.debugMode){$("body").append("<div id='dbug'></div>").css({"width":"500px","color":"#000","backgroundColor":"#fff","position":"absolute","zIndex":999,"top":0,"left":0});}			
		return this.each(function() {
		    var conteneur = $(this).parent();
			ImgUrl = $(this).attr('src');
			var obj = $(this);
			// On cache l'image pour le resize
			$(this).css("display","none");
			
			// on ajoute le noScan
			$(this).parent().append("<div class='replace'><img src='"+params.replaceBy+"' /></div>");
			
			var maxHeight = params.maxHeight;
			var maxWidth = params.maxWidth;
			
			$(this).load(function(){
				// CallBack : Image chargée
				var h = nH = obj.height();
				var w = nW = obj.width();
				
				if ((w >= maxWidth) || (h >= maxHeight)) {
					if ((h >= maxHeight) && (w >= maxWidth)) {
						if (h > w) {
							nH = maxHeight;
							nW = parseInt((w * nH) / h, 10);
						} else {
							nW = maxWidth;
							nH = parseInt((h * nW) / w, 10);
						}
					} else if ((h > maxHeight) && (w < maxWidth)) {
						nH = maxHeight;
						nW = parseInt((w * nH) / h, 10);
					} else if ((h < maxHeight) && (w > maxWidth)) {
						nW = maxWidth;
						nH = parseInt((h * nW) / w, 10);
					}
				}
				
				$(this).css( // on redimensionne l'image ici
                    {
                        "height":nH+"px",
                        "width":nW+"px",
                        "display":"block"
                    }
                ); 
                if (params.debugMode)
			    {
	               $("#dbug").append("New Height : "+nH+" NewWidth : "+nW+"<br/>");
                }
                
                $(".replace",conteneur).css("display","none"); // on cache la temporisation	
			}).each(function(){
                if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6)) 
                $(this).trigger("load");
            }).error(function(){
			    // Error : Lorsque l'image n'arriva pas à être chargée par le plugin
				//alert("erreur de chargement de l'image");
			})
		});
	};
	$.fn.preloadAndResize.defaults = {
	    maxHeight: 110,
	    maxWidth: 110,
	    replaceBy: "http://www4.fnac.com/Img/catalog/noscan_76x100.gif",
	    debugMode:0
	}
}) (jQuery) 

