(function( $ ){

  $.fn.resizeBGWithWindow = function( options ) {
		var theWindow = $(window),	bg = $(this);
		
		var settings = {
			'gMap' : '',
			'isMap' : false,
			'gLatLng' : '',
			'fit' : false
		}
		
		this.each(function() {
			if(options) {
				$.extend(settings, options);
			}
		});
		
		var width = theWindow.width();
		var height = theWindow.height();
		var bgWidth = 0;
		var bgHeight = 0;
		
		bg.fadeIn(2000);

		function resizeBg() {
			var aspectRatio = 1.0;
			var width = theWindow.width();
			var height = theWindow.height();
			bgWidth = bg.width();
			bgHeight = bg.height();

			if(bgWidth < width)
			{
				aspectRatio = width / bgWidth;
				bg.width(bgWidth * aspectRatio);
				bg.height(bgHeight * aspectRatio);
			}
			else if(bgWidth > width)
			{
				aspectRatio = width / bgWidth;
				bg.width(bgWidth * aspectRatio);
				bg.height(bgHeight * aspectRatio);
			}
			
			bgWidth = bg.width();
			bgHeight = bg.height();

			if(bgHeight < height)
			{
				aspectRatio = height / bgHeight;
				bg.height(bgHeight * aspectRatio);
				bg.width(bgWidth * aspectRatio);
			}
			
			bgWidth = bg.width();
			bgHeight = bg.height();

		}
		
		function fitToBg() {
			bg.width(width);
			bg.height(height);
			
			if(bg.width() < $(window).width())
			{
				bg.width($(window).width());
			}
			if(bg.height() < $(window).height())
			{
				bg.height($(window).height());
			}
			
			if(bg.width() < $(document).width())
			{
				bg.width($(document).width());
			}
			if(bg.height() < $(document).height())
			{
				bg.height($(document).height());
			}
			
			if(settings.isMap)
			{
				//settings.gMap.setCenter(settings.gLatLng);
			}
		}
		
		if($(this).is("img"))
		{
			$(this).load(function() {
				if(settings.fit)
				{
					fitToBg();
				}
				else
				{
					resizeBg();
				}
			});
		}
		else if(settings.fit)
		{
			fitToBg();
		}
		else
		{
			resizeBg();
		}
		
		theWindow.resize(function() {
			if(settings.fit)
			{
				fitToBg();
			}
			else
			{
				resizeBg();
			}
		}).trigger("resize");

  };
})( jQuery );
