/* Author: Mathtieu Aussaguel
 July 6th, 2011
 */


// Homepage Functions
var Homepage = {
  init: function () {
    // Background image element dom element
    $bgImage = $('img.bg-body:eq(0)');

    // Image Resizer
    if ($bgImage.length) bgImageResize = new ElementResize($bgImage, $('.fullWidth'), true);

    // Show Image
    $bgImage.css('opacity', 0)
        .show()
        .animate({'opacity':1}, {
	    duration: 1000,
	    easing: 'easeInOutQuad'
	});
  }
};

// image Resize class
// $e : jQuery DOM element to resize
// $w : jQuery DOM element to resize wrapper
// resize : boolean true if element needs to be resized on window resize
function ElementResize($e, $w, resize) {

    
  
  // if image is not defined, we can't process
  if (typeof $e === 'undefined') return false ;

  var eData = {
      height: homepageSourceHeight,
      width: homepageSourceWidth
  }

  // Calculate image size and resize it
  this.resize = function () {
    // Update the element dimensions css properties
    $e.css(ImageUtils.getFullScreenImageSize(eData, {width: $w.width(), height: $w.height()}, true));
  };

  // initial resize
  this.resize();

  // resize image on window resize
  
  if (resize) $(window).resize(this.resize);
}

// Image Utils
var ImageUtils = {
// Result optimal size of an image
  getFullScreenImageSize: function(imageSize, containerSize, crop) {
    var d = {}; // final dimensions
    if (typeof crop === 'undefined' || crop === false) {
      var wRatio = containerSize.width / imageSize.width,
          hRatio = containerSize.height / imageSize.height;

      // Default dimensions
      d['width'] = Math.floor(wRatio * imageSize.width);
      d['height'] = Math.floor(wRatio * imageSize.height);

      // if too big
      if ((d['width'] > containerSize.width) || (d['height'] > containerSize.height)) {
        d['width'] = Math.floor(hRatio * imageSize.width);
        d['height'] = Math.floor(hRatio * imageSize.height);
      }

    } else {
      var contentRatio = containerSize.width / containerSize.height,
          mRatio = imageSize.width / imageSize.height;

      // calculate the ratio
      if (contentRatio > mRatio) {
        d['width'] = containerSize.width;
        d['height'] = Math.floor(imageSize.height * (containerSize.width / imageSize.width));
      } else {
        d['width'] = Math.floor(imageSize.width * (containerSize.height / imageSize.height));
        d['height'] = containerSize.height;
      }

    }
    return d;
  }

};









$(function () {
  // Homepage
  if ($('#homepage').length) Homepage.init();

});


