$(document).ready(function() {

  var _video = document.getElementById('video'), _fps = 24;
  var _timeline, _timeline_container = document.getElementById('timeline'), _tl_data_ar=[], _tl_items;

  function init(){
    console.log("Init");
    // preload all pictures before launching

    // setTimeout(function(){
    //   play();
    // }, 5000);
    getMetaData();
    // setupTimeline();
  };

  function getMetaData(){
    console.log('getMetaData');
    // $.getJSON('metadata/frame.json',function(data){
    //   setUpData(data.frames)
    // });
    $.ajax({
      dataType:"json",
      url:'metadata/frames.json',
      success:setUpData
    });
    console.log('getMetaData END');
  };

  function setUpData(data){
    console.log("setUpData");
    // console.log("data", data);

    var frame;
    for (var i in data.frames) {
      console.log(data.frames[i]);
      _tl_data_ar.push({
        start:new Date(data.frames[i].time),
        id:data.frames[i].frame
      });
    }

    setupTimeline();
  };

  function setupTimeline(){

    // Create a DataSet (allows two way data-binding)
    _tl_items = new vis.DataSet(_tl_data_ar);

    // Configuration for the Timeline
    // var options = {};

    // Create a Timeline
    _timeline = new vis.Timeline(_timeline_container, _tl_items, {});

    _timeline.on('select', onSelectTimelineItem)
  }

  function onSelectTimelineItem(props){
    console.log("onSelectTimelineItem", props);
    seekVideoTo(props.items[0]);
  };

  function seekVideoTo(f){
    console.log("seekVideoTo frame", f);
    _video.pause();
    _video.currentTime = f/_fps;
  };

  function play(millis){
    requestAnimationFrame(play);

    // now = Date.now();
    // delta = now - then;
    //
    // if(delta > interval){
    //   then = now -(delta % interval);
    // }
  }




  init();

});
