(function($){

 	$.fn.extend({ 
 		
 		pageimage: function() {
			
			var init = function(target){
				var win = $(window);
				win.data('pageresize-target', target);
				win.resize( $.proxy( update, this ) );
				
				var link = $('a', target).first().attr('href');
				target.html('');
				
				var image = $('<img src="'+ link +'" />');
				image
					.appendTo(target)
					.hide()
					.load( $.proxy( loaded, this) );
					
				updateBackground(win, target);
			}
			
			var update = function() {
				var win = $(window);
				var target = win.data('pageresize-target');
				
				updateBackground(win, target);
				updateImage(win, target);
			}
			
			var updateBackground = function(win, target) {
				var width = win.width() - target.offset().left;
				var height = win.height();
				
				target
					.css('overflow','hidden')
					.css('width', width +'px')
					.css('height', height +'px');
			}
			
			var updateImage = function(win, target) {
				var width = win.width() - target.offset().left;
				var height = win.height();

				var image = $('img', target).first();	
				var imageWidth = image.data('width');
				var imageHeight = image.data('height');
				var ratio = imageHeight / imageWidth;

				if((height/width) > ratio){
				    image.height(height);
				    image.width(height / ratio);
				} else {
				    image.width(width);
				    image.height(width * ratio);
				}
			}
			
			var loaded = function(event) {
				var image = $(event.currentTarget);
				image.data('width', image.width());
				image.data('height', image.height());
				update();
				
				image.fadeIn(2000);
			}
		
    		return this.each(function() {
				init($(this));
    		});
    	}
	});
})(jQuery);
