var videoPlayer = function(data, initialIndex) {
  var videoWidth, videoHeight;

  var simpleApi = 'http://vimeo.com/api/v2/video/${videoId}.json';
  var oembedApi = 'http://vimeo.com/api/oembed.json';
  var getVideoId = function(url) { return url.match(/\/(\d{7})\/?/)[1]; };
  var initVideo = function(video, callback) {
    video.url = 'http://vimeo.com/' + video.id;
    var url = simpleApi.replace('${videoId}', video.id);
    $.getJSON(url + '?callback=?', function(json) {
      video.thumbnail = json[0].thumbnail_small;
      callback(video);
    });
  };
  var loadVideo = function(video, autoplay, callback) {
    var url = oembedApi + '?url=http%3A//vimeo.com/' + video.id +
      '&api=true&portrait=false&title=false&byline=false&width=' + videoWidth;
    if (autoplay) url += '&autoplay=true';
    $.getJSON(url + '&callback=?', function(json) { callback(json, video); });
  };

  var $container = $('#videos');
  var $video = $('#video');
  var $title = $('.title', $container);
  var $caption = $('.caption', $container);
  var $thumbnails = $('.thumbnails', $container);

  videoWidth = $video.width();
  videoHeight = $video.height();

  if (!data || !data.videos) return;
  var videos = data.videos;

  var updateDisplay = function(json, video) {
    var html = json.html.replace(/height="\d+?"/, 'height="' + videoHeight + '"');
    $video.html(html);
    var player = $('iframe', $video).get(0);
    var froogaloop = Froogaloop(player);
    $video.data('froogaloop', froogaloop);
    $title.text(video.title);
    $caption.html(htmlEncode(video.caption, false, 0) + '<span class="link"><a href="' + video.link + '">' + video.linkText + '</a></span>');
  };

  var initVideos = [];
  $.each(videos, function(i, video) {
    if (!video) return; // HACK: IE
    initVideos.push(function(callback) {
      initVideo(video, function(video) { callback(null, video); });
    });
  });
  async.parallel(initVideos, function(err, videos) {
    $.each(videos, function(i, video) {
      if (!video) return; // HACK: IE
      var $thumbnail = $('<li><a href="' + video.url + '"><img src="' + video.thumbnail + '" alt="' + video.title + '" /><span>' + video.thumbnailTitle + '</span></a></li>').appendTo($thumbnails);
      var $anchor = $('a', $thumbnail);
      $anchor.data('video', video);
      $anchor.click(function() {
        var $this = $(this);
        $this.closest('li').addClass('active').siblings().removeClass('active');
        loadVideo($this.data('video'), false, updateDisplay);
        return false;
      });
    });
    var $initial = $('a', $thumbnails).eq(initialIndex || 0);
    $initial.closest('li').addClass('active');
    loadVideo($initial.data('video'), false, updateDisplay);
  });
};
