function scaleBg(bg) {
  var 
    r = bg.width() / bg.height(),
    w = $(window).width()
    h = Math.round(w / r);
  
  bg.width(w);
  bg.height(h);

  if (h < $(window).height()) {
    h = $(window).height();
    bg.height(h);
    bg.width(Math.round(h * r));
  }
}

function round(img) {
  img.wrap('<span class="rounded-img" />').parent().css({ 
    'width' : img.width() + 'px', 
    'height' : img.height() + 'px',
    'backgroundImage' : 'url(' + img.attr('src') + ')',
    'float' : img.css('float'),
    'marginTop' : img.css('margin-top'),
    'marginRight' : img.css('margin-right'),
    'marginBottom' : img.css('margin-bottom'),
    'marginLeft' : img.css('margin-left')
  });
  
  img.css({
    'opacity' : '0',
    'margin' : '0'
  });
}

var $bg;
$(document).ready(function() {
  $bg = $("#sky_img");
  
  scaleBg($bg);
  
  $(window).resize(function() {
    scaleBg($bg);
  });
  
  $(".rounded").each(function() { round($(this)); });
});
