var Thumb = {
	
	Init: function () {
		$('img.thumb').each(function() {
			if($(this)[0].complete) {
				Thumb.Resize( $(this) );
			}
			else {
				$(this).load( function () {
					Thumb.Resize( $(this) );
				} );
			}
		} );
	},
	
	Resize: function ( $img ) {
		
		var $clone = $img.clone();
		
		$clone
			.appendTo('body')
			.load( function() {
				
				var div_width = $(this).attr('width');
				var div_height = $(this).attr('height');
		
				$(this).css( { width: 'auto', height: 'auto' } );
				
				var img_width = $(this).width();
				var img_height = $(this).height();
				
				var $div = $img.wrap( $('<div>') ).parent();
				
				$div.attr('class', $img.attr('class'))
					.css( {
						width: div_width, 
						height: div_height
					} );
				
				if (img_height > img_width) {
					
					new_width = Math.ceil((div_height / img_height) * img_width);
					new_height = div_height;
					
					$div.addClass('portrait');
					
				}
				else {
					
					new_width = div_width;
					new_height = Math.ceil((div_width / img_width) * img_height);
					
				}
				
				$img.removeAttr('class')
					.css( {
						width: new_width + 'px',
						height: new_height + 'px'
					} );
				
				$(this).remove();
				
			} );
		
	}
	
};

$(document).ready( function() { Thumb.Init(); } );