// Gotta wait until all the images are loaded, because we need their dimensions as a reference in case the video is part of a gallery
window.onload = function () {
  // initial resize
  resize_videoframes();

  var original_width = $('main').getWidth();
  Event.observe(document.onresize ? document : window, 'resize', function() {
    // observe window resize events, check if the page collapsed or expanded, resize videos when it happened
    var new_width = $('main').getWidth();
    if(original_width != new_width) {
      original_width = new_width;
      resize_videoframes();
    }
  });
}

// finds all video iframes (identified by class 'videoframe' or 'youtube-player') and resizes them
function resize_videoframes() {
  $$('iframe.videoframe, iframe.youtube-player, object.videoframe').each(function(frame) {
    // check if we are in a gallery
    if (in_gallery(frame)) {
      // indeed, we are in a gallery, so look to the right for a good size reference
      var nextImg = frame.up('figure').next('figure').down('img');
      if(nextImg !== undefined) {
        frame.writeAttribute('width',  nextImg.getWidth());
        frame.writeAttribute('height', nextImg.getHeight());
      } else {
        // no match to the right, so let's look to the left
        var previousImg = frame.up('figure').previous('figure').down('img');
        if (previousImg !== undefined) {
          frame.writeAttribute('width', previousImg.getWidth());
          frame.writeAttribute('height', previousImg.getHeight());
        }
      }
    } else {
      // not in a gallery, so we take all the width thereis, presumably from the #main container
      var new_width = $('main').getWidth();
      // but wait: blog posts have a sidebar! look for container with class 'main'
      if(frame.up('.main') !== undefined) {
        new_width = frame.up('.main').getWidth();
      }

      // since we dont have to fit into a grid (in opposite to the gallery), we can preserve the video's ratio
      var old_width = frame.readAttribute('width');
      var old_height = frame.readAttribute('height');
      var ratio = old_width/old_height;
      frame.writeAttribute('width', new_width);
      frame.writeAttribute('height', (new_width/ratio).floor());
    }
  });
}

// checks if the video is part of a gallery
function in_gallery(frame) {
  return (frame.up('div').hasClassName('twoUp') ||
          frame.up('div').hasClassName('threeUp') ||
          frame.up('div').hasClassName('fourUp'));
}
