// Browser detection. We really only care if browser is that troublesome MSIE.
var browser = '';
if (/MSIE/.test(navigator.userAgent)) browser = 'MSIE';



// Replaces element id with img with given attributes.
function set_overlay(dom_id) {
  var attrs = overlays[dom_id];
  var replace_me = document.getElementById(dom_id);
  if (replace_me) set_node(replace_me, attrs);
}


// Replaces node img with given attributes.
function set_node(replace_me, attrs) {
  var img = document.createElement("img");
  for (var key in attrs) {
    // MSIE does not consider event handlers attributes.
    if (browser == 'MSIE' &&
        (key == 'onmouseover' || key == 'onmouseout' || key == 'onclick'))
      img[key] = attrs[key];
    else
      img.setAttribute(key, attrs[key]);
  }
  replace_me.parentNode.replaceChild(img, replace_me);
  if (browser == 'MSIE')
    img.parentNode.innerHTML = img.parentNode.innerHTML;
}


// replace_with_yt_player(dom_id)
// Replaces DOM node with an embedded YouTube player.
// After player is loaded, begin playing the video.
// See http://code.google.com/apis/youtube/js_api_reference.html
function replace_with_yt_player(dom_id, width, height) {
  unloadYtPlayer();

  // rel=0: Do not offer related videos when this one is done playing.
  // enablejsapi=1: Allow this player to be controlled by Javascript.
  // playerapiid=ID: ID for this player. Cleverly use the video's ID. The
  //   onYouTubePlayerReady() function will be called when the player is
  //   loaded and ready to accept commands.
  var params = { allowScriptAccess: "always" };
  var atts = { id: dom_id };
  swfobject.embedSWF("http://www.youtube.com/v/" +
                     yt_ids[dom_id] + "&enablejsapi=1&playerapiid=" + dom_id,
                     dom_id, width, height, "8.0.0", null, null, params, atts);
}


// Currently playing video's player.
var player;
var player_dom_id;


// Callback for YouTube player. Called when player is loaded and ready to
// accept commands. This one starts the player (indirectly).
function onYouTubePlayerReady(dom_id) {
  player = document.getElementById(dom_id);

  // Player is now loaded, but video is not cued.
  // Wait until it is cued and then play it.
  // The state we want is Video Cued (5).
  if (player) {
    player_dom_id = dom_id;
    player.addEventListener("onStateChange", "onYtPlayerStateChange");
  }
  // else: failed to load.
}


// Starts video playing when cued.
function onYtPlayerStateChange(newState) {
  if (player) {
    if (newState == 5) // cued
      player.playVideo();
  }
}


// Stops video and unloads current player.
function unloadYtPlayer() {
  if (player) {
    var state = player.getPlayerState();
    if (state != -1) {
      player.stopVideo();
      player.clearVideo();
    }
    set_node(player, overlays[player_dom_id]);
    player = null;
    player_dom_id = null;
  }
}
