/** http://docs.sublimevideo.net/playlists **/
/** jQuery version **/

var SublimeVideo = SublimeVideo || {};

var InteractiveThumbnailsHandler = function(interactiveWrapperId){
  this.interactiveWrapperId = interactiveWrapperId;
  this.videosCount = $("#" + this.interactiveWrapperId + " .video_wrap").size();
  this.setup();
};

$.extend(InteractiveThumbnailsHandler.prototype, {
  setup: function() {
    var that = this;

    $("#"+ this.interactiveWrapperId + " li").each(function() {
      $(this).click(function(event) {
        event.preventDefault();
        if (!$(this).hasClass("active")) {
          that.clickOnThumbnail($(this).attr("id"));
        }
      });
    });

    sublimevideo.ready(function() {
      sublimevideo.onEnd(function(sv) {
        var matches = sv.element.id.match(/^video(\d+)$/);
        if (matches != undefined) {
          if (parseInt(matches[1], 10) <= that.videosCount) {
            that.handleAutoNext(sv.element.id);
          }
        }
      });
    });

    this.loadDemo();
  },
  loadDemo: function() {
    // Only if not the first time here
    if (this.activeVideoId) this.reset();

    this.activeVideoId = "video1";

    // Show first video
    this.showActiveVideo();
  },
  reset: function() {
    // Hide the current active video
    $("#" + this.interactiveWrapperId + " .video_wrap.active").first().removeClass("active");

    // Get current active video and unprepare it
    // we could have called sublimevideo.unprepare() without any arguments, but this is faster
    sublimevideo.unprepare(this.activeVideoId);

    // Deselect its thumbnail
    this.deselectThumbnail(this.activeVideoId);
  },
  clickOnThumbnail: function(thumbnailId) {
    // Basically undo all the stuff and bring it back to the point before js kicked in
    this.reset();

    // Set the new active video ...
    this.activeVideoId = thumbnailId.replace(/^thumbnail_/, "");

    // Show it ...
    this.showActiveVideo();

    // And finally, prepare and play it
    sublimevideo.prepareAndPlay(this.activeVideoId);
  },
  selectThumbnail: function(videoId) {
    $("#thumbnail_" + videoId).addClass("active");
  },
  deselectThumbnail: function(videoId) {
    $("#thumbnail_" + videoId).removeClass("active");
  },
  showActiveVideo: function() {
    // Show it
    $("#" + this.activeVideoId).parent().addClass("active");

    // Select its thumb
    this.selectThumbnail(this.activeVideoId);
  },
  handleAutoNext: function(endedVideoId) {
    var nextId = parseInt(endedVideoId.replace(/^video/, ""), 10) + 1;
    if (nextId > 1 && nextId <= this.videosCount) {
      this.clickOnThumbnail("thumbnail_video" + nextId);
    }
  }
});

$(document).ready(function() {
  // Pass in the id of the interactive wrapper div
  SublimeVideo.interactiveThumbnails = new InteractiveThumbnailsHandler("interactive");
});
