/*
 * 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($) {

  $.backstretch = function(src, options, callback) {
    var 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;
        
    // Extend the settings with those the user has provided
    if(options && typeof options == "object") $.extend(settings, options);
    
    // Initialize
    $(document).ready(function() {
        _init(src);
    });
  
    // For chaining
    return this;
    
    function _init(src) {
      // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
      if(src) {
        var commonCSS = {left: 0, top: 0};
        
        var self = $(src);
        
        _get_orig_data(self);
        
        _adjustBG(self, function() {
          if( settings.hideUntilReady )
            self.fadeIn(settings.speed, function(){
              // Callback, if necessary
              if(typeof callback == "function") callback();
            });
        });
        $(src).css({
          'overflow':   'hidden',
          'left':       0,
          'top':        0,
          'position':   'absolute'
        });
        
        $('html').css({'overflow-y': 'hidden'});
        
        if(settings.hideUntilReady) $(src).hide();

        // Adjust the background size when the window is resized
        $(window).resize(function() {
            $("#background img").each(function(i, image) {
                _adjustBG(image);
            });
            $("#slideshow img").each(function(i, image) {
                _adjustBG(image);
            });
        });
      }
      
    }
    
    function _adjustBG(image, callback) {
        _size_image(jQuery(image));
        _center_image(jQuery(image));
        
        if (typeof callback == "function") callback();
    }
    
    function _center_image(image){
		$this = image;
		
        var pageWidth = $(window).width();
		var newWidth = -1*($this.width() - pageWidth)/2;
        $(image).css({'left':newWidth});

        var pageHeight = $(window).height();
		var newHeight = -1*($this.height() - pageHeight)/2;
        $(image).css({'top':newHeight});
	}
    
    function _get_orig_data(image){
        $this = image;

        $this.attr('origWidth', $this.width());
        $this.attr('origHeight', $this.height());
        $this.attr('ratio', find_ratio($this.width(),$this.height()));
      }

      function _size_image(image){
        $this = image;

        var originalWidth = to_i($this.attr('origWidth'));
        var originalHeight = to_i($this.attr('origHeight'));
        var ratio = $this.attr('ratio');

      	if(originalWidth == 0 || originalHeight == 0){
      		setTimeout(function(){
    				_get_orig_data(image);
    				_size_image(image);
    			}, 100);
      		return;
      	}

        var width_and_height = [];
        width_and_height = find_width_and_height(originalWidth,originalHeight,ratio);

        $this.width( width_and_height[0] );
        $this.height( width_and_height[1] );
      }
      
      function find_width_and_height(originalWidth,originalHeight,ratio) {
        var pageWidth = $(window).width();
        var pageHeight = $(window).height();

        
        max_follows_width(pageWidth, ratio);

        if( height > pageHeight ){
          //max_follows_height(pageHeight, ratio);
        }

        arrayImageSize = new Array(width,height);

        return arrayImageSize;
      }

      function max_follows_height(pageHeight,ratio){
        height = pageHeight;  // Page Height minus topSpace and bottomSpace
        width = height*ratio;
      }

      function max_follows_width(pageWidth,ratio){
        width = pageWidth; // Page Width minus leftSpace and rightSpace
        height = width/ratio;
      }

      function find_ratio(width,height) {
        width = to_i(width);
        height = to_i(height);
        var ratio = width/height;
        ratio = ratio.toFixed(2);
        return ratio;
      }

      function to_i(i){
        last = parseInt(i);
        return last;
      }
  };
  
})(jQuery);
