/* if audio element is present, make sure it starts playing together with the
 * first video in the page, otherwise do nothing */

(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 setup_autoplay(video, audio) {
    var video_num = get_video_number(video);
    if (!video_num) { return; }

    // make sure autoplay is disabled
    video.removeAttribute('autoplay');
    audio.removeAttribute('autoplay');

    /* don't autoplay at all for opera on X11 because it's broken: it plays for
     * one frame and then stops, forcing the user to pause then play, which is
     * worse than just having to play for the first time */
    if (navigator.userAgent.match(/\bopera\b/i) && navigator.userAgent.match(/\bX11\b/)) {
      return;
    }

    var video_ready = false;
    var audio_ready = false;

    function play_video_and_audio() {
      if (video.paused) {
        video.play();
      }
      if (audio.paused) {
        audio.play();
      }
    }

    function audio_is_ready() {
      audio_ready = true;
      if (video_ready) {
        play_video_and_audio();
      }
    }

    function video_is_ready() {
      video_ready = true;
      if (audio_ready) {
        play_video_and_audio();
      }
    }

    /* mark audio as ready immediately if the video is already loaded (for
     * example, if it is already in cache) or set event listener to do so once
     * it gets loaded */
    function audio_can_play_handler() {
      /* jshint validthis:true */
      this.removeEventListener('canplaythrough', audio_can_play_handler);
      audio_is_ready();
    }
    if (audio.readyState == 4) {
      audio_is_ready();
    }
    else {
      audio.addEventListener('canplaythrough', audio_can_play_handler);
    }

    /* marks video as ready 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 */
    function video_can_play_handler() {
      /* jshint validthis:true */
      this.removeEventListener('canplaythrough', video_can_play_handler);
      video_is_ready();
    }
    if (video.readyState == 4) {
      video_is_ready();
    }
    else {
      video.addEventListener('canplaythrough', video_can_play_handler);
    }
  }
  
  document.addEventListener('DOMContentLoaded', function() {
    var video = document.getElementById('video0');
    var audio = document.getElementById('audio');
    // if there's audio, setup syncronized autoplay
    if (audio) {
      setup_autoplay(video, audio);
    }
  });
}());
