var timer = new Timer();
var ulpVimeo = {
  playerId        : 'ulp_vimeo_player',
  lessonId        : 0,
  autoplay        : 0,
  autocomplete    : 0,
  target          : '',
  width           : 450,
  height          : 390,

  init: function( args ){
      args = JSON.parse( args );
      var obj = this;
      obj.setAttributes(obj, args);
      obj.initPlayer( obj );
  },

  initPlayer: function( obj ){

    var options = {
        url       : obj.target,
        loop      : false,
        autoplay  : obj.autoplay,
        width     : obj.width,
        height    : obj.height,
    }

    var player = new Vimeo.Player( 'ulp_vimeo_player', options );
    
    
    player.getDuration().then(function(duration) {
       obj.setTimer(duration);
    })
    
    player.on( 'play', function() {
        obj.onVideoPlay( obj );
        console.log('Play Action');
         timer.start();
    })
    
    player.on( 'pause', function() {
        obj.onVideoPlay( obj );
        console.log('Pause Action');
        timer.pause();
    })

    player.on( 'ended', function() {
        obj.onFinishVideo( obj );
    });
    

  },

  onFinishVideo: function( obj ){
      if ( obj.autocomplete == 0 ){
          return;
      }
      jQuery.ajax({
    			type: 'post',
    			url: decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
    			data: {
    	                   action: "ulp_complete_lesson",
    	                   lesson_id: obj.lessonId,
    			},
    			success: function( response ){
                    console.log('reloadthis');
                    location.reload(); /// refresh
    			}
  		})
  },

  onVideoPlay: function( obj ){
   
  },
  
  setTimer: function( totalSeconds ){
    var hour = Math.floor(totalSeconds /3600);
    var minute = Math.floor((totalSeconds - hour*3600)/60);
    var seconds = totalSeconds - (hour*3600 + minute*60);
    if(hour < 10)
      hour = "0"+hour;
    if(minute < 10)
      minute = "0"+minute;
    if(seconds < 10)
      seconds = "0"+seconds;
    
    jQuery("#timer").html(hour + ":" + minute + ":" + seconds);
    timer.start({countdown: true, startValues: {seconds: totalSeconds}});
    timer.addEventListener('secondsUpdated', function (e) {
        jQuery('#timer').html(timer.getTimeValues().toString());
    });	
    console.log(timer);
  },

  setAttributes: function(obj, args){
      for (var key in args) {
        obj[key] = args[key];
      }
  },

}

ulpVimeo.init( ulp_vimeo_settings );
