jQuery(window).load(function () {
   var $ = jQuery;

   ///////////////

   var scaleBoxes = $('.imagebox');

   scaleBoxes.each(function () {
      var box = $(this);
      var img = $('img', this);

      var scale = 1;
      var offset = 0;

      img.width(img.width());
      img.height(img.height());
      img.css({position:'relative'});

      /////////

      aspect_box = box.width() / box.height();
      aspect_img = img.width() / img.height();

      if (isNaN(aspect_img)) {
         return;
      }

      if (aspect_img < aspect_box) {
         scale = (box.height() / img.height());

         img.width( img.width() * scale );
         img.height( img.height() * scale );

         offset = Math.floor(box.width() - img.width()) / 2;

         img.css({left: offset});
      }
      else {
         scale = (box.width() / img.width());

         img.width( img.width() * scale );
         img.height( img.height() * scale );

         offset = Math.floor(box.height() - img.height()) / 2;

         img.css({top: offset});
      }
   });
});


