(function($){

    $.fn.fullbackground = function(options) {
		var $this = $(this);
        var defaults = {
			wrapperId : 'bg-wrapper'
		};
        options = $.extend({}, defaults, options);
		var containerElement;
        var bgElement;
		if($this.is('img')) {
			bgElement = $this;
			bgElement.wrap('<div id="'+options.wrapperId+'" />');
			containerElement = bgElement.parent();
		} else {
			containerElement = $this;
			bgElement = containerElement.find('img').first();
		}

		$(window).load(function(){
			initStyle(containerElement, bgElement);
			resize(containerElement, bgElement, options);
		});

        $(window).bind("resize", function() {
            resize(containerElement, bgElement, options);
        });

        return this;
    };

    function resize(containerElement, element, options) {

        // Set element ratio
        var ratio = element.height() / element.width();
        // Get browser window size
        var browserwidth = $(window).width();
        var browserheight = $(window).height();

		//scale the container
		containerElement.css({
			width: browserwidth,
			height: browserheight
		});

        // Scale the element
        if ((browserheight/browserwidth) > ratio){
            element.height(browserheight);
            element.width(browserheight / ratio);
        } else {
            element.width(browserwidth);
            element.height(browserwidth * ratio);
        }

        // Center the element
        element.css('left', (browserwidth - element.width())/2);
        element.css('top', (browserheight - element.height())/2);

        return this;
    }

	function initStyle(containerElement, bgElement) {
		bgElement.css({
			position: 'absolute',
			outline: 'none',
			border: 'none',
			MsInterpolationMode: 'bicubic',
			imageRendering: 'optimizeQuality',
			zIndex: -999
		});
		containerElement.css({
			position: 'fixed',
			top: 0,
			left: 0,
			overflow: 'hidden'
		});
		containerElement.fadeIn(2000);
	}

})(jQuery);
