(function($) {
  $.fn.fancyscale = function(options) {
    var elements = this;
    var resize = function() {
      setTimeout(function() { $(elements).fancyscaleResize(options); }, 100);
      setTimeout(function() { $(elements).fancyscaleResize(options); }, 200);
    };
    resize();
    return this;
  };
  $.fn.fancyscaleResize = function(options) {
    this.each(function() {
      $(this).height($(this.parentNode).height());

      var container = this;
      $(container).find('img:not(.no-scale), div.video_area').each(function() {
        var image = this;
        
        var height = $(image).attr('data-height');
        if(height == null) height = $(image).height();
        var width = $(image).attr('data-width');
        if(width == null) width = $(image).width();
        
        var ratio = (height / width).toFixed(2);
        var containerHeight = $(container).height();
        var containerWidth = $(container).width();
        var containerRatio = containerHeight / containerWidth;

        $(container).css('position', 'relative');
        $(image).css('position', 'absolute');
        
        if (containerRatio > ratio) {
          $(image).height(containerHeight);
          $(image).width(containerHeight / ratio);
        }
        else {
          $(image).width(containerWidth);
          $(image).height(containerWidth * ratio);
        }

        if ($(image).hasClass('center')) {
          
          $(image).css('left', (containerWidth - $(image).width()) / 2);
        }
        else if ($(image).hasClass('right')) {
          $(image).css('right', 0);
        }

        if ($(image).hasClass('middle')) {
          $(image).css('top', (containerHeight - $(image).height()) / 2);
        }
        else if ($(image).hasClass('bottom')) {
          $(image).css('bottom', 0);
        }
      });
    });
    return this;
  };
})(jQuery);

