/*
 * jQuery Backstretch 1.0
 * http://srobbin.com/jquery-plugins/jquery-backstretch/
 *
 * Add a dynamically-resized background image to the page
 *
 * Copyright (c) 2009 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.

*/

(function($)
{
	virb.$.backstretch = {
		settings: {
			hideUntilReady: true, // Hide the image until it's finished loading
			speed: 0 // fadeIn speed for background after image loads (e.g. "fast" or 500)
		},
		imgRatio: 0,
		init: function(src, options, callback)
		{
			// Extend the settings with those the user has provided
			if(options && typeof options == "object") virb.$.extend(this.settings, options);			
			
			// Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
			if (src)
			{
				var commonCSS = {left: 0, top: 0};

				if (virb.$('#backstretch-wrap').length == 0)
				{
					var wrap = virb.$("<div />")
						.attr("id", "backstretch-wrap")
						.css( virb.$.extend(commonCSS, {position: "absolute", zIndex: -1}) );
					var container = virb.$("<div />")
							.attr("id", "backstretch")
							.css( virb.$.extend(commonCSS, {
								position: "fixed",
								overflow: "hidden",
								zIndex: -1
								}) )
							.appendTo(wrap);
				}
				else
				{
					var container = virb.$('#backstretch-wrap #backstretch');
					virb.$('#backstretch-wrap img').remove();
				}
				
				var img = virb.$("<img />")
						.attr("src", src)
						.bind("load", function()
						{
							var self = virb.$(this);
							virb.$.backstretch.imgRatio = self.width() / self.height();
							virb.$.backstretch.adjustBG(function()
							{
								if(virb.$.backstretch.settings.hideUntilReady)
								{
									self.fadeIn(virb.$.backstretch.settings.speed, function()
									{
										// Callback, if necessary
										if(typeof callback == "function") callback();
									});
								}
							});
						});
				
				
				if (this.settings.hideUntilReady) img.hide();
				img.appendTo(container);

				virb.$("body").prepend(wrap);
				if (this.settings.hideUntilReady) { virb.$("#load").animate({ opacity: 0}, 'fast'); }

				// Adjust the background size when the window is resized
				virb.$(window).resize(function()
				{
					virb.$.backstretch.adjustBG(false);	
				});
			}
		},
		adjustBG: function(callback)
		{
			var bgWidth = virb.$(window).width(),
			bgHeight = bgWidth / virb.$.backstretch.imgRatio;

			if(bgHeight < virb.$(window).height()) {
				bgHeight = virb.$(window).height();
				bgWidth = bgHeight * virb.$.backstretch.imgRatio;
			}

			var bgOffsetW = Math.round((bgWidth - virb.$(window).width()) / 2);
			var bgOffsetH = Math.round((bgHeight - virb.$(window).height()) /2);

			virb.$("#backstretch img").width(bgWidth).height(bgHeight);
			virb.$("#backstretch img").css({ position: 'relative',  top: '-' + bgOffsetH + 'px', left: '-' + bgOffsetW + 'px'})

			if (typeof callback == "function") callback();
		}
	}
})(jQuery);
