/* use video's unmute link to unmute it while muting all other videos */

(function() {
  'use strict';

  function toggle_mute() {
    /* toggle video's muted state and, if unmuting, also mute all other videos */
    /* jshint validthis:true */

    // this video's number
    var num = /\d+$/.exec(this.getAttribute('id'));
    var video = document.getElementById('video'+num);
    if (!video) { return; }

    // don't try to unmute videos that lack audio
    if (!(video.classList.contains('has_audio'))) { return; }

    if (video.muted) {
      // mute all other videos
      /* note we're not touching the audio element, if present, on purpose,
       * since the user has already expressed the desire to have an independent
       * audio file and one unmuted video playing at the same time */
      var videos = document.getElementsByTagName('video');
      var i;
      for (i=0; i < videos.length; i++) {
        videos[i].muted = true;
      }
      // unmute this video
      video.muted = false;
    }
    else {
      video.muted = true;
    }
  }

  function setup_unmute_link(video) {
    /* setup listener for video's unmute link */
    var num = /\d+$/.exec(video.getAttribute('id'));
    var link =  document.getElementById('unmute'+num);
    if (!link) { return; }

    link.addEventListener('click', toggle_mute);
    /* link will be unhidden in detect_audio_track.js */
  }

  function update_unmute_link() {
    /* toggle the unmute links' classes when the videos are
     * muted or unmuted */
    /* jshint validthis:true */

    var video = this;
    // get this video's number
    var num = /\d+$/.exec(video.getAttribute('id'));
    var link = document.getElementById('unmute'+num);
    if (!link) { return; }
    // videos without an audio track can't be unmuted
    if (!(video.classList.contains('has_audio'))) {
      link.classList.remove('fake_link');
      link.classList.remove('fake_link_greyed');
      link.classList.add('greyed_out');
    }
    // syncronize videos and links
    else if (video.muted && link.classList.contains('fake_link_greyed')) {
      link.classList.remove('fake_link_greyed');
      link.classList.add('fake_link');
    }
    else if ((!video.muted) && link.classList.contains('fake_link')) {
      link.classList.remove('fake_link');
      link.classList.add('fake_link_greyed');
    }
  }

  document.addEventListener('DOMContentLoaded', function() {
    var videos = document.getElementsByTagName('video');
    var i;
    for (i=0; i < videos.length; i++) {
      videos[i].addEventListener('volumechange', update_unmute_link);
      setup_unmute_link(videos[i]);
    }
  });
}());
