(function($) {
    $.fn.fitbox = function(options) {
 
        var settings = $.extend({
            w: null,
			h: 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;
			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;
			}
			
			/////////////////////////////////////
			var newWidth, newHeight;
			//////////////////////////////////////
			if ( width<=settings.w && height<=settings.h ){//image smaller than the box
				newWidth	= width;		//no change in size
				newHeight	= height;		//no change in size
			} else {//image goes out of the box
				if (width>height) {//horizontal so fit it with WIDTH ruling
					newWidth	= settings.w;
					newHeight	= height*(settings.w/width);
				} else { //vertical. HEIGHT rules
					newHeight	= settings.h;
					newWidth	= width*(settings.h/height);
				}
			}//smaller than box?
			
			/// Center image to box
			var top_offset = (settings.h-newHeight)/2;
			var left_offset = (settings.w-newWidth)/2;
			
			return $(this).css({
				'width': 	newWidth,
				'height': 	newHeight,
				'top':		top_offset,
				'left':		left_offset
			});
			
        });
    }
})(jQuery);

