/* setup controls for changing playback speed */

(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_speed_controls(video) {
    var video_num = get_video_number(video);
    if (!video_num) { return; }
    var speed_bar = document.getElementById('speed_bar'+video_num);
    // not present if this is older firefox which lacks range input
    var speed_value = document.getElementById('speed_value'+video_num);

    // start at 100% unless or what the user specified
    var playback_speed = 1;
    if (speed_bar) {
      playback_speed = speed_bar.value/100;
    }

    function adjust_playback_speed() {
      video.playbackRate = playback_speed;

      if (speed_bar) {
        if (speed_bar.value != playback_speed*100) {
          speed_bar.value = playback_speed*100;
        }
      }

      if (speed_value) {
        speed_value.innerHTML = Math.round(playback_speed*100)+'%';
      }
    }
    // adjust to the initial speed
    adjust_playback_speed();

    /* there's a bug in firefox where if you pause the video and play again, it
     * will go back to 100% speed, so we have to reset the speed every time */
    if (navigator.userAgent.match(/\bfirefox\b/i)) {
      video.addEventListener('play', adjust_playback_speed);
    }

    function speed_bar_input_handler() {
      playback_speed = speed_bar.value/100;
      adjust_playback_speed();
    }
    if (speed_bar) {
      // adjust speed as the user moves the speed bar
      speed_bar.addEventListener('input', speed_bar_input_handler);
      // just to make sure, adjust on change as well
      speed_bar.addEventListener('change', speed_bar_input_handler);
    }

    var speed_normal = document.getElementById('speed_normal'+video_num);
    if (speed_normal) {
      speed_normal.addEventListener('click', function() {
        // back to 100%
        playback_speed = 1;
        adjust_playback_speed();
      });
    }
  }

  function setup() {
    var video = document.getElementById('video0');
    setup_speed_controls(video);
  }

  document.addEventListener('DOMContentLoaded', setup);
  window.addEventListener('newVideoCreated', setup);
}());
