function SelectAll(id)
{
	document.getElementById(id).focus();
	document.getElementById(id).select();
}
var groupe = "";
var endOpenCategory = true;
var endOpenVideo = true;

/* Trouver un élément Html grâce à son ID */
function GetId(myId){
	return(document.getElementById(myId));
}

/* Fonction servant à switcher entre les page du bloc de navigation. Elle applique un effet de fondu quand on passe d'une page d'affichage des groupes à une page
d'affichage des vidéos et inversement. */

function switchPageNavigation(pageOuvrir, pageFermer) {
    
	$(pageOuvrir).hide();
	$(pageFermer).hide();
	if(VersionMSIE() == 0){
		$(pageFermer).fadeOut();
		$(pageOuvrir).fadeIn();
	}else{
		$(pageFermer).hide();
		$(pageOuvrir).show();
	}
}

/* Trouver la version d'Internet Explorer */
function VersionMSIE(){
	 var ua = window.navigator.userAgent;
	 var msie = ua.indexOf("MSIE ");
	
	 if(msie > 0) // Pour Internet Explorer, retourner la version
		return(parseInt(ua.substring(msie + 5,ua.indexOf(".",msie))));
	 else // Pour les autres navigateurs, retourner 0
		return(0);
}

/* Exécuter les scripts d'un fichier chargé en Ajax */
function ScriptExecuter(position){
	divContent = GetId(position);
	var All = divContent.getElementsByTagName("*");

	for(i = 0; i < All.length; i++){
		All[i].id = All[i].getAttribute("id");
		All[i].name = All[i].getAttribute("name");
		if(VersionMSIE() == 0)
			All[i].className = All[i].getAttribute("class");
	}
	var AllScripts = divContent.getElementsByTagName("script");

	for(i = 0; i < AllScripts.length; i++){
		var s = AllScripts[i];

		if((s.src) && (s.src != "")){ // Basculement en mode synchrone pour éviter des problèmes de dépendances de scripts
			//eval(getFileContent(s.src));
			jQuery.getScript(s.src);
		}else
			eval(s.innerHTML);
	}
	
	// si du contenu FBML est présent on passe dessus
	try{
		FB.XFBML.parse( divContent );
	}catch(ex){}
	// si la partage Google+ est présent on le relance
	try{
		gapi.plusone.go( divContent );
	}catch(ex){}
}

/**
* Retrieve the group from the given category
* Then displays the groups
*/
function openCategory(categorie, scroll) {
	if(endOpenCategory == true){
		endOpenCategory = false;
		jQuery.post(niveauRep+"content/modules/conteneur_episode.php",
			{categorie:categorie, nombre_niv_acces:nombre_niv_acces},
			function(leRetour){
				GetId("page_episodes").innerHTML = leRetour;
				ScriptExecuter("page_episodes");
				if(scroll){
					topscroll = $("#MenuEpi").offset().top
					$("html,body").animate({
						'scrollTop' : topscroll+'px'
					}, 'slow');
				}
				endOpenCategory = true;
			}
		);
	/*	jQuery.post(niveauRep+"content/modules/playeur.php",
			{nombre_niv_acces:nombre_niv_acces, categorie:categorie},
			function(leRetour){
				GetId("zonePlayeur").innerHTML = leRetour;
				endOpenVideo = true;
			}
		);*/
		selectTabbarItem('cat_'+categorie);
	}
}

function chargeNewsVideo(categorie) {
	jQuery.post(niveauRep+"content/modules/bloc_nouveaute_video.php",
		{autrevideo:categorie, nombre_niv_acces:nombre_niv_acces, paramIDVideo:0},
		function(leRetour){
			GetId("autres_videos").innerHTML = leRetour;
		}
	);
}
function chargeAutreVideo(categorie) {
	jQuery.post(niveauRep+"content/modules/bloc_autre_video.php",
		{autrevideo:categorie, nombre_niv_acces:nombre_niv_acces, paramIDVideo:paramIDVideo},
		function(leRetour){
			GetId("autres_videos").innerHTML = leRetour;
		}
	);
}


function partagerVideo(permalien) {

	var share = {
		   method: 'stream.share',
		   u: permalien
	};
	FB.ui(share, function(response) { 
	});
	
	/*window.fbAsyncInit = function() {
		FB.init({
			appId : '121991474505469',
			status : true, // check login status
			cookie : true, // enable cookies to allow the server to access the session
			xfbml : true // parse XFBML
		});*/
		/*
		var share = {
		   method: 'stream.share',
		   u: permalien
		 };*/

		 //FB.ui(share, function(response) { 
     /*if (response && response.post_id) {
       alert("Le message a été publié.");
     } else {
       alert("Le message n'a pas été publié.");
     }*/ //});
		
	//};

	/*
	(function() {
		var e = document.createElement('script');
		e.src = document.location.protocol + '//connect.facebook.net/fr_FR/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	}());*/
}
function chargeAffichage(categorie) {

	jQuery.post(niveauRep+"content/modules/catalogue.php",
		{affichage:categorie, paramIDVideo:paramIDVideo, categorie:paramcategorie, groupe:paramgroupe, nombre_niv_acces:nombre_niv_acces},
		function(leRetour){
			if(categorie == "2"){
			  window.fbAsyncInit = function() {
				FB.init({appId: '121991474505469', status: true, cookie: true,
						 xfbml: true});
			  };
			  (function() {
				var e = document.createElement('script'); e.async = true;
				e.src = document.location.protocol +
				  '//connect.facebook.net/fr_FR/all.js';
				document.getElementById('fb-root').appendChild(e);
			  }());
			}
			GetId("conteneur").innerHTML = leRetour;
			ScriptExecuter("conteneur");
		}
	);
	/*
	jQuery.post(niveauRep+"content/modules/playeur.php",
		{nombre_niv_acces:nombre_niv_acces, categorie:categorie},
		function(leRetour){
			GetId("zonePlayeur").innerHTML = leRetour;
			endOpenVideo = true;
		}
	);*/
}

/**
* openGroup occurs when the user clicked on a group button
* from the category view.
* displays the episodes of the selected group
*/ 
function openGroup(categorie, group, scroll) {
	if(endOpenCategory == true){
		endOpenCategory = false;
		jQuery.post(niveauRep+"content/modules/conteneur_episode.php",
			{categorie:categorie, groupe:group, nombre_niv_acces:nombre_niv_acces},
			function(leRetour){
				GetId("page_episodes").innerHTML = leRetour;
				ScriptExecuter("page_episodes");
				if(scroll){
					topscroll = $("#MenuEpi").offset().top
					$("html,body").animate({
						'scrollTop' : topscroll+'px'
					}, 'slow');
				}
				endOpenCategory = true;
			}
		);
	/*jQuery.post(niveauRep+"content/modules/playeur.php",
		{nombre_niv_acces:nombre_niv_acces, categorie:categorie, groupe:group, paramIDVideo:idvideo},
		function(leRetour){
			GetId("zonePlayeur").innerHTML = leRetour;
			endOpenVideo = true;
		}
	);*/
	}
}

function openVideo(idvideo, categorie) {
	if (idvideo==undefined){
		idvideo = 0;
	}
	if (categorie==undefined){
		categorie = "";
	}
	if(endOpenVideo == true){
		endOpenVideo = false;
		paramIDVideo = idvideo;
		chargeAutreVideo(1);
		jQuery.post(niveauRep+"content/modules/playeur.php",
			{paramIDVideo:idvideo, nombre_niv_acces:nombre_niv_acces, categorie:categorie},
			function(leRetour){
				GetId("zonePlayeur").innerHTML = leRetour;
				topscroll = $("#header_page").offset().top
				$("html,body").animate({
					'scrollTop' : topscroll+'px'
				}, 'slow');
				endOpenVideo = true;
			}
		);
	}
}

var changeInfoFromPlayeur = function (idvideo){
	if(GetId("lePlayeurBottom"))
	{
		paramIDVideo = idvideo;
		jQuery.post(niveauRep+"content/modules/playeurInfo.php",
			{paramIDVideo:idvideo, nombre_niv_acces:nombre_niv_acces},
			function(leRetour){
				GetId("lePlayeurBottom").innerHTML = leRetour;
				ScriptExecuter("lePlayeurBottom");
			}
		);
		return true;
	}else{
		return false;
	}
}

/**
* select an item in the tabbar
*/
function selectTabbarItem(id) {
    deselectTabbarItem();
    $('#'+id).addClass('selected');
    $('#'+id+' a').addClass('highlighted');
    var Categ = $('#'+id+' a').text();
	
	$('#conteneur_categorie p').text(Categ);
	
	if(Categ.search(' ') != -1) {
 		Categ = Categ.replace(/ /g,'_');
	}
}

/**
* Deselect items in the tabbar
*/
function deselectTabbarItem() {
    $('.highlighted').removeClass('highlighted');
    $('.selected').removeClass('selected');
}

function openInfo(div) {
	if (GetId(div).innerHTML == ""){
		fermeInfo();
		jQuery.post(niveauRep+"content/modules/about.php",
			{nombre_niv_acces:nombre_niv_acces},
			function(leRetour){
				GetId(div).innerHTML = leRetour;
			}
		);
	}else{
		fermeInfo();
	}
}
function fermeInfo() {
	GetId("credits").innerHTML = "";
	if(GetId("creditsfooter")){
		GetId("creditsfooter").innerHTML = "";
	}
}
plusInfoOuvert = false;
function ouvrePlusInfo() {
	if (plusInfoOuvert){
		plusInfoOuvert = false;
		$('#PlusInfo').stop(true).animate(
		{
		 'margin-top': '-100%'
		}, 200);
	}else{
		plusInfoOuvert = true;
		$('#PlusInfo').stop(true).animate(
		{
		 'margin-top': '0'
		}, 200);
	}
}
shareOuvert = false;
function ouvreShare() {
	if (shareOuvert){
		shareOuvert = false;
		$('#ShareInfo').stop(true).animate(
		{
		 'margin-top': '-100%'
		}, 200);
	}else{
		shareOuvert = true;
		$('#ShareInfo').stop(true).animate(
		{
		 'margin-top': '0'
		}, 200);
	}
}


var EndScrollLeft = true;
var EndScrollRight = true;

function GroupscrollLeft(div,dep,div_wrapp, classbase, classelect,divcontenu,divgroup) {
	if(EndScrollLeft == true){
		EndScrollLeft = false;
		var deplacement = dep; 
		if($(div).scrollLeft() < deplacement){
			deplacement = $(div).scrollLeft();
		}
		$(div).animate({
			'scrollLeft' : '-='+deplacement+'px'
		}, 'slow', function () {
			buildPagination(div_wrapp, classbase, classelect,divcontenu,divgroup, dep);	
			EndScrollLeft = true;
		});
	}
}

function GroupscrollRight(div,dep,div_wrapp, classbase, classelect,divcontenu,divgroup) {
	if(EndScrollRight == true){
		EndScrollRight = false;
		var deplacement = dep; 
		if(($(div).width - $(div).scrollLeft()) < deplacement){
			deplacement = $(div).width - $(div).scrollLeft();
		}
		$(div).animate({
			'scrollLeft' : '+='+deplacement+'px'
		}, 'slow', function () {
			buildPagination(div_wrapp, classbase, classelect,divcontenu,divgroup, dep);
			EndScrollRight = true;
		});	
	}
}

function buildPagination(div_wrapp, classbase, classelect,divcontenu,divgroup, largeur) {
    $(div_wrapp).empty();
    
    var oNbPoint = calculateNbPoint(divcontenu,divgroup, largeur);
    
    addPoints(oNbPoint.nbPointBeforeSelected, -1000, div_wrapp, classbase, classelect);
    addPoints(1, 0, div_wrapp, classbase, classelect);
    addPoints(oNbPoint.nbPointAfterSelected, -1000, div_wrapp, classbase, classelect);
    var indexSelectedPoint = oNbPoint.nbPointBeforeSelected;
    var currentScrollLeft = $(divgroup).scrollLeft();
    var scrollCurrentBloc = currentScrollLeft;
    
    $.each($(div_wrapp+' a'), function(index, item) {
        $(this).click(function (event) {
            event.preventDefault();
            
       //     var diffIndex = index - indexSelectedPoint;
            
            //console.log('indexCurr: '+index+', indexSelectedPoint: '+indexSelectedPoint+', diffIndex:'+diffIndex);
            var pixelToScroll = index * (largeur);
            
            $(divgroup).animate({
                'scrollLeft': pixelToScroll+'px'
            });
            
            $('.'+classelect).addClass(classbase).removeClass(classelect);
            $(this).addClass(classelect);

        });
    });
    
    var widthPoint = 20;
	
    $(div_wrapp).css({
		
        'width': oNbPoint.nbPoint*widthPoint+'px'
    });
}

function calculateNbPoint(divcontenu, divgroup, largeur) {
    var nbPointBeforeSelected = 0;
    var nbPointAfterSelected = 0;
	var nbPoint = 1;
    if($(divcontenu).width() > largeur){
		nbPoint = parseInt(($(divcontenu).width() - ($(divgroup).width() - largeur) - 1) / largeur) + 1;
		nbPointBeforeSelected = Math.ceil(($(divgroup).scrollLeft()) / largeur);
		if(nbPointBeforeSelected >= nbPoint){
			nbPointBeforeSelected = nbPoint - 1;
		}
		nbPointAfterSelected = nbPoint - nbPointBeforeSelected - 1;
	}
    return {'nbPointBeforeSelected' : nbPointBeforeSelected, 
            'nbPointAfterSelected' : nbPointAfterSelected,
            'nbPoint' : nbPoint};
}

function addPoints(nbPoint, indexSelected, div, classbase, classelect) {
    for (var i = 0; i < nbPoint; i++) {
        var point = null;
        if (i == indexSelected) {
            point = $('<a>').addClass(classelect);
        } else {
            point = $('<a>').addClass(classbase);
        }
        
        point.appendTo($(div));
    }    
    
}


function Timer(){
	timer=setTimeout('MAJProgramme();', tempsMAJProg);
}

function MAJProgramme(){
	jQuery.post(niveauRep+"content/modules/programme.php",
		{nombre_niv_acces:nombre_niv_acces},
		function(leRetour){
			GetId("contenu_resume_programme").innerHTML = leRetour;
			timer=setTimeout('MAJProgramme();', tempsMAJProg);
		}
	);
}


function FormInscriptionNL(){
	var email = $('#champ_inscription_newsletter').val();
	jQuery.post(niveauRep+"content/modules/checkEmail.php",
		{email:email},
		function(leRetour){
			if(leRetour == "1"){
				jQuery.post(niveauRep+"content/modules/inscriptionEmail.php",
					{email:email},
					function(leRetour){
						if(leRetour == "1"){
							$('#champ_inscription_newsletter').val('');
							DisplayAlert("Inscription effectuée.");
						}else{
							DisplayAlert(leRetour);
						}
					}
				);
			}else{
				DisplayAlert("Vous devez saisir<br>une adresse mail valide");
			}
		}
	);
	return false;
}

var fancybox_fake = false;
function DisplayAlert(message){
	
	//message = "<div class='fancy_logo'></div><div class='fancy_contenu'><table><tr><td>"+message+"</td></tr></table></div>";
	message = "<div class='fancy_contenu'><table><tr><td>"+message+"</td></tr></table></div>";
	
	$.fancybox({
		'content' : message,
		'padding' : 0,
		'scrolling' : 'no',
		'centerOnScroll' : true,
		'onStart' : keepCloseButtonVisible
	});
}
function keepCloseButtonVisible(){
	if(!fancybox_fake)
	{
		fancybox_fake = true;
		$("#fancybox-close").after('<a id="fancybox-close-fake"></a>');
		$("#fancybox-close-fake").css('display', 'block');
	}
	
}

function extendVideoPlayer(valeur)
{
	if(valeur)
	{
		$('#zonePlayeur').css('width', 'auto');
		$('#lePlayeur').css('width', '940px');
		// test si on a besoin de la playlist ou pas.
		if($('#lePlayeur').hasClass('playeurPlaylist'))
		{
			$('#lePlayeur').css('height', '655px');
		}else{
			$('#lePlayeur').css('height', '529px');
		}
		/*$('#lePlayeur').stop(true).animate(
		{
		 'width': '940px',
		 'height': '529px'
		}, 500);*/
	}else{
		$('#zonePlayeur').css('width', '640px');
		$('#lePlayeur').css('width', '640px');
		
		// test si on a besoin de la playlist ou pas.
		if($('#lePlayeur').hasClass('playeurPlaylist'))
		{
			$('#lePlayeur').css('height', '446px');
		}else{
			$('#lePlayeur').css('height', '360px');
		}
		/*$('#lePlayeur').stop(true).animate(
		{
		 'width': '640px',
		 'height': '360px'
		}, 500);*/
	}
}
