$(function() {
  var $body = $('body');

  $body.find('.video').each(function() {
    var $video = $(this);
    var iframe = this.querySelector('iframe');
    var player = new Vimeo.Player(iframe);
    var is_playing = false;

    $video.on('click', '.video__thumbnail', function(event) {
      event.preventDefault();
      if (is_playing) {
        player.pause();
      } else {
        player.play();
      }
    });

    player.on('play', function() {
      is_playing = true;
      window.requestAnimationFrame(function() {
        $video.addClass('playing');
      });
    });

    player.on('pause', function() {
      is_playing = false;
      window.requestAnimationFrame(function() {
        $video.removeClass('playing');
      });
    });

    player.on('ended', function() {
      is_playing = false;
      window.requestAnimationFrame(function() {
        $video.removeClass('playing');
      });
    });
  });
});
