/* set and display all video's download links once video's source is selected */

(function () {
  'use strict';

  function get_video_number(video) {
    if ((!video) || video.id === undefined) { return null; }
    var match = /\d+$/.exec(video.id);
    if (!match) { return null; }
    return match[0];
  }

  function add_download_link(video) {
    /* point download link to video's current source, and add listeners to
     * display info tooltip on hover */
    var video_num = get_video_number(video);
    if (!video_num) { return; }

    var download_link = document.getElementById('download_link'+video_num);
    if (!download_link) { return; }
    var download_div = document.getElementById('download_div'+video_num);
    if (!download_div) { return; }

    download_link.href = video.currentSrc;

    // also set innerhtml if it's missing
    if (!download_link.innerHTML) {
      download_link.appendChild(document.createTextNode(video.currentSrc));
    }

    // show download link
    download_div.classList.remove('hidden');
  }

  function can_play_handler() {
    /* jshint validthis:true */
    this.removeEventListener('canplay', can_play_handler);
    add_download_link(this);
  }
  document.addEventListener('DOMContentLoaded', function() {
    var videos = document.getElementsByTagName('video');
    var i;
    for (i=0; i < videos.length; i++) {
      /* add download link immediately if the video is already loaded (for
       * example, if it is already in cache) or sets event listener to do so
       * once it gets loaded */
      if (videos[i].readyState >= 2) {
        add_download_link(videos[i]);
      }
      else {
        videos[i].addEventListener('canplay', can_play_handler);
      }
    }
  });
}());
