// function log() {
// 	if (window.console && window.console.log)
// 		window.console.log('[resize]' + Array.prototype.join.call(arguments,' '));
// };

(function($) {
    $.fn.resizeImg = function(options) {
 
        var settings = $.extend({
            scale: 2,
            maxWidth: null,
			maxHeight: null,
			minHeight: null
        }, options);
 		
        return this.each(function() {
			
			
			// if(this.tagName.toLowerCase() != "img") {
			// 	// Only images can be resized
			// 	return $(this);
			// } 

			var width = this.naturalWidth;
			var height = this.naturalHeight;
			//
			var scaleWidth = 0;
			var scaleHeight = 0;
			
			if(!width || !height) {
				// Ooops you are an IE user, let's fix it.
				var img = document.createElement('img');
				img.src = this.src;
				
				width = img.width;
				height = img.height;
			}
						
			if(width - 50 > height && !$(this).hasClass('override_scaling'))
			{
				scaleWidth = 1;
			}
			
						
			if(settings.scale != 1) {
				width = width*settings.scale;
				height = height*settings.scale;
			}
			
			var pWidth = 1;
			if(settings.maxWidth != null) {
				pWidth = width/settings.maxWidth;
			}
			
			var pHeight = 1;
			if(settings.maxHeight != null) {
				pHeight = height/settings.maxHeight;
			}
			
			var reduce = 1;
			
			if(pWidth < pHeight) {
				reduce = pHeight;
			} else {
				reduce = pWidth;
			}
			
			// override if scaling by width
			if(scaleWidth == 1)
			{
				if(settings.minHeight && (height/pWidth) < settings.minHeight)
				{
					reduce = height/settings.minHeight
				}
				else
				{
					reduce = pWidth;	
				}
				
			}
			
			
			if(reduce < 1) {
				reduce = 1;
			}
			
			var newWidth = width/reduce;
			var newHeight = height/reduce;
			
			return $(this)
				.attr("width", newWidth)
				.attr("height", newHeight);
			
        });
    }
})(jQuery);
