//variable
path = window.location.pathname.split('/')
path.pop();
path = path.join('/');
site = window.location.origin;
if (site == "null") {
	site = 'file:'
}
videovisible = [];
document.getElementById('contenu').style.display = 'none';
document.getElementById('ferme').addEventListener('click', function (evt) {
	document.getElementById('grille').style.display = '';
	document.getElementById('contenu').style.display = 'none';
	window.location.hash = "";
	fermelecteur();
});

function fermelecteur() {
	for (i = 0; i < videovisible.length; i++) {
		lecteur = document.getElementById(videovisible[i]);
		lecteur.pause();
	}
	document.getElementById('contenuinner').innerHTML = '';
}
function affichagetableau(tab) {
	//detection largeur grille
	nbcasesmaxlargeur = 0;
	for (i = 0; i < tab.length; i++) {
		nbcasesmaxlargeur = Math.max(nbcasesmaxlargeur, tab[i].length);
	}
	divgrille = document.getElementById('grille');
	divgrille.innerHTML = "";
	if (tab.length > 0) //un titre est forcément écrit
	{

		for (i = 0; i < tab.length; i++) {
			var divligne = document.createElement('div');
			divligne.id = 'ligne' + i;
			divligne.className = "ligne";

			var largeurcase = Math.floor(100 / tab[i].length);
			divligne.style.gridTemplateColumns = 'repeat( ' + tab[i].length + ', 1fr)';

			divgrille.append(divligne);

			couleur = "#82E153" + (Math.floor(90 * i / tab.length));
			for (j = 0; j < tab[i].length; j++) {
				var divcase = document.createElement('div');
				divcase.id = 'element' + i + '-' + j;
				divcase.style.width = largeurcase + 'vi';

				if ((tab[i][j][0]).indexOf('(?)') > -1) {
					divcase.style.backgroundImage = 'linear-gradient(45deg, #ffffff00 25%,' + couleur + ' 25%, ' + couleur + ' 50%, #ffffff00 50%, #ffffff00 75%,' + couleur + ' 75%)'
					divcase.style.backgroundSize = '100px 100px';
					divcase.title = 'Optionnel'

					tab[i][j][0] = (tab[i][j][0]).replace('(?)', '');
				}
				else {
					divcase.style.backgroundColor = couleur;
				}
				divcase.className = "case"
				if ((tab[i][j][0]).indexOf('[D]') > -1) {
					tab[i][j][0] = (tab[i][j][0]).replace('[D]', '');
					divcase.className = "case caseD"
					divcase.title = "Niveau Débutant"
				}
				if ((tab[i][j][0]).indexOf('[A]') > -1) {
					tab[i][j][0] = (tab[i][j][0]).replace('[A]', '');
					divcase.className = "case caseA"
					divcase.title = "Niveau Apprenti"
				}
				if ((tab[i][j][0]).indexOf('[C]') > -1) {
					tab[i][j][0] = (tab[i][j][0]).replace('[C]', '');
					divcase.className = "case caseC"
					divcase.title = "Niveau Confirmé"
				}
				if ((tab[i][j][0]).indexOf('[E]') > -1) {
					tab[i][j][0] = (tab[i][j][0]).replace('[E]', '');
					divcase.className = "case caseE"
					divcase.title = "Niveau Expert"
				}
				
				divcase.innerHTML = '<p style="margin: auto;">' + tab[i][j][0] + '</p>';
				divcase.dataset.i = i;
				divcase.dataset.j = j;
				divligne.append(divcase);

				if (tab[i][j].length > 1) {
					var tmpi = i;
					var tmpj = j;
					console.log(i + '+' + j);
					divcase.dataset.i = i;
					divcase.dataset.j = j;
					divcase.addEventListener('click', function (evt) { console.log(evt.target); lancer(evt.currentTarget.dataset.i, evt.currentTarget.dataset.j, tab); });
				}
			}
		}
	}
}

function estlienyoutube(lien) {
	if ((lien.indexOf('youtube') > -1) || (lien.indexOf('youtu.be') > -1)) {
		regexchaine = /^https?:\/\/(?:(?:www|m)\.)?(?:youtube\.com\/watch(?:\?v=|\?.+?&v=)|youtu\.be\/)([a-z0-9_-]+)$/;
		regex = new RegExp(regexchaine, 'i');
		return lien.match(regex)[1];
	}
	else {
		return '';
	}
}

function lancer(i, j, tab) {
	chaine = '';
	chainecontrole = '';
	videovisible = [];
	stylemodifie = ''
	nbelement = tab[i][j].length - 1;
	for (k = 1; k < tab[i][j].length; k++) {
		if (estlienyoutube(tab[i][j][k]) != '') {
			chaine = chaine + '<iframe id="ancre' + tab[i][j][k] + '" src="https://www.youtube.com/embed/' + (estlienyoutube(tab[i][j][k])) + '" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
			chainecontrole = chainecontrole + '<a href="#ancre' + tab[i][j][k] + '" class="bouton" ><img src="./icone/youtube.png"></a>';
		}

		if (tab[i][j][k].slice(-3) == 'mp4') {
			chaine = chaine + '<video id="ancre' + tab[i][j][k] + '"  preload="metadata" id="video' + k + '" controls src="' + site + '' + path + '/' + repertoire + '/video/' + tab[i][j][k] + '">Vidéo</video>';
			videovisible.push('ancre' + tab[i][j][k]);
			chainecontrole = chainecontrole + '<a href="#ancre' + tab[i][j][k] + '" class="bouton" ><img src="./icone/video.png"></a>';
		}

		if (tab[i][j][k].slice(-3) == 'pdf') {
			//chaine=chaine+'<iframe '+stylemodifie+' src="pdf.html?pdf='+site+''+path+'/'+repertoire+'/exercices/'+tab[i][j][k]+'"></canvas>';
			chaine = chaine + '<div class="pdf" id="id' + tab[i][j][k] + '"><canvas style="width:100%" id="idcvs' + tab[i][j][k] + '"></canvas></div>';
			chainecontrole = chainecontrole + '<a href="#id' + tab[i][j][k] + '" class="bouton" ><img src="./icone/pdf.png"></a>';
		}

		if (tab[i][j][k].slice(-4) == 'html') {
			chaine = chaine + '<iframe  id="ancre' + tab[i][j][k] + '"  src="' + repertoire + '/' + tab[i][j][k] + '"></canvas>';
			chainecontrole = chainecontrole + '<a  href="#ancre' + tab[i][j][k] + '" class="bouton" ><img src="./icone/web.png"></a>';
		}
	}
	document.getElementById('contenuinner').innerHTML = chaine;
	for (k = 1; k < tab[i][j].length; k++) {
		if (tab[i][j][k].slice(-3) == 'pdf') {
			lire(site + path + '/' + repertoire + '/exercices/' + tab[i][j][k], 'idcvs' + tab[i][j][k])
		}
	}
	document.getElementById('grille').style.display = 'none';
	document.getElementById('contenu').style.display = '';
	if (nbelement > 1) {
		document.getElementById('controle').innerHTML = chainecontrole;
		document.getElementById('controle').style = 'display:block';
	}
	else {
		document.getElementById('controle').style = 'display:none';
	}
}
function GET(param) {
	var vars = {};
	window.location.href.replace(location.hash, '').replace(
		/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
		function (m, key, value) { // callback
			vars[key] = value !== undefined ? value : '';
		}
	);

	if (param) {
		return vars[param] ? vars[param] : null;
	}
	return vars;
}
var include = function (url, callback) {

	/* on crée une balise<script type="text/javascript"></script> */
	var script = document.createElement('script');
	script.type = 'text/javascript';

	/* On fait pointer la balise sur le script qu'on veut charger
	   avec en prime un timestamp pour éviter les problèmes de cache
	*/

	script.src = url + '?' + (new Date().getTime());

	/* On dit d'exécuter cette fonction une fois que le script est chargé */
	if (callback) {
		script.onreadystatechange = callback;
		script.onload = script.onreadystatechange;
	}

	/* On rajoute la balise script dans le head, ce qui démarre le téléchargement */
	document.getElementsByTagName('head')[0].appendChild(script);
}
repertoire = GET('fichier');
if (repertoire != null) {
	include(repertoire + '/data.js', function () {
		affichagetableau(data);
	})
}
else {
	repertoire = 'thales'
	include('thales/data.js', function () {

		affichagetableau(data);
	})
}
function renderPDFPage(page, canvas) {
	var scale = 1.5;
	var viewport = page.getViewport(scale);
	var context = canvas.getContext('2d');
	canvas.height = viewport.height;
	canvas.width = viewport.width;
	var renderContext = {
		canvasContext: context,
		viewport: viewport
	};
	page.render(renderContext);
}
function lire(pdfurl, cvs) {
	// If absolute URL from the remote server is provided, configure the CORS
	// header on that server.
	var url = pdfurl;

	// Loaded via <script> tag, create shortcut to access PDF.js exports.
	var pdfjsLib = window['pdfjs-dist/build/pdf'];

	// The workerSrc property shall be specified.
	pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdfjs/build/pdf.worker.js';

	// Asynchronous download of PDF
	var loadingTask = pdfjsLib.getDocument(url);
	loadingTask.promise.then(function (pdf) {
		console.log('PDF loaded');

		// Fetch the first page
		var pageNumber = 1;
		pdf.getPage(pageNumber).then(function (page) {
			console.log('Page loaded');

			var scale = 1.5;
			var viewport = page.getViewport({ scale: scale });

			// Prepare canvas using PDF page dimensions
			var canvas = document.getElementById(cvs);

			var context = canvas.getContext('2d');
			canvas.height = viewport.height;
			canvas.width = viewport.width;

			// Render PDF page into canvas context
			var renderContext = {
				canvasContext: context,
				viewport: viewport
			};
			var renderTask = page.render(renderContext);
			renderTask.promise.then(function () {
				console.log('Page rendered');
			});
		});
	}, function (reason) {
		// PDF loading error
		console.error(reason);
	});

}
