(function() {
  'use strict';

  function setup_container_direction_chooser() {
    /* setup functions to decide whether each of the containers should display
     * their hidden divs left or right, according to how close the thumbnail is
     * the the page's right margin */

    function choose_direction() {
      /* jshint validthis:true */

      /* choose whether a container should grow left or right */
      var margin, right, scrollbar, fixed_width, container, element;

      container = this.parentNode;
      fixed_width = 240;

      margin = 10;
      scrollbar = 15;

      /* notice we must include the body's right margin and a possible vertical
       * scrollbar, to avoid showing the horizontal scrollbar */
      right = container.offsetLeft + fixed_width + margin + scrollbar;

      element = container.getElementsByClassName('video_info')[0];
      if (element) {
        if (right <= window.innerWidth) {
          element.classList.remove('go_left');
          element.classList.add('go_right');
        }
        else {
          element.classList.remove('go_right');
          element.classList.add('go_left');
        }
      }

      /* remove listener until mouseout, to avoid it being fired over and over
       * each time the user moves the mouse without leaving the div */
      this.removeEventListener('mouseover', choose_direction);
    }

    function setup_mouseover() {
      /* jshint validthis:true */
      this.addEventListener('mouseover', choose_direction);
    }

    /* set up video_info's direction on mouse over the thumbnail itself (not
     * the whole container, because that causes it to fire mouseover and
     * mouseout multiple times) */
    var i, wrappers;
    wrappers = document.getElementsByClassName('thumbnail_wrapper');
    for (i=0; i<wrappers.length; i++) {
      // setup listener for the first time
      wrappers[i].addEventListener('mouseover', choose_direction);
      // on mouse out, setup listener again
      wrappers[i].addEventListener('mouseout', setup_mouseover);
    }
  }

  document.addEventListener('DOMContentLoaded', function() {
    setup_container_direction_chooser();
  });
}());
