/* Alt Media manager */
var altMediaMgr = {
	fMediaSelector : "",
	fIsLocal : window.location.protocol == "file:",
	fStrings : ["Montrer les sous-titres",
	/*01*/      "Cacher les sous-titres",
	/*02*/      "Choisir la langue","Off",
	/*04*/      "Clic droit, enregistrer sous ... pour télécharger","Lecture",
	/*06*/      "Désactiver le son","Désactiver le son",
	/*08*/      "Transcription","Consulter la transcription",
	/*10*/      "Alternative vidéo","Consulter l&apos;alternative vidéo (LSF,LPC)",
	/*12*/      "Audio-description","Consulter l&apos;audio-description",
	/*14*/      "Vidéo","Afficher le média d\'origine",
	/*16*/      "Sous-titres","Afficher les sous titres",
	/*18*/      "Pause","Lecture",
	/*20*/      "Activer le son","Désactiver le son",
	/*22*/      "Cacher la transcription","Consulter la transcription",
	/*24*/      "Afficher la vidéo en plein écran","Revenir au mode normal (Appuyer sur ESC)",
	/*26*/      "Pour quitter le plein écran, appuyer sur echap ...","",
	/*28*/      "Barre de navigation","Barre de volume",
	/*30*/		"Afficher la transcription"],

	init : function(pMediaSelector,pOpt){
		scCoLib.util.log("altMediaMgr.init");
		this.fOpt = {forcedOriginalWidth:false, HTML5FullSreen:true};
		if (typeof pMediaSelector != "undefined") this.fMediaSelector = pMediaSelector;
	},

	/* Méthode à appeller lorsque les medias sont prêts (peut être après le onload dans le cas du fallback flash */
	initMedias : function () {
		var vMedias = document.querySelectorAll(this.fMediaSelector);
		for (var i = 0; i < vMedias.length; i++) {
			this.initMedia(vMedias.item(i));

		}
		window.addEventListener('resize', function(event) {
			var vMedias = document.querySelectorAll(altMediaMgr.fMediaSelector);
			for (var i = 0; i < vMedias.length; i++) {
				var vMedia = vMedias.item(i);
				if (vMedia.fSubs) altMediaMgr.xUpdateSubPos(vMedia);
			}
		}, false);
	},

	initMedia: function(pMedia) {
		pMedia.fTranscriptType = pMedia.getAttribute('data-alt-transcript-type');
		pMedia.fAltVideo = pMedia.getAttribute('data-alt-altvideo');
		pMedia.fAudioDesc = pMedia.getAttribute('data-alt-audiodesc');
		pMedia.fAudioDescType = pMedia.getAttribute('data-alt-audiodesctype');

		this.fType = pMedia.fType = pMedia.getAttribute('data-type');
		this.fIsAltBtn = false;
		pMedia.fToolsBtnCnt = 0;
		pMedia.fSubtitles = pMedia.getAttribute('data-subtitles');

		if (pMedia.fTranscriptType) {
			var vTitle = this.fStrings[30];
			if (pMedia.fTranscriptType == 'nav') {
				var vUrl = pMedia.getAttribute('data-alt-transcript-url');
				vTitle += " (" + vUrl.substring(vUrl.lastIndexOf('/')+1) + pMedia.getAttribute('data-alt-transcript-infos') + ")";
			}
			pMedia.fTranscriptBtn = this.xAddBtn(sc$("controlBar"),"transcriptBtn",this.fStrings[8], vTitle);
			pMedia.fTranscriptBtn.fTitle = vTitle;
			altMediaMgr.xSwitchClass(pMedia.fTranscriptBtn,"display_on","display_off",true);
			if (pMedia.fTranscriptType == "nav") {
				pMedia.fTranscriptBtn.fUrl = pMedia.getAttribute('data-alt-transcript-url');
				pMedia.fTranscriptBtn.onclick = function() { window.open(this.fUrl, "_blank") };
			} else {
				pMedia.fTranscriptBtn.fElt = document.getElementById(pMedia.getAttribute('data-alt-transcript-id'));
				pMedia.fTranscriptBtn.onclick = function (pEvent) {
					if (this.fElt.className.indexOf("active") == -1) {
						var vTocTagsClose = this.fElt.querySelector('button.tocTagsClose'),
							vFocusOut = this.fElt.querySelector('.focusOut'),
							vFocusOnCloseBtn = this.fElt.querySelector('.focusOnCloseBtn');

						altMediaMgr.xSwitchClass(this.fElt,"notActive","active",true);
						this.setAttribute("data-checked", "true");
						setTimeout(function() {
							vTocTagsClose.focus();
						}, 200);
						this.title = this.firstElementChild.textContent = altMediaMgr.fStrings[22];
						// Boucle sur le focus
						vFocusOnCloseBtn.onfocus = function() { vTocTagsClose.focus(); }
						vFocusOut.onclick = function() { pMedia.fTranscriptBtn.focus(); }
					} else {
						altMediaMgr.xSwitchClass(this.fElt,"active","notActive",true);
						this.removeAttribute("data-checked");
						this.title = this.fTitle;
					}
					pEvent.stopPropagation();
				};

				if (pMedia.fTranscriptType == "subtitle") {
					if (pMedia.getAttribute('data-alt-transcript-format') == 'vtt') {
						var vTranscriptTxt = pMedia.fTranscriptBtn.fElt.querySelector('div.transcriptTxt');
						this.xVttToTranscript(pMedia.getAttribute('data-alt-transcript-url'), vTranscriptTxt);
					}
				}

				pMedia.fTranscriptBtn.fElt.querySelector('button.tocTagsClose').addEventListener('click', function () {
					altMediaMgr.xSwitchClass(pMedia.fTranscriptBtn.fElt,"active","notActive",true);
					pMedia.fTranscriptBtn.removeAttribute("data-checked");
					pMedia.fTranscriptBtn.title = pMedia.fTranscriptBtn.fTitle;
				});
			}
		}
		if(pMedia.fAudioDesc) {
			pMedia.fAudioDescBtn = this.xAddBtn(sc$("controlBar"),"audiodescBtn",this.fStrings[12],this.fStrings[13]);
			altMediaMgr.xSwitchClass(pMedia.fAudioDescBtn,"display_on","display_off",true);
			pMedia.fAudioDescBtn.media = pMedia;
			if (pMedia.fAudioDescType == "subwindow") {
				pMedia.fAudioDescBtn.onclick = function(){scDynUiMgr.displaySubWindow(this,this.media.fAudioDesc,"extra",{IMBR:true,NOSUBWINTI:true});return false;};
			} else {
				pMedia.fAudioDescMedia = sc$("controlBar").appendChild(document.createElement('audio'));
				pMedia.fAudioDescMedia.setAttribute("src", pMedia.fAudioDesc);
				pMedia.fAudioDescActive = false;

				pMedia.addEventListener("play", function() { if (pMedia.fAudioDescActive) pMedia.fAudioDescMedia.play(); });
				pMedia.addEventListener("pause", function() { pMedia.fAudioDescMedia.pause(); });
				pMedia.addEventListener("seeking", function() { pMedia.fAudioDescMedia.pause(); pMedia.fAudioDescMedia.currentTime = pMedia.currentTime; });
				pMedia.addEventListener("seeked", function() { if (!pMedia.paused && pMedia.fAudioDescActive) pMedia.fAudioDescMedia.play(); });
				pMedia.fAudioDescBtn.onclick = function() {
					if (this.hasAttribute("data-checked")){
						this.removeAttribute("data-checked");
						this.media.fAudioDescMedia.pause();
						this.media.fAudioDescActive = false;
					} else {
						this.setAttribute("data-checked", "true");
						this.media.fAudioDescMedia.currentTime = pMedia.currentTime;
						if (!this.media.paused) this.media.fAudioDescMedia.play();
						this.media.fAudioDescActive = true;
					}
				}
			}

		}
		if(pMedia.fAltVideo) {
			pMedia.fAltVideoBtn = this.xAddBtn(sc$("controlBar"),"altvideoBtn",this.fStrings[10],this.fStrings[11]);
			altMediaMgr.xSwitchClass(pMedia.fAltVideoBtn,"display_on","display_off",true);
			pMedia.fAltVideoBtn.media = pMedia;
			pMedia.fAltVideoBtn.onclick = function(){
				this.media.fAltVideoWinId = scDynUiMgr.displaySubWindow(this,this.media.fAltVideo,"extra",{IMBR:true,NOSUBWINTI:true});
				this.setAttribute("data-checked", "true");
				return false;
			};
			scDynUiMgr.subWindow.addCloseListener(function(pId) {
				if (pId == pMedia.fAltVideoBtn.fSwId) {
					pMedia.fAltVideoBtn.removeAttribute("data-checked");
				}
			});
		}
		this.initSubTitles(pMedia);
		if (pMedia.fSubs) pMedia.addEventListener('timeupdate', function (){
			// Lance le traitement des sous-titres
			altMediaMgr.xUpdateSub(this);
		}, false);
	},


	initSubTitles : function(pMedia) {
		if(!pMedia.fSubtitles || this.fIsLocal) return;
		this.fIsAltBtn = true;
		pMedia.fToolsBtnCnt += 1;

		// Traitement des sous titres et création de l'objet
		var vSubTemp = this.xDeserialiseObjJs(pMedia.fSubtitles).subtitles,
			isVideo = false;
		pMedia.fSubs = {};
		pMedia.fSubs.fSubtitles = [];

		for (var i = 0; i < vSubTemp.length; i++) {
			var vSubs = vSubTemp[i];
			pMedia.fSubs.fSubtitles[i] = {};
			pMedia.fSubs.fSubtitles[i].lang = vSubs.lang;
			pMedia.fSubs.fSubtitles[i].file = vSubs.url;
			pMedia.fSubs.fSubtitles[i].format = vSubs.format;
			pMedia.fSubs.fSubtitles[i].video = vSubs.format!="srt"&&vSubs.format!="vtt"?true:false;
			if(vSubs.format!="srt"&&vSubs.format!="vtt") isVideo = vSubs.url;
		}

		// Création des éléments
		pMedia.fSubs.fSubBox = scDynUiMgr.addElement("div",pMedia.parentNode,"subBox subDisplay_off");
		pMedia.fSubs.fSubBoxCo = scDynUiMgr.addElement("div",pMedia.fSubs.fSubBox,"subBox_co subDisplay_off");
		pMedia.fSubs.fSubHolder = scDynUiMgr.addElement("div",pMedia.fSubs.fSubBoxCo,"subtitles");
		pMedia.fSubs.fSubHolder.title = this.fStrings[16];
		pMedia.fSubs.fSubHolder.setAttribute("aria-live", "polite");
		pMedia.fSubs.fSubHolder.setAttribute("aria-relevant", "text");

		// Déclaration de la langue par défaut : la première rentrée
		pMedia.fSubs.fLang = pMedia.fSubs.fSubtitles[0].lang;

		// Création du lien sur le bouton permettant le choix des sous-titres
		var vBtnDisplayLangSub = this.xAddBtn(sc$("controlBar"),"subtitlesBtn",this.fStrings[16],this.fStrings[17]);
		altMediaMgr.xSwitchClass(vBtnDisplayLangSub,"display_on","display_off",true);
		pMedia.fSubs.fBtnDisplayLangSub = vBtnDisplayLangSub;
		vBtnDisplayLangSub.media = pMedia;
		vBtnDisplayLangSub.onclick = this.sToggleSubs;
		vBtnDisplayLangSub.fSubs = pMedia.fSubs;

		// Création de la liste des langues et changement du title de vBtnDisplayLangSub s'il y a plus d'un sous-titre
		pMedia.fSubs.fBtnsLang = [];
		if(pMedia.fSubs.fSubtitles.length > 1) {
			vBtnDisplayLangSub.title = this.fStrings[2];
			pMedia.fSubs.fBtnsLangList = scDynUiMgr.addElement("ul",sc$("controlBar"),"btnsLangList subDisplay_off");
			var vSubLi = scDynUiMgr.addElement("li",pMedia.fSubs.fBtnsLangList);
			var vSubBtn = this.xAddLnk(vSubLi, "btnSub_choice subSelect_on", this.fStrings[3], this.fStrings[1]);
			pMedia.fSubs.fBtnsLang.push(vSubBtn);
			vSubBtn.fSubs = pMedia.fSubs;
			vSubBtn.onclick = this.sHideSubs;

		} else vBtnDisplayLangSub.title = this.fStrings[0];

		for (var i = 0; i < pMedia.fSubs.fSubtitles.length; i++) {
			var vSubtitles = pMedia.fSubs.fSubtitles[i];
			// Si c pas une vidéo
			if(!vSubtitles.video) {
				vSubtitles.showing = false;
				vSubtitles.active = 0;
				// On ajoute les sous-titres
				this.xSubsAdd(vSubtitles.file,i,pMedia.fSubs.fSubtitles);
			}
			// Création de la liste des langues
			if(pMedia.fSubs.fSubtitles.length > 1) {
				console.log(vSubtitles);
				var vSubLi = scDynUiMgr.addElement("li",pMedia.fSubs.fBtnsLangList);
				var vSubBtn = this.xAddLnk(vSubLi, "btnSub_choice", vSubtitles.lang);
				pMedia.fSubs.fBtnsLang.push(vSubBtn);
				vSubBtn.fSubs = pMedia.fSubs;
				vSubBtn.fSub = vSubtitles;
				vSubBtn.onclick = this.sToggleSubLang;
			}
		}
	},

	/* ===  ============================================================ */


	sToggleSubs : function() {
		// Choix des langues si plusieurs langues ou toggle on/off sous-titres
		try{
			if(this.fSubs.fSubtitles.length > 1) altMediaMgr.xSubLangSelect(this);
			else altMediaMgr.xToggleSubsOnOff(this);
			altMediaMgr.xUpdateSub(this.media);
		} catch(e){}
		return false;
	},

	sHideSubs : function() {
		// Cache les sous-titres et ferme le menu des sous titres
		try{
			altMediaMgr.fIsSubBtnClicked = 0;
			this.subvis = false;
			altMediaMgr.xHideSubs(this);
			altMediaMgr.xSubLangSelect(this);
		} catch(e){}
		return false;
	},

	sToggleSubLang : function() {
		// Choix des langues et affichage du bon sous-titres
		try{
			altMediaMgr.fIsSubBtnClicked = 1;
			this.subvis = true;
			altMediaMgr.xShowSubs(this);
			if(this.fSub.showing) altMediaMgr.xShowSub(this.fSubs.fSubHolder, this.fSub[this.fSub.lang][this.fSub.active].text, true);
			this.fSubs.fLang = this.fSub.lang;
			altMediaMgr.xSubLangSelect(this);
		} catch(e){}
		return false;
	},

	sToggleFullScreen : function() {
		try{
			altMediaMgr.xToggleFullScreen(this);
		} catch(e){}
		return false;
	},


	/* ===  ============================================================ */
	xToggleSubsOnOff : function(pBtn,pVis) {
		// Toggle sous-titres on/off
		if(!pBtn) return;
		var vSubVis = pBtn.subvis?pBtn.subvis:pVis;
		if (vSubVis){
			altMediaMgr.xHideSubs(pBtn);
			pBtn.title = altMediaMgr.fStrings[0];
			pBtn.subvis = false;
			this.fIsSubBtnClicked = 0;
		} else {
			altMediaMgr.xShowSubs(pBtn);
			pBtn.title = altMediaMgr.fStrings[1];
			pBtn.subvis = true;
			this.fIsSubBtnClicked = 1;
		}
	},

	xShowSubs : function(pBtn) {
		// Montre les sous-titres
		if(!pBtn) return;
		this.xSwitchClass(pBtn.fSubs.fSubBox, "subDisplay_off", "subDisplay_on", true);
		var vRootButton = pBtn.tagName.toLowerCase()!="a"?pBtn:pBtn.fSubs.fBtnDisplayLangSub;
		vRootButton.setAttribute("data-checked", "true");
		var vClasse=vRootButton.className.indexOf(' ')==-1?vRootButton.className:vRootButton.className.substr(0,vRootButton.className.indexOf(' '));
		vRootButton.title = vRootButton.firstElementChild.textContent = this.fStrings[1];
	},

	xHideSubs : function(pBtn) {
		// Cache les sous-titres
		if(!pBtn) return;
		this.xSwitchClass(pBtn.fSubs.fSubBox, "subDisplay_on", "subDisplay_off", true);
		var vRootButton = pBtn.tagName.toLowerCase()!="a"?pBtn:pBtn.fSubs.fBtnDisplayLangSub;
		var vClasse=vRootButton.className.indexOf(' ')==-1?vRootButton.className:vRootButton.className.substr(0,vRootButton.className.indexOf(' '));
		vRootButton.title = vRootButton.firstElementChild.textContent = this.fStrings[1];
		vRootButton.removeAttribute("data-checked");
		if(pBtn.tagName.toLowerCase()=="a") {
			// On repasse la liste de choix active sur le off
			for (var i = 0; i < pBtn.fSubs.fBtnsLang.length; i++) {
				var vBtn = pBtn.fSubs.fBtnsLang[i];
				if(i == 0) this.xSwitchClass(vBtn, "subSelect_off", "subSelect_on", true);
				else this.xSwitchClass(vBtn, "subSelect_on", "subSelect_off", true);
			}
		}
	},

	xSubLangSelect : function(pBtn) {
		// Ouverture du menu des sous-titres
		if(!pBtn) return;
		if (!pBtn.fSubs.subLangState) {
			this.xSwitchClass(pBtn.fSubs.fBtnsLangList, "subDisplay_off", "subDisplay_on", true);
			pBtn.fSubs.subLangState = true;
		} else {
			this.xSwitchClass(pBtn.fSubs.fBtnsLangList, "subDisplay_on", "subDisplay_off", true);
			if (pBtn.fSubs.fBtnsLang.indexOf(pBtn) != -1) {
				for (var i = 0; i < pBtn.fSubs.fBtnsLang.length; i++) {
					var vBtn = pBtn.fSubs.fBtnsLang[i];
					if(pBtn == vBtn) this.xSwitchClass(pBtn, "subSelect_off", "subSelect_on", true);
					else this.xSwitchClass(vBtn, "subSelect_on", "subSelect_off", true);
				}
			}
			pBtn.fSubs.subLangState = false;
		}
	},

	xShowSub : function(pElt, pText, pIsActive) {
		// Insertion des sous-titre s'ils sont actifs
		if(pIsActive) pElt.innerHTML = pText;
		else pElt.innerHTML = "";
	},

	xUpdateSub : function(pMedia) {
		altMediaMgr.xUpdateSubPos(pMedia);
		var vRootMedia = document.querySelector('#mediafull, #media');
		vRootMedia.addEventListener('transitionend', function() {
			altMediaMgr.xUpdateSubPos(pMedia);
		});

		// Affichage des sous-titres en fonction de la postion et du temps
		if(!pMedia.fSubtitles) return;
		for(var i in pMedia.fSubs.fSubtitles){
			var vSubsObj = pMedia.fSubs.fSubtitles[i];

			if(!vSubsObj[vSubsObj.lang]) return 0;

			var vRecordedTime 	= vSubsObj[vSubsObj.lang].curTime || 0,
				vCurrentTime 	= pMedia.currentTime;

			if(!pMedia.paused && vCurrentTime === vRecordedTime) continue;
			else {
				var j = vSubsObj.active;
				vSubsObj[vSubsObj.lang].curTime = vCurrentTime;
				if(vRecordedTime <= vCurrentTime) {
					if((vSubsObj[vSubsObj.lang][j].end > vCurrentTime && vSubsObj.showing)) continue;

					for(var dd = j; dd < vSubsObj[vSubsObj.lang].length; dd++ )
						if(!altMediaMgr.xSubtitleLoop(vSubsObj,vCurrentTime,dd,pMedia)) break;

					for(var dd = 0; dd < j; dd++)
						if(!altMediaMgr.xSubtitleLoop(vSubsObj,vCurrentTime,dd,pMedia)) break;

				} else if( vRecordedTime > vCurrentTime )
					for(j = j; j >= 0; j-- )
						if(!altMediaMgr.xSubtitleLoop(vSubsObj,vCurrentTime,dd,pMedia)) break;
			}
		}
	},

	xUpdateSubPos: function (pMedia) {
		var vBoxRatio = pMedia.clientWidth / pMedia.clientHeight;
		var vVideoRatio = pMedia.videoWidth / pMedia.videoHeight;
		var vWidth, vHeight;
		if (vBoxRatio > vVideoRatio) {
			vWidth = pMedia.clientHeight * vVideoRatio;
			vHeight = pMedia.clientHeight;
		} else {
			vWidth = pMedia.clientWidth;
			vHeight = pMedia.clientWidth / vVideoRatio;
		}
		var vBottom = pMedia.clientHeight / 2 - vHeight / 2;
		pMedia.fSubs.fSubBox.style.width = vWidth + "px";
		pMedia.fSubs.fSubBox.style.left = pMedia.clientWidth / 2 - vWidth / 2 + "px";
		pMedia.fSubs.fSubBox.style.bottom =  pMedia.clientHeight / 2 - vHeight / 2 + "px";
	},

	xSubtitleLoop : function(pSubsObj, pCurrentTime, pKey, pMedia){
		// Loop sur le tableau des sous-titres pour affichage
		var vSrtTmp = pSubsObj[pSubsObj.lang][pKey]

		// Réinititalisation si pas de vSrtTmp
		if(!vSrtTmp) {
			for(var i in pMedia.fSubs.fSubtitles) pMedia.fSubs.fSubtitles[i].showing = false;
			this.xSwitchClass(pMedia.fSubs.fSubBoxCo, "subDisplay_on", "subDisplay_off", true);
			return;
		}

		var vTimeStart = vSrtTmp.start,
			vTimeEnd = vSrtTmp.end;

		if(pCurrentTime >= vTimeStart && pCurrentTime < vTimeEnd) {
			if(pSubsObj.active !== pKey || pSubsObj.showing === false) {
				pSubsObj.active = pKey;
				if(pSubsObj[pMedia.fSubs.fLang]) this.xShowSub(pMedia.fSubs.fSubHolder, vSrtTmp.text, true); //on
				pSubsObj.showing = true;
				this.xSwitchClass(pMedia.fSubs.fSubBoxCo, "subDisplay_off", "subDisplay_on", true);
			}
			return false;
		} else {
			if(pSubsObj.active === pKey) {
				pSubsObj.showing = false;
				if(pSubsObj[pMedia.fSubs.fLang]) this.xShowSub(pMedia.fSubs.fSubHolder, vSrtTmp.text, false); //off
				this.xSwitchClass(pMedia.fSubs.fSubBoxCo, "subDisplay_on", "subDisplay_off", true);
			}
		}
		return true;
	},

	xSubsAdd : function(pFile, pKey, pSubs) {
		// Chargement des sous-titres
		var vSub = pSubs[pKey];
		var vReq = null;
		if(window.XMLHttpRequest && (!this.fIsLocal || !window.ActiveXObject)) vReq = new XMLHttpRequest();
		else if(window.ActiveXObject) vReq = new ActiveXObject("Microsoft.XMLHTTP");
		vReq.open("GET", pFile, true);
		vReq.onreadystatechange = function () {
			if(vReq.readyState != 4) return;
			if(vReq.status != 0 && vReq.status != 200 && vReq.status != 304) {
				alert("ERROR : unable de retrieve "+pFile+": " + vReq.status);
				return;
			}
			vSub[vSub.lang] = vSub.format == "srt" ? altMediaMgr.xSrtSubsParser(vReq.responseText) : altMediaMgr.xVttSubsParser(vReq.responseText);
		}
		vReq.send();
	},

	//Parser from http://bubbles.childnodes.com/
	xSrtSubsParser : function(obj) {
		// Parsage des sous-titres dans un objet
		var fileLines = obj.split('\n'),
			len = fileLines.length - 1,
			ret = [],
			old_int = 0,
			j = 0,
			tmp,
			c,
			str="";

		for(var i = 0; i < len; i++) {
			var string = fileLines[i].replace(/^\s+|\s+$/g, "");
			if(!isNaN(string) &&  parseInt(fileLines[i]) === (old_int + 1)) {
				++j;

				old_int = parseInt(fileLines[i]);
				ret[ j ] = [];

				tmp = [];
				tmpEnd = [];
				tmp = fileLines[ ++i ].split("-->");

				tmpEnd = tmp[1].split(" ");
				tmp[1] = tmpEnd[1].replace(".",",");
				tmp[0] = tmp[0].replace(".",",");

				ret[j]["start"]	= this.xToSecs(tmp[0]);
				ret[j]["end"]	= this.xToSecs(tmp[1]);
				ret[j]["text"]	= "";
				ret[j]["cue"]	= tmpEnd[2]?tmpEnd[2]:"";

				c = 0;
				while(fileLines[i + c+1] && fileLines[i + ++c].replace(/^\s+|\s+$/g, "" ) !== "")
					ret[j]["text"] += fileLines[i + c].replace(/\n\r|\r\n|\n|\r/g, "<br />");
			}
		}

		//printing the array
		tmp = ret.length;
		str = [];
		for(var i = 1;i < tmp;i++) {
			str[ i - 1 ] = {
				start:	ret[i]["start"],
				end:	ret[i]["end"],
				text: 	ret[i]["text"],
				cue: 	ret[i]["cue"]
			};
		}
		return str;
	},

	xVttSubsParser: function(pSubText) {
		var vParser = new WebVTT.Parser(window, WebVTT.StringDecoder());
		var vSubs = [];
		vParser.oncue = function(vCue) {
			vSubs.push({
				start: vCue.startTime,
				end: vCue.endTime,
				text: vCue.getCueAsHTML().innerHTML.replace(/\n/g, '<br />')
			});
		};
		vParser.parse(pSubText);
		vParser.flush();
		return vSubs;
	},

	/* === Utilities ============================================================ */
	/** altMediaMgr.xToSecs. */
	xToSecs : function(pTime) {
		var vSec = 0.0, vTimeTab = [];
		if (pTime) {
			vTimeTab = pTime.split(':');
			for (var i = 0; i < vTimeTab.length; i++) vSec = vSec * 60 + parseFloat(vTimeTab[i].replace(',','.'));
		}
		return vSec;
	},

	/** altMediaMgr.xDeserialiseObjJs. */
	xDeserialiseObjJs : function(pStr){
		if(!pStr) return {};
		var vVal;
		eval("vVal="+pStr);
		return vVal;
	},

	/** altMediaMgr.xAddBtn : Add a HTML button to a parent node. */
	xAddBtn : function(pParent, pClassName, pCapt, pTitle, pNxtSib) {
		var vBtn = pParent.ownerDocument.createElement("button");
		vBtn.className = pClassName;
		vBtn.fName = pClassName;
		if (pTitle) vBtn.setAttribute("title", pTitle.replace("&apos;","'"));
		var vSpan = vBtn.appendChild(pParent.ownerDocument.createElement("span"));
		vSpan.appendChild(pParent.ownerDocument.createTextNode(pTitle));
		if (pNxtSib) pParent.insertBefore(vBtn,pNxtSib);
		else pParent.appendChild(vBtn);
		return vBtn;
	},

	xAddLnk : function(pParent, pClassName, pCapt, pTitle, pNxtSib) {
		var vBtn = pParent.ownerDocument.createElement("a");
		vBtn.className = pClassName;
		vBtn.fName = pClassName;
		vBtn.href = "#";
		vBtn.target = "_self";
		if (pTitle) vBtn.setAttribute("title", pTitle);
		if (pCapt) vBtn.innerHTML = '<span class="capt">' + pCapt + '</span>';
		if (pNxtSib) pParent.insertBefore(vBtn,pNxtSib);
		else pParent.appendChild(vBtn);
		return vBtn;
	},

	/** altMediaMgr.xSwitchClass - replace a class name. */
	xSwitchClass : function(pNode, pClassOld, pClassNew, pAddIfAbsent, pMatchExact) {
		var vAddIfAbsent = typeof pAddIfAbsent == "undefined" ? false : pAddIfAbsent;
		var vMatchExact = typeof pMatchExact == "undefined" ? true : pMatchExact;
		var vClassName = pNode.className;
		var vReg = new RegExp("\\b"+pClassNew+"\\b");
		if (vMatchExact && vClassName.match(vReg)) return;
		var vClassFound = false;
		if (pClassOld && pClassOld != "") {
			if (vClassName.indexOf(pClassOld)==-1){
				if (!vAddIfAbsent) return;
				else if (pClassNew && pClassNew != '') pNode.className = vClassName + " " + pClassNew;
			} else {
				var vCurrentClasses = vClassName.split(' ');
				var vNewClasses = new Array();
				for (var i = 0, n = vCurrentClasses.length; i < n; i++) {
					var vCurrentClass = vCurrentClasses[i];
					if (vMatchExact && vCurrentClass != pClassOld || !vMatchExact && vCurrentClass.indexOf(pClassOld) != 0) {
						vNewClasses.push(vCurrentClasses[i]);
					} else {
						if (pClassNew && pClassNew != '') vNewClasses.push(pClassNew);
						vClassFound = true;
					}
				}
				pNode.className = vNewClasses.join(' ');
			}
		}
		return vClassFound;
	},

	xVttToTranscript: function (pVttUrl, pDestElt) {
		// Chargement des sous-titres
		var vReq = null;
		if(window.XMLHttpRequest && (!this.fIsLocal || !window.ActiveXObject)) vReq = new XMLHttpRequest();
		else if(window.ActiveXObject) vReq = new ActiveXObject("Microsoft.XMLHTTP");
		vReq.open("GET", pVttUrl, true);
		vReq.onreadystatechange = function () {
			if(vReq.readyState != 4) return;
			if(vReq.status != 0 && vReq.status != 200 && vReq.status != 304) {
				alert("ERROR : unable de retrieve "+pVttUrl+": " + vReq.status);
				return;
			}
			var vParser = new WebVTT.Parser(window, WebVTT.StringDecoder());
			var vCues = [];
			vParser.oncue = function(vCue) { vCues.push(vCue); };
			vParser.parse(vReq.responseText);
			vParser.flush();

			var vFragment = document.createDocumentFragment();
			var vCurrentVoice = null;
			var vCurrentPara = vFragment.appendChild(document.createElement('p'));

			vCues.forEach(function(vCue) {
				var vCueElt = vCue.getCueAsHTML();
				while (vCueElt.firstChild) {
					var vCuePartLinkElt = document.createElement('a');
					vCuePartLinkElt.href = '#t=' + vCue.startTime;
					vCuePartLinkElt.className = 'txt_tcLink';
					var vVoice = vCueElt.firstChild.localName == 'span' ? vCueElt.firstChild.getAttribute('title') : null;
					if (vVoice != vCurrentVoice) {
						vCurrentPara = vFragment.appendChild(document.createElement('p'));
						if (vVoice) {
							vCurrentPara.appendChild(document.createTextNode(vVoice));
							vCurrentPara.className = 'voice';
							vCurrentPara = vFragment.appendChild(document.createElement('p'));
						}
						vCurrentVoice = vVoice;
					}
					vCuePartLinkElt.appendChild(vCueElt.firstChild);
					vCurrentPara.appendChild(vCuePartLinkElt);
					vCurrentPara.appendChild(document.createTextNode(' '));
				}
			});
			pDestElt.appendChild(vFragment);
		};
		vReq.send();
	}
}
