(function($){	
	$.fn.fullscreendResize = function() {
		var ratio = Math.max($(window).width()/$(this).width(),$(window).height()/$(this).height());
		if ($(window).width() > $(window).height()) {
			$(this).css({width: $(this).width()*ratio,height:'auto'});
		} else {
			$(this).css({width:'auto',height: $(this).height()*ratio});
		}
		return this;
	};
	
	$.fn.fullscreend = function(options) {

		// custom settings not working yet
		settings = $.extend({
			wrap: false
		}, options);

		var self = $(this),
			wrap = (settings.wrap === false) ? $(this) : $(settings.wrap);

		/* STEP 1: get image out of body's background style */
		var src = $(this).css('background-image');
		
		// do nothing if there was no background image set
		if(!src || src == "none") return;
		
		$('html').addClass('fullscreend');
		$(this).css('background-image', 'none');
		
		// either wrap inside (expect body), or wrap
		if(settings.wrap === false) {
			$(wrap).wrapInner('<div id="fullscreend_wrapper">');
		} else {
			$(wrap).wrap('<div id="fullscreend_wrapper">');
		}
		
		// STEP 2: pick apart src
		src = src.substring(4, src.length - 1);

		// STEP 2a: remove wrapping quotes if exist
		if(src.substring(0, 1) == '"' || src.substring(0, 1) == "'") {
			src = src.substring(1, src.length - 1);
		}
		
		// STEP 3: load image
		var img = new Image();
		$(img)
			// once the image has loaded, execute this code
			.load(function () {
				$(self).prepend('<div id="fullscreend"><div><table><tr><td></td></tr></table></div></div>');
				$('#fullscreend td')
					.html('<img src="' + $(this).attr('src') + '">')
					.find('img').fullscreendResize().fadeIn();
				$(window).wresize(function(){ $('#fullscreend img').fullscreendResize(); });
			})
			// if there was an error loading the image, put everything back as was
			.error(function () {
				$('html').removeClass('fullscreend');
				$(this).css('background-image', 'url(' + src + ')');
				$('#fullscreend_wrapper').children(':first').unwrap();
			})
			
			// *finally*, set the src attribute of the new image to our image
			.attr('src', src);

		return this;
	};
})(jQuery);

