	/* ====================== HTML5 AUDIO PLAYER V1.06. DEVELOPED BY WEBRAMBO.RU ====================== */

const playerHtml = `
<div class="player player--not-loaded">
	<div class="player__main wrapper__container d-flex ai-center">
		<div class="player__left d-flex ai-center flex-grow-1">
			<div class="player__info flex-grow-1 d-flex ai-center">
				<div class="player__img img-fixed-size"><img src="/templates/${dle_skin}/images/logo.svg" loading="lazy" alt=""></div>
				<div class="player__info-text flex-grow-1">
					<div  class="player__title ws-nowrap">Appuyez sur le bouton Play</div>
					<div class="player__subtitle ws-nowrap">pour lancer la lecture</div>
				</div>
			</div>
			<a href="#" download class="player__dl btn fas fa-arrow-to-bottom" aria-label="Télécharger le morceau"></a>
		</div>
		<div class="player__btns d-flex ai-center">
			<button class="player__btn player__btn-repeat fas fa-redo" title="Activer la répétition de la piste" aria-label="Mettre la piste en boucle"></button>
			<button class="player__btn player__btn-prev fas fa-backward" aria-label="Piste précédente"></button>
			<button class="player__btn player__btn-play fas fa-play" aria-label="Mettre de la musique"></button>
			<button class="player__btn player__btn-next fas fa-forward" aria-label="Piste suivante"></button>
			<button class="player__btn player__btn-playlist fas fa-list-music" aria-label="Ouvrir la playlist"></button>
		</div>
		<div class="player__right d-flex ai-center flex-grow-1">
			<div class="player__time d-flex ai-center jc-flex-end flex-grow-1">
				<div class="player__time-current">0:00</div>
				<div class="player__time-duration">--</div>
			</div>
			<div class="player__volume fas fa-volume d-flex ai-center jc-flex-end">
				<div class="player__range p-relative" style="--range-progress:100%;">
					<input type="range" min="0" max="100" value="50" step="1">
				</div>
				<div class="player__volume-value">50</div>
			</div>
			<ul class="player__equalizer d-flex ai-center jc-center"><li></li><li></li><li></li><li></li><li></li></ul>
		</div>
		<div class="player__bar flex-grow-1 player__range p-relative" style="--range-progress:0%;">
			<input type="range" min="0" max="100" value="0" step="1">
		</div>
		<div class="player__playlist">
			<div class="player__playlist-title fal fa-times fa-pull-right d-flex ai-center jc-space-between">Playlist</div>
			<ul class="player__playlist-list"></ul>
		</div>
	</div>
	<audio  src="" preload="metadata" controls></audio>
</div>`;
bd.insertAdjacentHTML('beforeend',playerHtml);

const player = document.querySelector('.player'), 
	playerImg = document.querySelector('.player__img img'), 
	playerTitle = document.querySelector('.player__title'), 
	playerSubtitle = document.querySelector('.player__subtitle'),
	playerTimeCurrent = player.querySelector('.player__time-current'), 
	playerTimeDuration = player.querySelector('.player__time-duration'), 
	playerLoaded = player.querySelector('.player__loaded'),  
	playerBtnPlay = player.querySelector('.player__btn-play'), 
	playerBtnBack = player.querySelector('.player__btn-prev'), 
	playerBtnNext = player.querySelector('.player__btn-next'), 
	playerBtnRepeat = player.querySelector('.player__btn-repeat'), 
	playerBtnDl = player.querySelector('.player__dl'), 
	playerBtnPlaylist = player.querySelector('.player__btn-playlist'), 
	playerBar = player.querySelector('.player__bar input'), 
	//playerBarProgress = player.querySelector('.player__bar-progress'), 
	playerVolume = player.querySelector('.player__volume input'), 
	//playerVolumeProgress = player.querySelector('.player__volume-progress'), 
	playerVolumeValue = player.querySelector('.player__volume-value'), 
	playerAudio = player.querySelector('audio'), 
	playerPlaylistList = player.querySelector('.player__playlist-list'), 
	playerPlaylistTitle = player.querySelector('.player__playlist-title');
let myplaylist = [], musicIndex = 1;

function buildPlaylistArray() {
	document.querySelectorAll('.js-trc').forEach((element,i) => {
		myplaylist[i] = element.dataset;
	});
};

function buildPlaylist() {
	for ( i = 0; i < myplaylist.length; i++) {
		let playlistItem = `<li class="player__playlist-item d-flex ai-center">
			<div class="player__playlist-item-desc flex-grow-1 d-flex ai-center gap-10" li-index="${i + 1}" onclick="clicked(this)">
				<div class="player__playlist-item-img img-fixed-size">
<img src="${myplaylist[i].img}" loading="lazy" alt="">  
</div>
				<div class="flex-grow-1">
					<div class="player__playlist-item-title ws-nowrap">${myplaylist[i].title}</div>
					<div class="player__playlist-item-subtitle ws-nowrap">${myplaylist[i].subtitle}</div> 
				</div>
				<div class="player__playlist-item-duration">${myplaylist[i].duration}</div>
			</div> 
<a href="${myplaylist[i].src}" download target="_blank" class="player__playlist-item-dl fal fa-arrow-to-bottom"></a>

		</li>`;
		playerPlaylistList.insertAdjacentHTML('beforeend', playlistItem);
	};
};

function detectCurrentTrackInPlaylist(musicIndex) {
	const playlistItem = playerPlaylistList.querySelectorAll('li');
	for ( j = 0; j < playlistItem.length; j++) {
		if ( playlistItem[j].classList.contains('is-playing') ) {
			playlistItem[j].classList.remove('is-playing');
		};
		if ( playlistItem[j].querySelector('.player__playlist-item-desc').getAttribute('li-index') == musicIndex ) {
			playlistItem[j].classList.add('is-playing');
		};
	};
	const playing = playerPlaylistList.querySelector('.is-playing'), 
		scr = playing.offsetTop - playing.offsetHeight - 150;
	playerPlaylistList.scrollTo({top: scr, behavior: 'smooth'});
};

window.addEventListener('load', ()=> {
	buildPlaylistArray();
	//loadMusic(musicIndex);
	let volume = localStorage.getItem('volume');
	if ( !volume) { localStorage.setItem('volume', 1); };
	volume = localStorage.getItem('volume');
	playerAudio.volume = volume;
	const volPercent = Math.floor(volume * 100);
	playerVolume.value = volPercent;
	playerVolumeValue.innerText = volPercent;
	playerVolume.parentElement.style.setProperty('--range-progress',volPercent + '%');
	//playerVolumeProgress.style.width = volPercent + '%';
	if (volume == 0) {
		player.classList.add('player--is-muted');
	};
	//detectCurrentTrack(musicIndex);
	buildPlaylist();
	//detectCurrentTrackInPlaylist(musicIndex);
});

function loadMusic(indexNumb) {
	playerTitle.innerText = myplaylist[indexNumb - 1].title;
	playerSubtitle.innerText = myplaylist[indexNumb - 1].subtitle;
	playerImg.src = myplaylist[indexNumb - 1].img;
	playerAudio.src = myplaylist[indexNumb - 1].src;
	playerBtnDl.href = myplaylist[indexNumb - 1].src;
	playerAudio.addEventListener('loadeddata', ()=> {
		let audioDuration = playerAudio.duration;
		let min = Math.floor(audioDuration/60);
		let sec = Math.floor(audioDuration%60);
		if (sec < 10) {
			sec = `0${sec}`;
		};
		playerTimeDuration.innerText = `${min}:${sec}`;
		const loaded = Math.floor((playerAudio.buffered.end(0) / playerAudio.duration ) * 100);
		playerBar.parentElement.style.setProperty('--loaded-progress',loaded+'%');
	});
};

function playMusic() {
	player.classList.add('player--is-playing');
	player.classList.remove('player--is-paused');
	playerAudio.play();
	let trackCurrent = document.querySelector('.js-trc--is-current');
	if (trackCurrent) {
		trackCurrent.classList.add('js-trc--is-playing');
		trackCurrent.classList.remove('js-trc--is-paused');
	};
};

function pauseMusic() {
	player.classList.remove('player--is-playing');
	player.classList.add('player--is-paused');
	playerAudio.pause();
	let trackCurrent = document.querySelector('.js-trc--is-current');
	if (trackCurrent) {
		trackCurrent.classList.remove('js-trc--is-playing');
		trackCurrent.classList.add('js-trc--is-paused');
	};
};

function detectCurrentTrack(musicIndex) {
	let currentTrackId = myplaylist[musicIndex-1].id, 
		tracks = document.querySelectorAll('.js-trc');
	if (tracks) {
		tracks.forEach( (trc)=> {
			trc.classList.remove('js-trc--is-playing','js-trc--is-current','js-trc--is-paused');
		});
		let trackCurrent = document.querySelector(`[data-id="${currentTrackId}"]`);
		if (trackCurrent) {
			trackCurrent.classList.add('js-trc--is-current');
		};
	};
};

function prevMusic() {
	musicIndex--;
	musicIndex < 1 ? musicIndex = myplaylist.length : musicIndex = musicIndex;
	loadMusic(musicIndex);
	detectCurrentTrack(musicIndex);
	playMusic();
	detectCurrentTrackInPlaylist(musicIndex);
};

function nextMusic() {
	musicIndex++;
	musicIndex > myplaylist.length ? musicIndex = 1 : musicIndex = musicIndex;
	loadMusic(musicIndex);
	detectCurrentTrack(musicIndex);
	playMusic();
	detectCurrentTrackInPlaylist(musicIndex);
};

playerBtnPlay.addEventListener('click', ()=> {
	if (player.classList.contains('player--not-loaded')) {
		player.classList.remove('player--not-loaded');
		loadMusic(musicIndex);
		detectCurrentTrack(musicIndex);
		playMusic();
		detectCurrentTrackInPlaylist(musicIndex);
	} else {
		const isPlaying = player.classList.contains('player--is-playing');
		isPlaying ? pauseMusic() : playMusic();
	};
});

playerBtnBack.addEventListener('click', ()=> {
	prevMusic();
});

playerBtnNext.addEventListener('click', ()=> {
	nextMusic();
});

playerBtnPlaylist.addEventListener('click', (e)=> {
	playerPlaylistList.parentElement.classList.toggle('is-active');
	e.target.classList.toggle('is-active');
});

playerPlaylistTitle.addEventListener('click', ()=> {
	playerBtnPlaylist.click();
});

playerAudio.addEventListener('timeupdate', (e)=> {
	let currentTime = e.target.currentTime;
	let duration = e.target.duration; 
	let progress = parseInt((currentTime/duration)*100);
	if (Number.isNaN(progress)) {
		progress = 0
	};
	playerBar.value = progress;
	playerBar.parentElement.style.setProperty('--range-progress',progress + '%');
	//playerBarProgress.style.width = progress + '%';
	let minCurrent = Math.floor(currentTime/60);
	let secCurrent = Math.floor(currentTime%60);
	if (secCurrent < 10) {
		secCurrent = `0${secCurrent}`;
	};
	playerTimeCurrent.innerText = `${minCurrent}:${secCurrent}`;
	if(playerAudio.buffered.length > 0) {
		const loaded = Math.floor((playerAudio.buffered.end(0) / playerAudio.duration ) * 100);
		playerBar.parentElement.style.setProperty('--loaded-progress',loaded+'%');
	};
});

playerBar.addEventListener('input', ()=> {
	playerAudio.currentTime = playerBar.value * playerAudio.duration / 100;
	playerBar.parentElement.style.setProperty('--range-progress',playerBar.value + '%');
	//playerBarProgress.style.width = playerBar.value + '%';
});

playerVolume.addEventListener('input', ()=> {
	if (playerVolume.value == 0) {
		player.classList.add('player--is-muted');
	};
	if (playerVolume.value > 0) {
		player.classList.remove('player--is-muted');
	};
	playerAudio.volume = playerVolume.value / 100;
	playerVolumeValue.innerText = playerVolume.value;
	playerVolume.parentElement.style.setProperty('--range-progress',playerVolume.value + '%');
	//playerVolumeProgress.style.width = playerVolume.value + '%';
	localStorage.setItem('volume', playerAudio.volume);
});

playerBtnRepeat.addEventListener('click', (e)=> {
	let isRepeated = e.target.getAttribute('title');
	switch(isRepeated) {
		case 'Activer la répétition de la piste': 
		player.classList.add('player--is-repeated');
		e.target.setAttribute('title','Mettre en marche')
		DLEalert("La répétition de la piste en cours est activée", 'Informations');
		break;
		case 'Activer la lecture aléatoire': 
		player.classList.remove('player--is-repeated');
		player.classList.add('player--is-shuffled');
		e.target.setAttribute('title','Passer au mode normal')
		DLEalert("Lecture aléatoire activée", 'Informations');
		break; 
		case 'Activer le mode normal': 
		player.classList.remove('player--is-shuffled');
		e.target.setAttribute('title','Activer la répétition de la piste')
		DLEalert("Mode de lecture normale activé", 'Informations');
		break; 
	};
});

playerAudio.addEventListener('ended', ()=> {
	let isRepeated = playerBtnRepeat.getAttribute('title'); 
	switch(isRepeated) {
		case 'Activer la lecture aléatoire': 
		playerAudio.currentTime = 0;
		loadMusic(musicIndex);
		detectCurrentTrack(musicIndex);
		playMusic();
		break;
		case 'Activer la répétition de la piste': 
		nextMusic();
		break; 
		case 'Activer le mode normal':
		let randIndex;
		do {
			randIndex = Math.floor((Math.random() * myplaylist.length) + 1);
		} while (
			musicIndex == randIndex
		);
		musicIndex = randIndex;
		loadMusic(musicIndex);
		detectCurrentTrack(musicIndex);
		playMusic();
		detectCurrentTrackInPlaylist(musicIndex);
		break;
	};
});

function clicked(element) {
	let getLiIndex = element.getAttribute('li-index');
	musicIndex = getLiIndex;
	loadMusic(musicIndex);
	detectCurrentTrack(musicIndex);
	playMusic();
	detectCurrentTrackInPlaylist(musicIndex);
};

document.addEventListener('click', (e)=> {
	if (e.target.closest('.js-trc__play')) {
		player.classList.remove('player--not-loaded');
		let trackId = e.target.closest('.js-trc__play').id;
		let trackIndex = myplaylist.findIndex( (element) => element.id === trackId ) + 1;
		if (trackIndex != 0) {
			let track = e.target.closest('.js-trc');
			if (track.classList.contains('js-trc--is-current')) {
				if (track.classList.contains('js-trc--is-playing')) {
					pauseMusic();
				} else {
					playMusic();
				};
			} else {
				musicIndex = trackIndex;
				loadMusic(trackIndex);
				detectCurrentTrack(trackIndex);
				playMusic();
				detectCurrentTrackInPlaylist(trackIndex);
			};
		} else {
			myplaylist = [];
			buildPlaylistArray();
			musicIndex = myplaylist.findIndex( (element) => element.id === trackId ) + 1;
			loadMusic(musicIndex);
			detectCurrentTrack(musicIndex);
			playMusic();
			playerPlaylistList.innerHTML = '';
			buildPlaylist();
			detectCurrentTrackInPlaylist(musicIndex);
		};
	};
});

document.addEventListener('click', (e)=> {
	if (e.target.closest('.trc__to-playlist-add')) {
		const id = e.target.closest('.trc__to-playlist-add').dataset.id;
		const trackIndex = myplaylist.findIndex( (element) => element.id === id ) + 1;
		if (trackIndex != 0) {
			DLEalert("Déjà dans la playlist", 'Annuler', 'warning');
		} 
		else {
			//myplaylist.push(e.target.closest('.js-trc').dataset);
			myplaylist.push(document.querySelector('.js-trc[data-id="'+id+'"]').dataset);
			playerPlaylistList.innerHTML = '';
			buildPlaylist();
			detectCurrentTrackInPlaylist(musicIndex);
			DLEalert("Ajouté à la playlist", 'Terminé!', 'success');
		};
		document.querySelector('.overlay').click();
	};
});

document.addEventListener('click', (e)=> {
	if (e.target.closest('.trc__to-playlist-next')) {
		const id = e.target.closest('.trc__to-playlist-next').dataset.id;
		const trackIndex = myplaylist.findIndex( (element) => element.id === id ) + 1;
		if (trackIndex != 0) {
			if (trackIndex == musicIndex) {
				DLEalert("Il est impossible de lire la piste en cour", 'Piste actuel en cour', 'error');
				document.querySelector('.overlay').click();
				return;
			};
			DLEalert("Déjà dans la playlist", 'Déplacer', 'info');
			myplaylist.splice(trackIndex - 1, 1);
			if (musicIndex > trackIndex) {
				musicIndex = musicIndex - 1;
			};
			myplaylist.splice(musicIndex, 0, document.querySelector('.js-trc[data-id="'+id+'"]').dataset);
			playerPlaylistList.innerHTML = '';
			buildPlaylist();
			detectCurrentTrackInPlaylist(musicIndex);
			DLEalert("Ajout des éléments suivants à la playlist", 'Terminé!', 'success');
		} 
		else {
			//myplaylist.splice(musicIndex, 0, e.target.closest('.js-trc').dataset);
			myplaylist.splice(musidetectCurrentTrackInPlaylistcIndex, 0, document.querySelector('.js-trc[data-id="'+id+'"]').dataset);
			playerPlaylistList.innerHTML = '';
			buildPlaylist();
			(musicIndex);
			DLEalert("Ajouté à la playlist", 'Terminé!', 'success');
		};
		document.querySelector('.overlay').click();
	};
});


$(document).ready(function(){
	$(document).on('click','.trc__to-playlist',function(){
		var ddd = $(this).data('id');
		$('body').append('<ul class="ctrl d-none"><li data-id="'+ddd+'" class="d-flex ai-center gap-10 fal fa-plus-circle trc__to-playlist-add">Ajouter à la playlist</li><li data-id="'+ddd+'" class="d-flex ai-center gap-10 fal fa-chevron-circle-right trc__to-playlist-next">Inclure les éléments suivants</li></ul>');
		$('.overlay, .ctrl').fadeIn(200);
	});
});