/*
	jQuery Image Resize plugin
	by Peter Snyder (snyderp@gmail.com)
	Resize an image keeping ratio to fix in a box
	Options:
		height and width: define the size of the box
		size: accepts either max or min.  Defines whether the passed sizes are the max or min sizes for the image
	
*/
(function () {

	$.fn.imagescale = function (options) {
	
		var opts = $.extend({}, $.fn.imagescale.defaults, options);
	
		return this.each(function () {
		
			var $this = $(this);
		
			var o = ($.meta) ? $.extend({}, opts, $this.data()) : opts;

			// Make sure this is an image, that at least a height or widht have been passed
			// and that the height and width attributes have been set in the image
			if ($this.is("img") && (o.height || o.width) && $this.attr("width") && $this.attr("height")) {
			
				var scale_direction = (o.size === "max") ? "max" : "min"; 
			
				if (o.height !== false) {
				
					$.fn.imagescale.oneWayScale($this, o.height, "height", scale_direction);						
				
				}
		
				if (o.width !== false) {
				
					$.fn.imagescale.oneWayScale($this, o.width, "width", scale_direction);
				}
			
			}
		
		});
	};
	
	// Scale the passed image to be no smaller than "size" if scale == "min"
	// or no larger than "size" if scale == "max" 
	// in the given direction ("height" or "width")
	$.fn.imagescale.oneWayScale = function (image, size, direction, scale) {
	
		var other_direction = (direction === "height") ? "width" : "height";
	
		var current = image.attr(direction);
	
		var resize = (scale === "max") ? (current > size) : (current < size);
	
		if (resize === true) {
		
			var other_size = (size / current) * image.attr(other_direction);
		
			image.attr(other_direction, other_size);
			image.attr(direction, size);
		
		}
		
		return true;
	
	};
	
	$.fn.imagescale.defaults = {
		height: false,
		width: 	false,
		size:	"max"
	};


})(jQuery);