/*
	Fit an image to the parent container
	Author Fulvio Baratta
	Sample code
	$(".container img").fit();
*/
(function($){
	$.fn.fit = function(options) {
		var settings = {
			'keepAspectRatio' : true,
			'noCenter' : false
		};

		if (options) { 
			$.extend(settings, options);
		}
		return this.each(function() {
			var currEl = $(this);
			var container = currEl.parent();
			var divW, divH, contentW, contentH, padW, padH, newW, newH, 
				containerW, containerH;
			var divisor;
			
			containerW = container.width();
			containerH = container.height();
			contentW = currEl.width();
			contentH = currEl.height();
			
			if (settings.keepAspectRatio) {
				divW = contentW / containerW;
				divH = contentH / containerH;
				
				divisor = (divH > divW)?divH:divW;

				newW = contentW/divisor;
				newH = contentH/divisor;

				currEl.width(newW);
				currEl.height(newH);
				
				if (!settings.noCenter) {
					padW = (containerW - newW)/2;
					padH = (containerH - newH)/2;
				}
				
				currEl.css("padding",padH+"px "+padW+"px");
			}
			else {
				currEl.width(containerW);
				currEl.height(containerH);
			}
		});
	};
	$.fn.unfit = function() {
		return this.each(function(){
			var currEl = $(this);
			currEl.css("padding","0");
			currEl.width(currEl[0].naturalWidth);
			currEl.height(currEl[0].naturalHeight);
		});
	};
})(jQuery);
