/*
           ,-------------------------------------------------------.
          /  Fonctions Javascript pour tester la bande passante     )
         /   et les plugins à la première visite du site           /
        /    Afin de créer des cookies qui serviront aux vidéos   /
       (            Ioan Sameli, 27.03.2006                      /
        `--\   /------------------------------------------------´
           |  /
            \|
             `
           (")-''-(").___..--''"`-._
            \O_ O  )   `-.  (     ).`-.__.´)
            (_Y_.)/  ._   )  `._ `. ``-..-´
          _..`--'_..-_/  /--'_.' ,'
         (il).-''  (li).'  ((!.-'
*/

  /************************************/
 /***   Embedded tests functions   ***/
/************************************/

	// Cookie names are all defined here. AVOID HARDCODE !
	var cookieWM='testWindowsMedia';	// Windows Media
	var cookieRP='testRealPlayer';	// Real Player
	var cookieMF='testFlash';	// Macromedia Flash
	var cookieBW='testBandWidth';	// BandWidth

	// A-t-on besoin de la comptabilité avec l'ancien cookie ?
	var cookieBW='bandWidth';

	// Définit si les tests sont en cours, pour si quelqu'un clique sur un lien vers une vidéo avant d'avoir les résultats
	var testRunning=false;

	// Utile pour tester la bande passante
	var bwTested=false;

	//addToStart(checkAll);
	addToStart(checkWM);
	addToStart(checkMF);
	addToStart(checkRP);
	addToStart(autoSetUserprefs);

	function addToStart(fnc){
	// Add a finction that will be executed at page loading
		if(!window.listStart) window.listStart = new Array();
		window.listStart.push(fnc)
	}

	window.onload = function(){
	// To execute several functions on page load
	// Solution from http://www.ibilab.net/webdev/articles/Javascript/evenements-multiples-chargement-page-7.htm
		var ls = window.listStart;
		if(ls){
			for(iIp=0; iIp<ls.length; iIp++){
				fnc = ls[iIp];
				try {
					if(typeof(fnc) == 'function')fnc();
					else eval(fnc);
				}
				catch(e){trace(e);}
			}
		}
	}

	function initializeTestingZone(){
	// To avoid trouble with §#@%£¬*%# if MSIE, we have to run this BEFORE the page finished loading, or the flash elements will disappear.
	// Function called at the end of remp.php, file included at the end of most of the pages

		// Write all the HTML elements we'll need
		ctrls ='<div id="msgZone"></div>';
		ctrls+='<div id="debugPanel"></div>';

		// We have to display the iframe under safari, or the test won't work.
		if(navigator.appVersion.indexOf('Safari') != -1)strlStyle='display:block;';
		else strlStyle='display:none;';
		ctrls+='<div id="testingZone" style="'+strlStyle+'"></div>';

		document.write(ctrls);

	}

	function checkAll(redo){
	//Call all the tests


		testRunning=true;
		checkWM(redo);	// Windows media
		checkMF(redo);	// Macromedia Flash
		checkRP(redo);	// Real Player
		checkBW(redo);	// BandWidth
	}

	function autoSetUserprefs(redo){
	// Check the user preferences and find the best configuration

		// Get all the tests results from the cookies
		var resWM=mangerBiscuit(cookieWM);
		var resRP=mangerBiscuit(cookieRP);
		var resBW=mangerBiscuit(cookieBW);

		// Does not execute until all the tests are done
		if(resWM&&resRP&&resBW){

			if((redo) || (!mangerBiscuit('favouriteCodec'))){
				if(resRP=='yes')cuireBiscuit('favouriteCodec','realMedia',7);
				else if(resWM=='yes')cuireBiscuit('favouriteCodec','windowsMedia',7);
				else cuireBiscuit('favouriteCodec','none',7);
			}

			if((redo) || (!mangerBiscuit('favouriteBitrate'))){
				if(resBW >= 450)cuireBiscuit('favouriteBitrate','450',7);
				else if(resBW >= 150)cuireBiscuit('favouriteBitrate','160',7);
				else cuireBiscuit('favouriteBitrate','80',7);
			}
			parsePlaylistLinks();
		}
		else if(redo)checkIfFinished('autoSetUserprefs(1)');
	}

	function alreadyTested(cookieName){
		trace('On a déja un cookie nommé <b>'+cookieName+'</b>, Sa valeur est <b>'+mangerBiscuit(cookieName)+'</b> [<a href="javascript:cuireBiscuit(\''+cookieName+'\',\'\',0);trace(\'On a vidé le cookie '+cookieName+' \');">effacer ce cookie</a>]');
	}

	function goToJEC(){
	// When we want to play a video, just call this function and give the ids of the video.
	// It will check all the cookies, and redirect to the right page, according to the user's settings

		// IE for mac is creepy, skip it.
		if((navigator.appVersion.indexOf('MSIE') != -1)&&(navigator.appVersion.indexOf('acint') != -1)){
			alert('Votre navigateur n\'est pas supporté. Veuillez mettre à jour votre navigateur.');
			return;
			}

		// do no play the video until all the tests are finished
		if(testRunning){
			checkIfFinished('goToJEC()');
			return;
		}

		// Get all the tests results from the cookies
		var resWM=mangerBiscuit(cookieWM);
		var resRP=mangerBiscuit(cookieRP);
		var resMF=mangerBiscuit(cookieMF);
		var resBW=mangerBiscuit(cookieBW);

		// If we have all the test results already
		if(resWM&&resRP&&resMF&&resBW){

			// Si on a Windows Media et assez de bande passante (>450) et bah on va vers la page journal en continu
			if(resWM=='yes'&&resBW > 450){
				// Aller hop, assez de bande passante et WM installé, on va vers la page Journal en Continu
				self.location='index.html?siteSect=502400';
				}
			//else if(resMF=='yes'&&resBW > 160){
			else{
				// On a tout juste ce qu'il faut pour aller vers le flash sur la page tsrinfo
				self.location='index.html?siteSect=200000';
			}
		}

		// If not, run the tests and wait for the tests to be finished before launching the video
		else{
			checkAll();
			checkIfFinished('goToJEC()');
		}
	}

	function checkIfFinished(func,count){
	// Check periodically if the tests are finished.

		var elmDisplayPanel=document.getElementById('displayPanel');



		if(!count)count=1;
		count=count+1;

		if(testRunning){
			if(elmDisplayPanel)elmDisplayPanel.style.display='block';
			else document.getElementById('msgZone').innerHTML=('<div id="displayPanel" style="opacity: .75;filter:Alpha(opacity=75);position:absolute;width:33%;left:33%;top:33%;border:1px solid red;font-size:14px;font-weight:bold;background:url(/images/interactif/player/searching.gif) no-repeat left #FFFFFF;-moz-border-radius:16px;padding:32px;padding-left:48px;">Veuillez patienter quelques secondes avant de visionner la vidéo.<br/>Des tests sont en cours d\'exécution.</div>');
			func='checkIfFinished("'+func+'",'+count+')';
			window.setTimeout(func,250);
		}
		else{

			if(elmDisplayPanel)elmDisplayPanel.style.display='none';
			// Warning, if sometimes we don't wait long enough, the cookie may not be yet recorded or something and it would run the test again.
			// But that was more probably caused by a logic bug...

			eval(func);
		}
	}

  /*****************/
 /***   Debug   ***/
/*****************/

	function trace(str,msgClass){
	// To print a debug comment
	// msgClass is used to apply a style on the debug message
		var zone=document.getElementById('loggingZone');
		if(zone)zone.innerHTML='<p class="'+msgClass+'">'+str+'</p>'+zone.innerHTML;
	}

	function activateDebugButtons(){

		tButtons=document.getElementsByTagName('input');
		for(var i=0;i<tButtons.length;i++){
			b=tButtons[i];
			if(b.className=='debugButton'){
				var att = (document.createAttribute("onMouseOver"));
				att.nodeValue = "document.getElementById('consoleInput').value=this.attributes['onclick'].nodeValue.split(';').shift();";
				b.setAttributeNode(att);
			}
		}
	}

  /*************************************/
 /***   Bandwidth tests functions   ***/
/*************************************/

	function checkBW(redo){
	// Bandwidth test if no cookie
		if(!mangerBiscuit(cookieBW)||redo) testBandwidthInPage();
		else {
			alreadyTested(cookieBW);
			testRunning=false;
			}
	}

	function testBandwidthInPage(size){
	// Write an invisible iframe element in the page with an embedded bandwidth test

		// Change the status of the test
		testRunning=true;

		if(size)bwTested=true;
		else {
			bwTested=false;
			size=64;
		}
		var now=new Date();
		var ifrSrc='/download/test-bandwidth-'+size+'k.html?random='+now.getTime();

		var testBandwidthCode = '<iframe id="ifrBw" style="display:block;" src="'+ifrSrc+'" width="1" height="1">&nbsp;</iframe>';
		var tZone = document.getElementById('testingZone');
		if(tZone)tZone.innerHTML=testBandwidthCode;
		trace('On fait le test avec une taille de <b><a href="'+ifrSrc+'">'+size+'Ko</a></b>');
	}

	function setBandwidth(testResult){
	// The embedded bandwidth test will call this function to return the result
	// If the bandwidth is high enough, we'll run a second test to have a more accurate result

		// For that silly macIE that doesn't understand anything, need to create a cookie here because it will fail on next line

		testResult=testResult*8;
		testResult.toString();

		cuireBiscuit(cookieBW,testResult,7);
		trace('Le résultat est '+testResult+' Kbps => cookie');

		if(bwTested==false){
			if(testResult>128)cuireBiscuit(cookieBW,'',2);
			//Maintenant, si on a assez de bande passante, un autre test, plus précis car plus long
			//if(testResult>1024)testBandwidthInPage(1024);
			if(testResult>512)testBandwidthInPage(512);
			else if(testResult>256)testBandwidthInPage(256);
			else if(testResult>128)testBandwidthInPage(128);
			else{
				cuireBiscuit(cookieBW,testResult,7);
				testRunning=false;
			}
		}
		else{
			// maintenant, ceci est la deuxième fois que on a fait le test
			cuireBiscuit(cookieBW,testResult,7);
			testRunning=false;
		}
	}


  /**********************************/
 /***   Window media detection   ***/
/**********************************/

	function checkWM(redo){
		// teste si on a un cookie qui indique la présence du plugin Windows Media.
		// Si on ne l'a pas, on teste si il est présent et on enregistre le cookie
		// la présence du plugin Windows Media Player pour IE (testWMActiveX) et pour les autres navigateurs (checkPlugIn)

		if(!mangerBiscuit(cookieWM)||redo){
			if(testWMActiveX() || checkPlugIn("Windows Media")){
				cuireBiscuit(cookieWM,'yes',30);
				trace('Test: Le plugin Window Media est présent ! On a fait le cookie.');
			}
			else{
				cuireBiscuit(cookieWM,'no',30);
				trace('Test: Erreur ! Pas de plugin Windows media :(  On a fait le cookie.');
			}
		}
		else alreadyTested(cookieWM);
	}

	function testWMActiveX(){
	// MSIE only !
	// Essaie de créer un ActiveX Windows Media. Uniquement valable pour MSIE
		try {
			testWMObject = new ActiveXObject("MediaPlayer.MediaPlayer.1");
			return true;
		}
		catch(f) {
			return false;
		}
	}

	function checkPlugIn(){
	// Mozilla compatible browsers only !
	// recherche dans la collection de plugins avec les strings passés en paramètres
	// Par exemple : "Real","Flash", etc...
	// Ioan Sameli, 2003

		// si le navigateur (IE notamment) ne supporte pas cette méthode, on se casse
		if(! navigator.plugins.length)return false;

		// initialisation des variables
		allFound = false;
	    plugInsCollection = navigator.plugins;

		// Pour chaque plugin trouvé, on regarde si il contient tous les arguments passés à la fonction
		for (i=0;i<plugInsCollection.length;i++) {

			// On passe tout en majuscule pour ne pas être embêté par des bêtises
	        plugInDescription = " " + (plugInsCollection[i].description.toUpperCase());
			plugInName = " " + (plugInsCollection[i].name.toUpperCase());

			// on cherche chaque arguments
			for (j=0;j<arguments.length;j++) {
				if (plugInDescription.indexOf(" " + arguments[j].toUpperCase())!=-1 || plugInName.indexOf(" " + arguments[j].toUpperCase())!=-1) {
					allFound = true;
				}
				else{
					if(allFound!=true)allFound = false;
					break;
				}
			}
			if (allFound)return true;
	   	 }
		return false;
	}

  /********************************/
 /***   Real media detection   ***/
/********************************/

	// Determines si un Real Player superieur au G2 Gold est disponible
	// basé sur le détecteur disponible sur http://www.diplok.com/1ppl/index_real.html
	// retourne 2 si ce n'est pas internet explorer
	// Ioan Sameli, 2003

	function checkRP(redo){
		// teste si on a un cookie qui indique la présence du plugin Real Player.
		// Si on ne l'a pas, on teste si il est présent et on enregistre le cookie
		// la présence du plugin Real Player pour IE (testRealActiveX) et pour les autres navigateurs (checkPlugIn)

		if(!mangerBiscuit(cookieRP)||redo){
			if(testRealActiveX() || checkPlugIn("real")){
				cuireBiscuit(cookieRP,'yes',30);
				trace('Test: Le plugin Real Media est présent ! On a fait le cookie.');
			}
			else{
				cuireBiscuit(cookieRP,'no',30);
				trace('Test: Erreur ! Pas de plugin Real media. On a fait le cookie.');
			}
		}
		else alreadyTested(cookieRP);
	}


	function testRealActiveX(){
		if(navigator.appVersion.indexOf('MSIE')>0)return testThisActiveXVB('rmocx.RealPlayer G2 Control.1');
	}

	/*function testRealActiveX(){
	// Essaie de créer un ActiveX Real et d'en récuperer la version, ne marche que sous IE
	// Désactivé, parce que Real Enterprise ne peut pas être détecté sous MSIE via JS. Voir la fonction en VBscript.
	// Ioan Sameli, 2003

		try {
			testObject = new ActiveXObject("rmocx.RealPlayer G2 Control.1");

			// Since G2 (Real 6), all Real player version numbers begin by 6
			embedVersion = testObject.GetVersionInfo();

			// First version supported : 6.0.6.131 = G2 Gold
			versionArray = embedVersion.split(".");
			conditionA = versionArray[0]>=6;
			conditionB = versionArray[1]>=0;
			conditionC = versionArray[2]>=6;
			conditionD = versionArray[3]>=131;

			if (conditionA && conditionB && conditionC && conditionD)return true;
			return false;
			}
		catch(e) {
			return false;
			}
	}*/

  /**************************************/
 /***   Macromedia flash detection   ***/
/**************************************/

	var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
	var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
	var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;


	function checkMF(redo){
	// Check if Macromedia flash seems installed
		if(!mangerBiscuit(cookieMF)||redo){
			if(DetectFlashVer(7)){
				cuireBiscuit(cookieMF,'yes',1);
				trace('Test: Le plugin Flash est présent ! On a fait le cookie.');
			}
			else{
				cuireBiscuit(cookieMF,'no',1);
				trace('Test: Erreur : Pas de plugin Flash !  On a fait le cookie.');
			}
		}
		else alreadyTested(cookieMF);
	}


	function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision){
	// Fonction qui retourne TRUE si la version demandée de flash à été trouvée (ou version plus récente)
	 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
		for (i=25;i>0;i--) {
			if (isIE && isWin && !isOpera)versionStr = JSGetSwfVerIE(i);
			else versionStr = JSGetSwfVer(i);

			if (versionStr == -1 ) {
				return false;
			} else if (versionStr != 0) {
				if(typeof versionStr=='int' || typeof versionStr=='number') versionMajor = versionStr;

				else{

					if(isIE && isWin && !isOpera) {
						tempArray         = versionStr.split(" ");
						tempString        = tempArray[1];
						versionArray      = tempString.split(",");
					}
					else versionArray      = versionStr.split(".");

					versionMajor      = versionArray[0];
				}

		        // Si revision majeure >= version majeure demandee ET que la version mineure >= version mineure demandée
				if (versionMajor >= reqMajorVer) {
					return true;
				} else {
					return false;
				}
			}
		}
	}
	function JSGetSwfVer(i){
	// Détection flash - navigateur non IE

		if (navigator.plugins != null && navigator.plugins.length > 0) {
			if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
				var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
		      	var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
				descArray = flashDescription.split(" ");
				tempArrayMajor = descArray[2].split(".");
				versionMajor = tempArrayMajor[0];
				versionMinor = tempArrayMajor[1];
				if ( descArray[3] != "" ) {
					tempArrayMinor = descArray[3].split("r");
				} else {
					tempArrayMinor = descArray[4].split("r");
				}
				versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
				flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
	      		} else {
				flashVer = -1;
			}
		}
		else {
			// Flash n'as pas été trouvé
			flashVer = -1;
		}
		return flashVer;
	}
	function JSGetSwfVerIE(){
	// Détection flash - seulement MSIE
		for(var i=15; i>0; i--){
			try{
				var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
				return i;
			}
			catch(e){
			}
		}
		return -1;
	}

  /*****************************/
 /***   General functions   ***/
/*****************************/

	function getURLParam(strGet){
	// récupère le paramètre demandé dans l'url
	// on peut passer en deuxième paramètre une autre URL (si par exemple on est dans des frames)
	// Ioan Sameli, 2003
		var url, args=getURLParam.arguments;

		if(args.length != 1) url = args[1];
		else url = window.location.search;

		if (url!=''){
			url=url.substring(1,url.length);
			liste=url.split("&");
			for (i=0;i<=liste.length-1;i++){
				temp=liste[i].split('=');
				if(temp[0]==strGet)return(temp[1]);
			}
			return(null);
		}
		else return(null);
	}

	function mangerBiscuit(leQuel){
	// function: Get a value from cookie
		if(!document.cookie) return false;
		var biscuits   = document.cookie;
		if (biscuits != ""){
			liste = biscuits.split(";");
			for (i=0;i<=liste.length-1;i++){
				temp = liste[i].split("=");
				if(temp[0].replace(/\s/,'')==leQuel) return(temp[1]);
			}
			return null;
		}
		else return null;
	}

	function cuireBiscuit(leQuel, valeur, maxage){
	// function: Save a value from a cookie
	// maxage is the maximum age in day
		if(!maxage)maxage=90;
		var expire = 1000*60*60*24*maxage;
		var maintenant = new Date();
		var temps = new Date(maintenant.getTime() + expire);
		document.cookie = leQuel+"="+valeur+"; expires="+temps.toGMTString()+"; path=/;";
	}

	// Pour la box A la tv et autres
	function bandePassanteok(){
		if(mangerBiscuit('testBandWidth') >= 160) return true;
		else return false;
	}




  /********************************/
 /***   Old funtions (used ?)  ***/
/********************************/

    // convert all characters to lowercase to simplify testing
    var agt = navigator.userAgent.toLowerCase();

    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is_ie5up to detect IE5.
    var is_major = parseInt(navigator.appVersion);
    var is_minor = parseFloat(navigator.appVersion);

    // Note: Opera and WebTV spoof Navigator.  We do strict client detection.
    // If you want to allow spoofing, take out the tests for opera and webtv.
    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    var is_nav2 = (is_nav && (is_major == 2));
    var is_nav3 = (is_nav && (is_major == 3));
    var is_nav4 = (is_nav && (is_major == 4));
