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