//var vpVideoControls = true;
//var vpCustomControlsShow = true;
//var vpCustomControlsHide = false;
//var vpCustomControlsBlockMove = false;
//var vpMouseValueBlockedCursorY;
//var vpMouseLastCursorY;
//var progressBar;
//var vpVideo;
//var ID;
//
//var vpShowHideControls;
//var vpShowHideControlsPosition;
//
//var vpUpdateVideoSeek;
//
var vpSoundClickToPlayButton = false;

if ( courseStatus.vpVideo === undefined ) {
    courseStatus.vpVideo = new Array;
}
if ( courseStatus.vpVideoTotal === undefined ) {
    courseStatus.vpVideoTotal = new Array;
}

function vpVideoSet( vID, vSeek, vControl, vPlay ) {
    var vpVideoControls = true;
    var vpCustomControlsShow = true;
    var vpCustomControlsHide = false;
    var vpCustomControlsBlockMove = false;
    var vpMouseValueBlockedCursorY;
    var vpMouseLastCursorY;
    var progressBar;
    var vpVideo;
    var ID;


    
    var vpUpdateVideoSeek;


    
    var vSeek  = vSeek;

    vpVideo = $('#vpVideo-' + vID ); 
    // Turn off the default controls
    vpVideo.controls = false;
    
    
    var playpause = $('#vpControls-' + vID + ' .playpause');

    function vpTogglePlayPause(){

        var videoLength = vpVideo[0].duration;
        $( '#vpControls-' + vID + ' .vpTotalTime' ).html(vpConvertDurationToMinutes( videoLength ));  

//        playerMusicUpdateBG();


       if (vpVideo[0].paused || vpVideo[0].ended) {
          playpause.html('<img src="images/icon_play.png" />');
          vpVideo[0].play();
          vpSoundClickToPlayButton = true;
       }
       else {
          playpause.html('<img src="images/icon_pause.png" />');
          vpVideo[0].pause();
       }

       if(!$("#capa").hasClass("exit")){
            $(".btn-start").fadeOut()
            $("#capa").addClass("exit")
       }

       if (courseStatus.vpVideo[0] && $('#vpVideo-0')[0].currentTime == 0) {
            var targetTime = 0;
            var duration = $('#vpVideo-0')[0].duration;
            var previousTime = courseStatus.vpVideo[0];
            var previousTotalTime = courseStatus.vpVideoTotal[0];
            targetTime = previousTime / previousTotalTime * duration; 
            $('#vpVideo-0')[0].currentTime = targetTime;
        }

        setInterval(() => {
            courseSave()
        }, 5000);

    }
    playpause.on('click keypress', function() {           

        vpTogglePlayPause();
    });
    
    var fastforward = $('#vpControls-' + vID + ' .fastforward');
    function vpToggleFastForward(){
        var currentTime = vpVideo[0].currentTime;
        var durationTime = vpVideo[0].duration;
        var targetTime = currentTime + 10;
        var unlockTime = courseStatus.vpVideo[ vID ];
        
        if ( targetTime < unlockTime ) {
            vpVideo[0].currentTime = targetTime;
        } else if (targetTime >= durationTime ) {
            vpVideo[0].currentTime = durationTime;
        } else {
            vpVideo[0].currentTime = unlockTime;
        }
    }
    fastforward.on('click keypress', function() {
        vpToggleFastForward();
    });
    
    var fastbackward = $('#vpControls-' + vID + ' .fastbackward');
    function vpToggleFastBackward(){
        var currentTime = vpVideo[0].currentTime;
        var targetTime = currentTime - 10;
        
        if ( targetTime > 0 ) {
            vpVideo[0].currentTime = targetTime;
        } else {
            vpVideo[0].currentTime = 0;
        }
    }
    fastbackward.on('click keypress', function() {
        vpToggleFastBackward();
    });
    
    function vpSetVolume() {
       var volume = $('#vpControls-' + vID + ' .vpVolume');
       vpVideo.volume = volume.value;
    }
    function vpToggleMute() {
       vpVideo.muted = !vpVideo.muted;
    }
    function vpUpdateProgress() {
       var progress = $('#vpControls-' + vID + ' .vpProgress');
       var value = 0;
       if ( vpVideo[0].currentTime > 0 ) {
//          value = Math.floor((100 / vpVideo[0].duration) * vpVideo[0].currentTime);
          value = (100 / vpVideo[0].duration) * vpVideo[0].currentTime;
       }
       progress.css({'width': value + '%'});  
       $('#vpControls-' + vID + ' .vpCurrentTime' ).html( vpConvertDurationToMinutes( vpVideo[0].currentTime ));  
    }
    function vpUpdateProgressUnlocked() {
       var progressUnlocked = $('#vpControls-' + vID + ' .vpProgressUnlocked');
       var value = 0;
       if ( courseStatus.vpVideo[vID] > 0) {
//          value = Math.floor((100 / vpVideo[0].duration) * courseStatus.vpVideo[vID]);
          value = (100 / vpVideo[0].duration) * courseStatus.vpVideo[vID];
       }
       if ( value > 100 ) {
           value = 100;
       }
       progressUnlocked.css({'width': value + '%'});  
    }
    function vpConvertDurationToMinutes(seconds){
        var vpMinutes = parseInt(seconds / 60, 10);
        var vpSeconds = parseInt(seconds % 60);
        if(vpMinutes<10){vpMinutes='0'+vpMinutes;}
        if(vpSeconds<10){vpSeconds='0'+vpSeconds;}
        var vpTotalTime=''+vpMinutes+':'+vpSeconds+'';
        return vpTotalTime;
    }

    function vpPlaylistClick(file) {
       var v = document.createElement('video');
       if (v.canPlayType('video/mp4') != '') {
          vpChangeSource(file + '.mp4');
       }
       else if (v.canPlayType('video/webm') != '') {
          vpChangeSource(file + '.webm');
       }
       return false;
    }

    function vpChangeSource(src) {
       vpResetPlayer();
       vpVideo.src = src;
       vpVideo.load();
    }

    function vpResetPlayer() {
       var playpause = $('#vpControls-' + vID + ' .playpause');
       playpause.innerHTML = '<img src="images/icon_play.png" />';
       if (vpVideo[0].currentTime > 0) {vpVideo[0].currentTime = 0};
       vpUpdateProgress();
    }

    function vpCheckCursorAfterBlockMove(){
//        if( ( vpCustomControlsShow === true ) && ( vpMouseLastCursorY <= vpShowHideControlsPosition.top ) ){
//            vpHideMenu( vpMouseLastCursorY );
//        }
//        if( ( vpCustomControlsHide === true )&&( vpMouseLastCursorY >= vpShowHideControlsPosition.top ) ){
//            vpShowMenu( vpMouseLastCursorY );
//        }
    }

    function vpHideMenu( cursorValue ){

    }
    function vpShowMenu( cursorValue ){
   
    }


    function vpSeek(e) {
        var percent = e.offsetX / this.offsetWidth;
        var targetTime = Math.floor( percent * vpVideo[0].duration );
        var unlockTime = courseStatus.vpVideo[ vID ];
        if ( vSeek === true || vSeek === false && targetTime <= unlockTime ) {
            
//            vpVideo[0].currentTime = percent * vpVideo[0].duration;
            vpVideo[0].currentTime = targetTime;
        }
    }

    function vpSaveSeek( ) {
        var currentTime = vpVideo[0].currentTime;
        var duration = vpVideo[0].duration;
        courseStatus.vpVideoTotal[vID] = duration;
        if ( courseStatus.vpVideo[vID] < currentTime || courseStatus.vpVideo[vID] === undefined ) {
            courseStatus.vpVideo[vID] = currentTime;
            vpUpdateProgressUnlocked();
        }
    }
    
    
    
    var vpIsFirstVideo = $('#vpStage-' + vID ).data('first-video');
    

    $('#fullscreen-button').on('click', fullscreenToggle);

    function fullscreenToggle() {
        let bodyFS = $('body').hasClass('fullscreen');
        if ( bodyFS ) {
            $('body').removeClass('fullscreen');
            document.exitFullscreen();
        } else {
            $('body').addClass('fullscreen');
            document.documentElement.requestFullscreen();
        }
    }
    
    
    
//    if( autoplay === false && playerAudioWarning === false  ) {
//        $('.vpSoundClickToPlay').show();
//    }else{
//        if ( vPlay === true ) { vpVideo[0].play(); }
//        vpSoundClickToPlayButton = true;
//    }
    $(document).on( 'click keypress', '.vpSoundClickToPlayButton', function() {
        
//         vpSoundClickToPlayButton = true;
//         autoplay = true;


//         var videoLength = vpVideo[0].duration;
//         $( '#vpControls-' + vID + ' .vpTotalTime' ).html(vpConvertDurationToMinutes( videoLength ));  
//         if ( vPlay === true ) { vpVideo[0].play(); }
//         playerAudioWarning = true;
// //        playerMusicUpdateBG();
//         playerMusicOff();
//         setTimeout( function() {
//             courseIndex[slideActive].bg_music = 0;   
//         }, 1000);
// //        if (  courseStatus.vpVideo[vID] > 0 && vpVideo[0].currentTime < vpVideo[0].duration - 1 ) {
// //            vpVideo[0].currentTime = courseStatus.vpVideo[vID];
// //        }
//         if (  courseStatus.vpVideo[vID] > 0 ) {
//             var targetTime = 0;
//             var duration = vpVideo[0].duration;
//             var previousTime = courseStatus.vpVideo[vID];
//             var previousTotalTime = courseStatus.vpVideoTotal[vID];
//             targetTime = previousTime / previousTotalTime * duration; 
//             console.log(targetTime);
// //            vpVideo[0].currentTime = courseStatus.vpVideo[vID];
//             vpVideo[0].currentTime = targetTime;
//         }
//         setTimeout(function() {
//             $( '.vpSoundClickToPlay' ).fadeOut( 500 );
//             vpVideo[0].play();
//         }, 500);
    });

    vpVideo[0].addEventListener('timeupdate', vpUpdateProgress, false);

    vpVideo[0].addEventListener('loadedmetadata', function() { // Video is loaded and can be played
        var videoLength = vpVideo[0].duration;
        $( '#vpControls-' + vID + ' .vpTotalTime' ).html(vpConvertDurationToMinutes( videoLength ));    
        zork('Video is ' + videoLength + ' seconds long!');
    }, false);
    
    
    var playpause = $('#vpControls-' + vID + ' .playpause');
    
    vpVideo[0].addEventListener('play', function() {
       
       playpause.html('<img src="images/icon_pause.png" />');
       zork('Saving video progress!');
       vpUpdateVideoSeek = window.setInterval( function() {
           vpSaveSeek( vID );
       }, 500);
       vpUpdateProgressUnlocked();

        $( '.vpSoundClickToPlay' ).hide();
    }, false);

    vpVideo[0].addEventListener('pause', function() {
        playpause.html('<img src="images/icon_play.png" />');
        zork('NOT saving video progress...');
        window.clearInterval( vpUpdateVideoSeek );
    }, false);

    progressBar = $('#vpControls-' + vID + ' .vpProgressBar');
    progressBar.on('click', vpSeek);

    $(document).mousemove( function( event ) {
        if ( $('.vpVideo').length > 0 ) {
//            vpShowHideControls = $('.vpShowHideControls');
//            vpShowHideControlsPosition = vpShowHideControls.position();
//            vpMouseLastCursorY = event.pageY;
//            if( event.pageY >= vpShowHideControlsPosition.top ){
//                vpShowMenu( vpMouseLastCursorY );
//            }else{
//                vpHideMenu( vpMouseLastCursorY );
//            }
        }
     });

}