$(document).ready(function() {

  var _frames;

  var _$timelaps = $('#timelaps'),
      _$video = $("#timelapsvid"),
      _video = document.getElementById('timelapsvid'),
      _fps = 12,
      _vid_current_time;

  var _timeline, _timeline_container = document.getElementById('timeline'),
      _tl_data_ar = [], _tl_items, _tl_start, _tl_end;

  var _mapout, _mapout_zoom=5, _mapout_pin, _mapout_provider = "CartoDB.DarkMatter";
  var _mapin, _mapin_zoom=15, _mapin_pin, _mapin_provider = "CartoDB.DarkMatter";
  var _map_pin_coordinates;
  var _mapicon = L.icon({
    iconUrl: 'assets/icon.svg',
    iconSize: [20, 20],
    iconAnchor: [10, 10]
  });

  function init(){
    console.log("Init");

    // teasing
    // var now = Date.now();
    // var opening = new Date("2016-07-02T18:30");
    // // console.log(now);
    // // console.log(limit.getTime());
    // if( window.location.hostname == "centipede.hehe.org" && now < opening.getTime()){
    //   $('body').addClass('teasing');
    //   setTimeout(function(){
    //     window.location.reload();
    //   },1000*60);
    // }else{
      loadData();
    // }

  };


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

  function setUpData(d){
    console.log("setUpData");
    _frames = d.frames;
    // console.log(_frames);

    for (i in _frames) {
      // convert gps from string to float array
      _frames[i].gps = _frames[i].gps.split(',').map(function(a) {
        return parseFloat(a);
      });
    }

    // timeline
    _tl_start= new Date(_frames[0].datetime);
    _tl_end= new Date(_frames[_frames.length-1].datetime);
    // console.log('_tl_start : '+_tl_start+" | _tl_end"+_tl_end);

    // map
    _map_pin_coordinates = _frames[0].gps;
    console.log(_map_pin_coordinates);

    initDataReady();
  };

  function initDataReady(){
    console.log("initDataReady");
    setupTimeline();
    setupMap();
    setupVideoEvents();

    play();

    setTimeout(function(){
      _video.play();
    }, 2000);
  }

  /*
    _   _                _ _
   | | (_)              | (_)
   | |_ _ _ __ ___   ___| |_ _ __   ___
   | __| | '_ ` _ \ / _ \ | | '_ \ / _ \
   | |_| | | | | | |  __/ | | | | |  __/
    \__|_|_| |_| |_|\___|_|_|_| |_|\___|
  */
  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, [], {
      // height:'50px',
      showCurrentTime:false,
      start:_tl_start,
      end:_tl_end,
      stack:false
    });

    _timeline.addCustomTime(_tl_start, "videotime");

    _timeline.on('click', onClickTimeline)
  }

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

  function moveTimelineCursor(date){
    _timeline.setCustomTime(date, "videotime", {animation:false});
    _timeline.moveTo(date, {animation:false});
  }

  /*
    __  __
   |  \/  |
   | \  / | __ _ _ __
   | |\/| |/ _` | '_ \
   | |  | | (_| | |_) |
   |_|  |_|\__,_| .__/
                | |
                |_|
  */
  function setupMap(){
    console.log('setupMap');

    _mapout = L.map('mapout', {
      center:_map_pin_coordinates,
      zoom:_mapout_zoom,
      zoomControl:false,
      attributionControl:false
    });
    L.tileLayer.provider(_mapout_provider).addTo(_mapout);
    _mapout_pin = L.marker(_map_pin_coordinates, {icon:_mapicon}).addTo(_mapout);

    _mapin = L.map('mapin', {
      center:_map_pin_coordinates,
      zoom:_mapin_zoom,
      zoomControl:false,
      attributionControl:false
    });
    L.tileLayer.provider(_mapin_provider).addTo(_mapin);
    _mapin_pin = L.marker(_map_pin_coordinates, {icon:_mapicon}).addTo(_mapin);
  };

  function moveMapPin(c){
    _mapout.setView(c, _mapout_zoom);
    _mapout_pin.setLatLng(c);
    _mapout_pin.update(c);
    //
    _mapin.setView(c, _mapin_zoom);
    _mapin_pin.setLatLng(c);
    _mapin_pin.update(c);
  };

  /*
   __      ___     _
   \ \    / (_)   | |
    \ \  / / _  __| | ___  ___
     \ \/ / | |/ _` |/ _ \/ _ \
      \  /  | | (_| |  __/ (_) |
       \/   |_|\__,_|\___|\___/
  */
  function setupVideoEvents(){
    // console.log("setupVideoEvents");
    _$video.on("click", onClickVid);
  };

  function onClickVid(e){
    console.log("onClickVid",e);
    if(_video.paused){
      _video.play();
    }else{
      _video.pause();
    }
  };

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

  /*
                _                 _   _
               (_)               | | (_)
     __ _ _ __  _ _ __ ___   __ _| |_ _  ___  _ __
    / _` | '_ \| | '_ ` _ \ / _` | __| |/ _ \| '_ \
   | (_| | | | | | | | | | | (_| | |_| | (_) | | | |
    \__,_|_| |_|_|_| |_| |_|\__,_|\__|_|\___/|_| |_|
  */
  function play(millis){
    requestAnimationFrame(play);
    // console.log("_video.playing",_video.paused);

    if (!_video.paused) {
      moveTimelineCursor(_frames[vt2f(_video.currentTime)].datetime);
      moveMapPin(_frames[vt2f(_video.currentTime)].gps);
    }
    // now = Date.now();
    // delta = now - then;
    //
    // if(delta > interval){
    //   then = now -(delta % interval);
    // }
  }

  /* helpers */

  function vt2f(ct){
    // console.log("Video Time 2 frame");
    return Math.round(ct/(1/_fps));
    // console.log("frame", frame);
  }


  init();

});
