/**
 * shrinking bigger images to small
 * 
 * @param integer 	maxWidth  
 * @param integer	maxHeight
 * @version 1.0
 * @type  jQuery
 * 
 * @author Basit (basit@imegah.com || http://Basit.me)
 */
(function($) {
	$.fn.imageShrink = function(maxWidth, maxHeight) {

		return this.each(function() {
			var img = $(this);
			var width = img.width();
			var height = img.height();
			
			if (maxWidth > width && maxHeight > height)
	            return this; // stops the method to continue
	   
	        if (width > height)
	        {
	            var ratio = width / img.width();
	            height = img.height() * ratio;
				var resize_by = 'width';
	        }
	        else
	        {
	            var ratio = height / img.height();
	            width = img.width() * ratio;
				var resize_by = 'height';
	        }
			
			// recheck if its still bigger after reducing the by width or height
			// but if its resized by height and height is still bigger, then resize by height
			if (width > maxWidth && !(resize_by == 'height' && height > maxHeight))
				resize_by = 'width';
			else if (height > maxHeight)
				resize_by = 'height';
				
			// resize 
			if (resize_by == 'width')
	        {
				width = maxWidth;
				ratio = width / img.width();
		        height = img.height() * ratio;
			}
	        else
	       	{
				height = maxHeight;
				ratio = height / img.height();
		        width = img.width() * ratio;
			}
	
			img.width(Math.round(width));
			img.height(Math.round(height));
		});
	};
})(jQuery);
