var instances = [];

function secondsToTime(secs) {
    var minutes = Math.floor(secs / 60);
    var seconds = Math.floor(secs % 60);
    if (isNaN(minutes)) minutes = 0;
    if (isNaN(seconds)) seconds = 0;
    if (minutes < 0) minutes = 0;
    if (seconds < 0) seconds = 0;
    if (seconds < 10) seconds = "0" + seconds;
    if (minutes < 10) minutes = "0" + minutes;
    var obj = {
        "m": minutes,
        "s": seconds,
    };
    return obj;
}

$(document).on("change", ".p5VideoPlayer_zakres", function(slideEvt) {
    //console.log("test");
    var player = $(this).closest(".p5VideoPlayer")
    var start = $(player).data("start")
    var end = $(player).find('.p5VideoPlayer_vid')[0].duration - $(player).data("end")
    $(player).find('.p5VideoPlayer_vid')[0].currentTime = slideEvt.value.newValue * ($(player).find('.p5VideoPlayer_vid')[0].duration - start - end) * 0.01 + start
});




function videoPlayer_updateProgress(player, id) {
	if(!jQuery.contains(document, $(player)[0])){

		clearInterval(instances[id]["INTERVAL"])
		return
	}

    var start = $(player).data("start")
    var end = $(player).data("end")
    var current = $(player).find('.p5VideoPlayer_vid')[0].currentTime - start;
    var video = $(player).find(".p5VideoPlayer_vid");
    end = $(player).find('.p5VideoPlayer_vid')[0].duration - end
    var duration = $(player).find('.p5VideoPlayer_vid')[0].duration - start - end;
    var result = (current / duration)

    $(player).find(".p5VideoPlayer_zakres").slider('setValue', result * 100)
    var currentObj = secondsToTime(current);
    var durationObj = secondsToTime(duration);
    $(player).find(".p5VideoPlayer_current").text(currentObj.m + ":" + currentObj.s);
    $(player).find(".p5VideoPlayer_duration").text(durationObj.m + ":" + durationObj.s);
    if (current < 0) {
        $(player).find('.p5VideoPlayer_vid')[0].currentTime = start;
    }

    if (current >= duration) {
        $(player).find('.p5VideoPlayer_vid')[0].currentTime = duration + start;
        var el = $(player).find(".p5VideoPlayer_play");
        $(video).trigger('pause');
        $(el).removeClass("glyphicon-pause")
        $(el).addClass("glyphicon-play")
    }
	$( player ).trigger( "videoProgress" );
}

function p5VideoPlayer_init(imgEl){
 if (!$(imgEl).parent().hasClass("p5VideoPlayer")) return false;
    var player = $(imgEl).parent();
    var id = $(player).data("videoid");
    var link = BASE_URL + "index.php?_route=UrlAction_ProcesEditor&_task=getVideoFileAjax&id=" + id;
    $.get(link, function(data) {
		if($(player).data("start") === true)
			$(player).data("start", data["VIDEO_START"]);
		if($(player).data("end") === true)
			$(player).data("end", data["VIDEO_END"]);
        $(player).append(`
				<video class="p5VideoPlayer_vid">
	 		   <source src="` + data["src"] + `" type="video/mp4">
	 		 Your browser does not support the video tag.
	 		 </video>
	 		   <div class="p5VideoPlayer_video-controls">
	 		 	<table>
	 		 	<tr>
	 		     <td><span class="glyphicon glyphicon-play p5VideoPlayer_play ico"></span></td>
	 		     <td style=width:100%;><input class="p5VideoPlayer_zakres"  type="text" data-slider-handle="custom2"
	 		 	data-slider-min="0" data-slider-max="100" data-slider-step="0.01" data-slider-value="0"/>
	 		 	</td>
				<td class=only_fullscreen><span style=margin-top:15px;><span class=p5VideoPlayer_current>00:00</span>&nbsp/&nbsp<span class=p5VideoPlayer_duration>00:00</span> </span></td>
	 		 		<td class=only_fullscreen><input class="p5VideoPlayer_glosnosc" style=margin-top:10px;width:30px; type="text" data-slider-handle="custom2"
	 		 	data-slider-min="0" data-slider-max="100" data-slider-value="0"/>
	 		 	</td>
	 		 	<td><span class="glyphicon glyphicon-fullscreen ico p5VideoPlayer_fullscreen"></span></td>

	 		 	</tr>
	 		 	</table>

	 		   </div>
				`)
		$(player).find(".img").hide()
        $(player).find('.p5VideoPlayer_vid')[0].currentTime = $(player).data("start");
        $('.p5VideoPlayer_zakres').slider({

            formatter: function(value) {
                return value + "%";
            }
        });

        $('.p5VideoPlayer_glosnosc').slider({
            formatter: function(value) {
                return value + "%";
            }
        });
        //videoPlayer_updateProgress(player);
		var temp = {}
		temp["vid"] = $(player).find('.p5VideoPlayer_vid');
		//console.log("instances ", instances.length)
		instances.push(temp);
		
        instances[instances.length-1]["INTERVAL"] = setInterval(function() {
            videoPlayer_updateProgress(player, instances.length-1);
        }, 500);
		
    });

}

$(document).on("click", ".img", function() {
   p5VideoPlayer_init(this);
});

function videoPlayer_play(el) {
    var player = $(el).closest(".p5VideoPlayer")

    var video = $(player).find(".p5VideoPlayer_vid");
    el = $(player).find(".p5VideoPlayer_play");
    if ($(video).prop("paused")) {
		$.each(instances, function(i,e){
			if(!$(e["vid"]).prop("paused")){
				videoPlayer_play(e["vid"]);
			}
		})
        $(video).trigger('play');
        $(el).removeClass("glyphicon-play")
        $(el).addClass("glyphicon-pause")


    } else {
        $(video).trigger('pause');
        $(el).removeClass("glyphicon-pause")
        $(el).addClass("glyphicon-play")

    }
    //videoPlayer_updateProgress(player);
}

$('.p5VideoPlayer_vid').on('canplay canplaythrough', function() {
    alert('canplay event fired');
});


$(document).on("click", ".p5VideoPlayer_play", function() {
    videoPlayer_play(this);
})

$(document).on("click", ".p5VideoPlayer_vid", function() {
    videoPlayer_play(this);
})



$(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange', ".p5VideoPlayer_vid", function() {
    var state = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
    var player = $(this).closest(".p5VideoPlayer")
    var video = $(player).find(".p5VideoPlayer_vid");
    if (state) {
        $(player).find(".p5VideoPlayer_video-controls").addClass("p5VideoPlayer_video-controls-fs");
    } else {
        $(player).find(".p5VideoPlayer_video-controls").removeClass("p5VideoPlayer_video-controls-fs");
    }
});

$(document).on("click", ".p5VideoPlayer_fullscreen", function() {
    var player = $(this).closest(".p5VideoPlayer")
    var video = $(player).find(".p5VideoPlayer_vid");
    var elem = video[0];
    $(player).find(".p5VideoPlayer_video-controls").addClass("p5VideoPlayer_video-controls-fs");
    var state = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
    if (!state) {
        if (elem.requestFullscreen) {
            elem.requestFullscreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
            elem.webkitRequestFullscreen();
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }

    }


});
