(function($)
{
	$.resizeImages = {
		
		onLoadImage: function($image, sceneWidth, sceneHeight, ratioScene)
	    {			
			if( $image[0].naturalWidth )
			{
				var imageWidth = $image[0].naturalWidth;
	            var imageHeight = $image[0].naturalHeight;
			}
			else {
				var imageWidth = $image[0].width;
	            var imageHeight = $image[0].height;
			}
			
	        var ratioImage = imageWidth / imageHeight;

	        if( ratioScene >= ratioImage )
	        {
	            var height = Math.ceil(sceneWidth / ratioImage);
	            $image.css({
	                'width': sceneWidth,
	                'height': height,
	                'position': 'absolute',
	                'left': 0,
	                'top': (sceneHeight - height) / 2 +'px'
	            });
	        }
	        else {
	            var width = Math.ceil(sceneHeight * ratioImage);
	            $image.css({
	                'width': width,
	                'height': sceneHeight,
	                'position': 'absolute',
	                'left': (sceneWidth - width) / 2 +'px',
	                'top': 0,
	            });
	        }
	    }
		
	};
	
    $.fn.resizeImages = function()
    {
        this.each(function()
        {
        	var scene = $(this);
            
            var sceneWidth = scene.innerWidth();
			var sceneHeight = scene.height();
            var ratioScene = sceneWidth / sceneHeight;

            scene.css({
                'overflow': 'hidden',
                'position': 'relative'
            });
            
            var images = scene.find('img');
            
            $.each(images, function(i, image)
            {
                var $image = $(this);
                
            	var img = new Image();
                img.src = image.src;
				
				if(img.complete) $.resizeImages.onLoadImage($image, sceneWidth, sceneHeight, ratioScene);
                else img.onload = $.resizeImages.onLoadImage($image, sceneWidth, sceneHeight, ratioScene);
            });
            
        });
    	
        return this;
    };
	
})(jQuery);
