/**
 * .scaledBackground - jQuery Fader Plugin
 *
 * Version: 2.4
 * Updated: 2011-05-11
 *
 * Scales primary child image of an element to 100% of the height/width of the browser window, while maintaining the images original aspect ratio.
 *
 * Copyright (c) 2011 digital_ice
 *
 * Licensed for use under the LGPL v3.0 Licence (LISCENCE.txt)
 *
 * Version History:
 * 0.9b   -  Original adapted codebase for scaling images to 100% on resize
 * 1.0    -  Added in code to maintain aspect ratio
 * 1.1    -  Added in css resets to overide any custom stylesheets that may affect display
 * 2.0    -  Reworked codebase for speed and size.
 * 2.1    -  Adapted code for cross-browser compatibility
 * 2.2    -  Minor speed tweaks
 * 2.2.1  -  Changed css resets to avoid z-index conficts
 * 2.3    -  Updated ratio calculation to allow different sized images
 * 2.3.1  -  Resolved Z-Index issue
 * 2.3.2  -  Added code to return object at end of function, to allow chaining
 * 2.4    -  Added in flags to make center aligning the image optional
 **/

(function($){
  $.fn.scaledBackground = function(centerHorizontal, centerVertical) {
    var winwidth   = $(window).width();
    var winheight  = $(window).height();

    $(this).css({'margin' : '0', 'padding' : '0', 'position' : 'fixed', 'top' : '0', 'left' : '0', 'border' : '0', 'height' : '100%', 'width' : '100%', 'z-index': '0' });
    $(this).children('img').css({'margin' : '0', 'padding' : '0', 'position' : 'absolute', 'top' : '0', 'left' : '0', 'border' : '0', 'height' : '100%', 'width' : '100%', 'z-index': '-5'})
    $(this).children('img').each(function() {
      var imgratio = $(this).attr('height')/$(this).attr('width');
      if ((winheight/winwidth) > imgratio) {
        $(this).parent().height(winheight);
        $(this).parent().width(winheight / imgratio);
        $(this).height(winheight);
        $(this).width(winheight / imgratio);
      } else {
        $(this).parent().width(winwidth);
        $(this).parent().height(winwidth * imgratio);
        $(this).width(winwidth);
        $(this).height(winwidth * imgratio);
      }

      if (centerHorizontal) {
        $(this).css('left', (winwidth  - $(this).parent().width())/2);
      } else {
        $(this).css('left', 0);
      }

      if (centerVertical) {
        $(this).css('top',  (winheight - $(this).parent().height())/2);
      } else {
        $(this).css('top', 0);
      }
    });
    return $(this);
  };
})(jQuery);
