// Versión modificada del plugin de Greg Winiarski
// URL: http://ditio.net/2010/01/02/jquery-image-resize-plugin/
//
// Esta versión está preparada para tomar como maxWidth y maxHeight los valores definidos por css.
// Por lo tanto, es necesario tenerlos definidos previamente por css.
//

(function($) {
    $.fn.resize = function() {
 
      this.each(function() {
			
				if(this.tagName.toLowerCase() != "img") {
					// Only images can be resized
					return;
				} 

				//obtenemos el tamaño máximo por defecto definido por css
				var maxWidth = $(this).width();
				var maxHeight = $(this).height();

				this.onload = function() { imageLoaded(this, maxWidth, maxHeight); }
				
			});
			
			function imageLoaded(img, maxWidth, maxHeight) {
		
				//obtenemos el tamaño real
				var width = img.naturalWidth;
				var height = img.naturalHeight;
				if(!width || !height) {
					//alert('ie?');
					// Ooops you are an IE user, let's fix it.
					var img = document.createElement('img');
					img.src = img.src;
					width = img.width;
					height = img.height;
				}

				//alert('src='+img.src+' maxWidth='+maxWidth+' maxHeight='+maxHeight+' width='+width+' height='+height);
		
				var pWidth = 1;
				if(maxWidth != null) {
					pWidth = width/maxWidth;
				}
				var pHeight = 1;
				if(maxHeight != null) {
					pHeight = height/maxHeight;
				}
		
				var reduce = 1;

				if(pWidth > pHeight) {
					reduce = pWidth;
				} else {
					reduce = pHeight;
				}
		
				if(reduce < 1) {
					reduce = 1;
				}
					
				if(pWidth > pHeight) {
					$(img)
						.removeAttr('height')
						.css({'height':'auto'})
						.attr("width", width/reduce);
				} else {
					$(img)
						.removeAttr('width')
						.css({'width':'auto'})
						.attr("height", height/reduce);
				}
			}
    }
})(jQuery);

