/*
 * jQuery Backscale 0.2
 * Modified and extended by Mike van Veenhuijzen (www.mikevv.com)
 * Based on the jQuery Backstretch, by Scott Robbin (www.srobbin.com)
 *
 * Add dynamically-resized background images to the page
 *
*/

(function($) {

  $.fn.backscale = function(options, callback) {
    var settings = {
          hideUntilReady: true, // Hide the image until it's finished loading
          speed: 500 // fadeIn speed for background after image loads (e.g. 'fast' or 500)
        },
        imgRatio=0, imgHeight=0, imgWidth=0;
	
    // Extend the settings with those the user has provided
    if(options && typeof options == 'object') $.extend(settings, options);
      
    return this.each(function() { // Chainable
		var self = $(this);
		var image = new Image();
		var commonCSS = {left: 0, top: 0};
		
		if(settings.hideUntilReady) self.hide();

		var wrap = $('<div />').attr('id', 'backscale-wrap')
			.css( $.extend(commonCSS, {position: 'absolute', zIndex: 5}) );

		var container = $('<div />').attr('id', 'backscale')
			.css( $.extend(commonCSS, {position: 'fixed', overflow: 'hidden', zIndex: -1}) )
			.appendTo(wrap);
		
		$(image).bind('load', function() {
			imgWidth = self.width();
			imgHeight = self.height();
			imgRatio = imgWidth / imgHeight;

			_resizeBG(function() {
			
				if(settings.hideUntilReady) {
					if(settings.speed == 0) {
						self.show();
						if(typeof callback == 'function') callback(); // Callback, if necessary
					} else {
						self.fadeIn(settings.speed, function(){
							if(typeof callback == 'function') callback(); // Callback, if necessary
						});
					}
				
				}
			});
			
		}).bind('error', function() {
			// error handler
		}).attr('src',self.attr('src'));
		
		self.wrap(wrap); // Add wrapper around the image
		
		$(window).resize(_resizeBG); // Adjust the background size when the window is resized
			  
		function _resizeBG(callback) {
			var newWidth = $(window).width();
			var newHeight = newWidth / imgRatio;
			
			if(newHeight < $(window).height()) {
				newHeight = $(window).height();
				newWidth = newHeight * imgRatio;
			}

			self.width(newWidth).height(newHeight); // Resize it

			if (typeof callback == 'function') callback(); // Callback, if necessary
		};
      
    });
	
	return this;
  
  };
  
})(jQuery);
