if(typeof jQuery != 'undefined') {
	(function($) {
		$.fn.extend({
			imageFit: function(o) {
				var $$ = $(this);
			
				$().ready(function() {
					$$.imageFitResize(o); 
				});
				$(window).bind('resize.imageFitResize', function() {
					$$.imageFitResize(o);
				});
			}
		});
		
		$.fn.extend({
			imageFitResize: function(options) {	
				return this.each(function(){
					var $$, $img, src, height, width, type, ratio, cssHeight, cssWidth, cssTop;
					$$		= $(this);
					$img	= $$.find('img');
					src		= $img.attr('src');
					cheight	= parseInt($(window).height(), 10) - options.offset.top;
					cwidth	= parseInt($('#content').width(), 10); // - options.offset.left
					
					$$.css({
						height: cheight,
						width:	cwidth
					});
					
					$('<img />').load(function(){
						height	= this.height;
						width	= this.width;
						ratio	= height / width;
						
						type 			= 'landscape';
						cssHeight 		= 'auto';
						cssWidth 		= '100%';
						cssTop			= 'auto';
						currentHeight	= parseInt($$.css('height'), 10);
						currentWidth	= parseInt($$.css('width'), 10);
						
						if(parseInt(height, 10) > currentHeight) {
							cssHeight	= Math.round(currentHeight);
							cssWidth	= Math.round(currentHeight / ratio);
							
							if(parseInt(cssWidth, 10) > currentWidth) {
								cssHeight	= Math.round(currentWidth * ratio);
								cssWidth	= Math.round(currentWidth);
								cssTop 		= Math.round((currentHeight - parseInt(cssHeight, 10)) / 2);
							}
						}
						else if(parseInt(height, 10) <  currentHeight) {
							cssTop = Math.round((currentHeight - parseInt(height, 10)) / 2);
						}
						
						if(height > width) {
							type 		= 'portrait';
							cssHeight 	= '100%';
							cssWidth 	= 'auto';
						
							if(parseInt(width, 10) > currentWidth) {
								cssHeight	= Math.round(currentWidth * ratio);
								cssWidth	= Math.round(currentWidth);
								
								if(parseInt(cssHeight, 10) > currentHeight) {
									cssHeight	= Math.round(currentHeight);
									cssWidth	= Math.round(currentHeight / ratio);
								}
							}
						}
													
						$img.css({
							position: 	'relative',
							//left: 	'auto',
							//top: 		cssTop,
							height: 	cssHeight,
							width:		cssWidth,
							//margin:	'0 auto',
							padding:	0
						}).attr({
							height: 	height,
							width:		width
						});

						if(cheight > height) {
							$$.css({
								height:	height,
								width:	width
							});
						}
						
						if(typeof options.callback === 'function') {
							options.callback.call(this, $$, $img, $img.height(), $img.width(), options);
						}
						
					}).attr('src', src);
				});
			}
		});
		
	})(jQuery);
}
