let resumevid = "";
let resumevidtime = 0;
let adisrunning = false;
let adndx = 0;
let slidermax = 100;
let xfactor="";
let ctlstimer="";
let xvideo="";
let zvindx = 1;
var dxx = [0,100];
xw=0;xh=0;
firstload=1;
var barwidth = undefined;
function metaldd(){
	//if (firstload == 1){firstload = 0; return;}
	h = myVideo.videoHeight;
	w = myVideo.videoWidth;
	dw = lp.clientWidth;
	dh = lp.clientHeight;
	r = (w/h);
	xh = (dw/r);
	if(xh > dh){
		xw = dh * r;
		xh = dh;
	}else{
		xw = dw;
	}
	wp = 100 * xw/dw;
	hp = 100 * xh/dh;
	myVideo.style.width = wp + "%";
	myVideo.style.height = hp + "%";
}
	// Check if there is a cookie for the volume
let volumeCookie = getCookie("volume");


(function() {

document.addEventListener("DOMContentLoaded", setupControl, false); 
function setupControl() { 
	var myVideo = document.getElementById("myVideo"); 

	//myVideo = document.getElementById("myVideo"); 
	lp = document.getElementById("loopplayer"); 
	myVideo.addEventListener('loadedmetadata', metaldd);

	let slider = document.getElementById('slider');
	noUiSlider.create(slider, {
		start: [0, 100],
		connect: true,
		range: {
			'min': 0,
			'max': 100
		}
	});
	let speedslider = document.getElementById('speedslider');
	noUiSlider.create(speedslider, {
		start: 1,
		range: {
			'min': 0.1,
			'max': 1
		}
	});
	//var dxx = [0,100];
	let vslider = document.getElementById('vslider');
	noUiSlider.create(vslider, {
		start: 0,
		range: {
			'min': 0,
			'max': 1
		}
	});
	slider.noUiSlider.on('update', function( values, handle ) {
		dxx[handle] = values[handle];
	});
	speedslider.noUiSlider.on('update', function( value) {
		myVideo = document.getElementById("myVideo");  
		myVideo.playbackRate = value;
	});
	vslider.noUiSlider.on('update', function( value) {
		myVideo = document.getElementById("myVideo");  
		myVideo.volume = value;

	});

	// Make the DIV element draggable:
	dragElement(document.getElementById("myVideo"));
		
	// Get the video player element
	const videoPlayer = document.getElementById("myVideo");

	//volumeCookie = getCookie("volume");
	if (volumeCookie !== "") {
	  // Use the volume value from the cookie if it exists
	  	volume = parseFloat(volumeCookie);
	  	vslider.noUiSlider.set([volume]);
	}else{
		volume = 0;
	}
	var now = new Date();
  	var time = now.getTime();
  	var expireTime = time + 1000*36000;
 	now.setTime(expireTime);
	videoPlayer.addEventListener('volumechange', () => {
		volume = videoPlayer.volume;
		document.cookie = 'volume=' + volume + ';expires='+now.toUTCString()+';path=/';
	});
	// Check if there is a cookie for the volume


	// Set the volume of the video player
	videoPlayer.volume = volume;

	// Save the volume value as a cookie
	
	var clickTime;

	videoPlayer.addEventListener('mousedown', (event) => {
	  clickTime = new Date();
	});

	videoPlayer.addEventListener('click', (event) => {
	  if (new Date() - clickTime > 600) {
			playerclicked();
		
	  } else {
		// pause
	  }
	});	
	
	
	
	
	
	if (myVideo.canPlayType) {  
		document.getElementById("progressbar").style.display="block"; 
		myVideo.addEventListener("timeupdate", reportProgress, false); 
		myVideo.addEventListener("ended", endPlayback, false); 
		myVideo.addEventListener("click", playerclicked, false); 
		myVideo.addEventListener("play",function() { 
						document.getElementById("playbutton").disabled=true; 
						document.getElementById("pausebutton").disabled=false; 
						document.getElementById("playbutton").style.display="none";
						document.getElementById("pausebutton").style.display="block";
						document.getElementById("loopbuttongreen").disabled=false; 
					}, false); 

		myVideo.addEventListener("pause", function() { 
						document.getElementById("playbutton").disabled=false; 
						document.getElementById("pausebutton").disabled=true; 
						document.getElementById("playbutton").style.display="block";
						document.getElementById("pausebutton").style.display="none";
						document.getElementById("loopbuttongreen").disabled=true; 
					}, false); 
		document.getElementById("playbutton").addEventListener("click",startPlayback,false); 
		document.getElementById("pausebutton").addEventListener("click",pausePlayback,false); 
		document.getElementById("fsbutton").addEventListener("click",toggleFullScreen,false); 
		document.getElementById("loopbuttongreen").addEventListener("click", toggleloop, false);
		document.getElementById("loopbuttonred").addEventListener("click", toggleloop, false); 
		document.getElementById("progressbar").addEventListener("click", xseekbar, false); 
		document.getElementById("loopplayer").addEventListener("mousemove", showctlssteadycheck, false);
		document.getElementById("loopcontrols").addEventListener("mouseover", showctlssteady, false);
		document.getElementById("loopcontrols").addEventListener("mousemove", showctlssteady, false);
		document.getElementById("loopcontrols").addEventListener("mouseout", showctls, false);
		document.getElementById("vzoom").addEventListener("click", vzoomin, false);
		document.getElementById("vzoomout").addEventListener("click", vzoomout, false);

		let svcolr = document.body.style.background;
		myVideo.addEventListener("play",function() { 
			document.body.style.background = "#000000"; 
		}, false); 
		myVideo.addEventListener("ended",function() { 
			document.body.style.background = svcolr; 
		}, false); 
		myVideo.addEventListener("pause",function() { 
			document.body.style.background = svcolr; 
		}, false); 
	} 
}

})();






function vzoomin() {
	zvindx += .1;
	x=document.getElementById('myVideo');
	x.style.transform = "scale(" + zvindx + ")";

}

function vzoomout() {
	zvindx -= .1;
	x=document.getElementById('myVideo');
	x.style.transform = "scale(" + zvindx + ")";

}
function showctls() {
	document.getElementById("loopcontrols").style.visibility = "visible";
	document.getElementById("loopplayer").style.cursor="default"; 
	ctlstimer = setTimeout(fadectls, 3000);
}
function fadectls() {
	document.getElementById("loopcontrols").style.visibility = "hidden";
	document.getElementById("loopplayer").style.cursor="none";
}

function showctlssteady() {
	clearTimeout(ctlstimer);
}
function showctlssteadycheck() {
	var vcheck = document.getElementById("loopcontrols").style.visibility;
	if (vcheck == "hidden") {
		showctls();
	}
}
function playerclicked() { 

		var myVideo = document.getElementById("myVideo"); 
		if (myVideo.paused) {
			startPlayback();
		}else if 
		 (!myVideo.paused) {
			pausePlayback();			
		}
		
}
function startPlayback() { 
		document.getElementById("myVideo").removeAttribute("poster");
		document.getElementById("myVideo").play(); 
		document.getElementById("playbutton").style.display="none";
		document.getElementById("pausebutton").style.display="block";
		} 

function pausePlayback() { 
		document.getElementById("myVideo").pause(); 
		document.getElementById("pausebutton").style.display="none";
		document.getElementById("playbutton").style.display="block";
} 
function stopPlayback() { 
		var myVideo = document.getElementById("myVideo"); 
		myVideo.pause(); 
		myVideo.currentTime=0; 
		endPlayback();  
} 

function toggleloop() { myVideo = document.getElementById("myVideo"); 
	var loop = document.getElementById("loop"); 
	if(myVideo.looped) { 
		myVideo.looped = false;  
		document.getElementById("loopbuttongreen").style.display="block"; 
		document.getElementById("loopbuttonred").style.display="none";
	} else {  
		myVideo.looped = true; 
		document.getElementById("loopbuttongreen").style.display="none";
		document.getElementById("loopbuttonred").style.display="block"; 
	} 

} 

function endPlayback() { 

		if (adisrunning) {
			document.getElementById("myVideo").src=resumevid;
			startPlayback();
			xseek(resumevidtime);
			adisrunning = false;
			document.getElementById("loopplayer").removeEventListener("click",adlinkout); 
			document.getElementById("loopplayer").style.cursor="default"; 
			document.getElementById("skipad").style.visibility = "hidden";
			return;
		}
		document.getElementById("loopplayer").removeEventListener("click",adlinkout); 
		
		if (vplaylist[plndx].indexOf("https") == 0){
			document.getElementById("myVideo").src=vplaylist[plndx];
			plndx++;
			startPlayback();	
		}else {
			document.getElementById("pausebutton").style.display="none";
			document.getElementById("playbutton").style.display="block";
		}
} 


function reportProgress() { 
 	barwidth = document.getElementById("progressbar").offsetWidth;
	var vtime = document.getElementById("vtime");
	time = Math.round(this.currentTime); 
	duration = parseInt(this.duration); 
	xposition = barwidth * (time / duration); 
	var vdate1 = new Date(null);
	var vdate2 = new Date(null);
	vdate1.setSeconds(time);
	vdate2.setSeconds(duration);
	if ( (Number.isInteger(time)) && (Number.isInteger(duration)) ) {
		vtime.innerHTML = vdate1.toISOString().substr(11,8) + " / " + vdate2.toISOString().substr(11,8);
	}
	xfactor = duration / slidermax;
	xdur = duration;
	
	xprog = document.getElementById("loadingprogress");
	if (xposition <= barwidth) { 
		xprog.style.width=(xposition / barwidth) * 100 + "%"; 
	} 	
	

	if( (adndx < numofads) && (adisrunning == false) ){
		if (time >= advertlist[adndx].time) {
			resumevidtime = time;
			playad(advertlist[adndx]);
		}	
	}
	if (adisrunning == true) {
		time = Math.round(this.currentTime);
		if (time == 7) {
			document.getElementById("skipad").style.visibility = "visible";
			document.getElementById("skipad").addEventListener("click",endPlayback,false); 
		}
	}

	if (myVideo.looped !== true) {
		return;
	}
	

	if (isNaN(xposition)) return; 
	loopposseek = dxx[0];
	loopposend = dxx[1];
	loopposend *= xfactor;
	loopposseek *= xfactor;
	if (time >= duration * .9999) {
		xseek( loopposseek); 
		return;
	} 
	if (time > loopposend) {
		xseek( loopposseek);
	}
} 

function xseek(xeek) {
	document.getElementById("myVideo").currentTime = xeek;
}
function xseekbar(event) {

	if (typeof barwidth === 'undefined') {
		return;
	}
	thisx = event.clientX;
	fspbar = document.getElementById("progressbar").getBoundingClientRect();
	thisx -= fspbar.left;
	xeek = Math.floor(xfactor * thisx * (slidermax/barwidth));
	xseek(xeek);
}

function toggleFullScreen() {
	var thisdocelement = document.getElementById("loopplayer");
	if (!document.fullscreenElement &&    // alternative standard method
	      !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
		    if (thisdocelement.requestFullscreen) {
		      thisdocelement.requestFullscreen();
		    } else if (thisdocelement.msRequestFullscreen) {
		      thisdocelement.msRequestFullscreen();
		    } else if (thisdocelement.mozRequestFullScreen) {
		      thisdocelement.mozRequestFullScreen();
		    } else if (thisdocelement.webkitRequestFullscreen) {
		      thisdocelement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
		    }
			loop_fs = true;
			showctls();
	  } else {
		if (document.exitFullscreen) {
		      document.exitFullscreen();
		} else if (document.msExitFullscreen) {
		      document.msExitFullscreen();
		} else if (document.mozCancelFullScreen) {
		      document.mozCancelFullScreen();
		} else if (document.webkitExitFullscreen) {
		      document.webkitExitFullscreen();
		}
			fsexit();
	  }
}

fsexit = function() {
	loop_fs = false;
}

window.onresize = function() {
	metaldd();
	if (!document.fullscreenElement &&    // alternative standard method
	      !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {
		     if(xvideo) {fsexit();} 	
	} else {
		

	}
}

// Function to get the value of a cookie by name
function getCookie(name) {
  const cookieValue = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
  return cookieValue ? cookieValue.pop() : "";
}
function playad(ad) {
	url = ad.link;
	document.getElementById("loopplayer").addEventListener("click",adlinkout,false); 
	document.getElementById("loopplayer").style.cursor="pointer"; 
	myVideo = document.getElementById("myVideo");
	if (ad.adtype == "video") {
		myVideo.removeAttribute("poster");
		resumevid = myVideo.src;
		myVideo.src=ad.vidurl;
		myVideo.play(); 
		startPlayback();
		adndx++;
		adisrunning = true;
	}

}
function adlinkout() {
	window.open(url);
}
var draggingvideo = false;
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  elmnt.onmousedown = dragMouseDown;
  
  function dragMouseDown(e) {
  	//draggingvideo = true;
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    //draggingvideo = false;
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

