var trace=function(){try{console.log.apply(console,arguments);}catch(e){try{opera.postError.apply(opera, arguments);}catch(e){}}};
var vp;
function whenOnLoad(){
	//trace("onReady");
	$("#logoloader").fadeOut();
	$("#logo").fadeIn();	
	
	//slider pour about
	/*		$('#banner_w2p').cycle({
				fx: 'fade',
				speed: 800,
				timeout: 6000
			});
		*/
////////////////////////////////	IE FIX
	var nav = navigator.appName;
	if( nav == "Microsoft Internet Explorer"){	
		$("source").remove();	
	}
/////////	
	//<-------------------->//
	//je cache la GUI
	$("#uicontainer").hide();	
	$("#aboutContainer").hide();
	//**** OUVERTURE & FERMETURE sideBarre & bloquage UI *****//
	$('#sidebarre').mouseleave(function(){
			$('#sidebarre').animate({"right":'-365px'},{ duration: 500, queue: false});
			$('#bt_top').animate({'right':'0'},{ duration: 500,  queue: false});
			hideMe = true;// boolean pour le timer UI
	});
	$('#sidebarre').mouseenter(function(){
			window.clearInterval(timerUI); // je stop le timer UI
			hideMe = false;// boolean pour le timer UI en cas de MV souris
	})
	/*** GESTION SCROLL MENU ***/
	var wh = $(window).height(); 
	var fh = $("#uicontainer").height(); 
	var h = wh - fh - $("#barreTemoins").height(); 
	// Override default parameters onload
	$.fn.hoverscroll.params = $.extend($.fn.hoverscroll.params, {
		vertical : true,
		width: 280, //<-- width des images
		height: h,
		arrows: true
		//fixedArrows: true
	});
	// Generate hoverscroll with overridden default parameters
	var mv = $('#listeVertical').hoverscroll();	
	mv.scrollTop(0);
	
// pour faire rapparaitre le bt pour scroller en bas dans la page about quand le scroll est en haut	cf open about
$('#aboutContainer').scroll(function() {
	 if ($("#aboutContainer").scrollTop() == 0){
	 	$("#basAbout").show();
	 	$("#hautAbout").hide();		
	}else{
	 	$("#basAbout").hide();
		$("#hautAbout").show();					
	}
});		
	//lance le player apres la liste vertical pour eviter un bug du au resize forcé au 1er lancement
	if(supports_video()){
		 vp = new PlayVideo(); //<-- lance la video si support html5
	}else{
////////////////////////////////////////////////////////////	
//		****PLAY PAUSE SI FLASH PLAYER******			  //
////////////////////////////////////////////////////////////
		var barreTemoins = document.getElementById('barreTemoins');	
		var play =  document.getElementById('play');
		var nav = navigator.appName;
		if( nav == "Microsoft Internet Explorer"){	
			play.attachEvent("onclick", playControlFlash);
			barrePosition.attachEvent('onclick',jumpToFlash);	
			barrePreload.attachEvent('onclick',jumpToFlash);
			barreTemoins.attachEvent('onclick',jumpToFlash);			
		}else {
			play.addEventListener('click',playControlFlash,false);
			barrePosition.addEventListener('click',jumpToFlash,false);	
			barrePreload.addEventListener('click',jumpToFlash,false);
			barreTemoins.addEventListener('click',jumpToFlash,false);			
		}
	}


	////register onresize event
	$(window).bind("resize", function() {	onResize();  }    );
	var rs = $("body").ezBgResize({center: true}); // enable the resize of video, déclare apres le start de la video pour on bon resize
	 $("body").trigger('resize');
	$("#hautAbout").hide();
	//cache le bt bas dans about si pas besoin
		// if( $("#contentAbout").height() <= $("#aboutContainer").height()){
			// $("#basAbout").hide();
			// $("#hautAbout").hide();
		// }
		
}
function supports_video() {return !!document.createElement('video').canPlayType;} //<-- fallback flash
//////////////////////////////////////////////
	//******DIALOGUE JS & FLASH******//
/////////////////////////////////////////////	
var bolIsPlaying = true; // pour le switch du bouton play
function playControlFlash() {
	//alert(thisMovie("fallback"));
	thisMovie("fallback").playPauseJS();
	if(bolIsPlaying){
		$("#play").css("background-position",'bottom');
	}else{
		$("#play").css("background-position",'top');
	}
	bolIsPlaying = !bolIsPlaying;
}
function playNewVideoFlash(s){
	thisMovie("fallback").playNewVideoJS(s);
}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function updateBarre(wt, wb){
	barrePosition.style.width = wt+"px";
	barrePreload.style.width = ($(window).width()*wb)+"px"; //<-- buffer
}

function jumpToFlash(e){
	var posX;
	if (document.layers||document.getElementById&&!document.all) {
		posX = e.pageX; //if NS
	}else if (document.all) {
		posX = window.event.clientX // if IE
	}
	var perc = posX / $(window).width();
	var totalTime = thisMovie("fallback").getVtime();
	var newTime = perc * totalTime;
	//video.currentTime = newTime;
	
	var currentTime = newTime;
	var percPosition = currentTime/totalTime ;
	var npos = $(window).width() * percPosition;
	barrePosition.style.width = npos+"px";
	
	thisMovie("fallback").gotoTimeFlash(newTime);
}

///////////////////////////////////////.///////
		//******PLAYER HTML5******//
////////////////////////////////////////////// var global a cause du changement de video
var t; // This is for the timer	progressbar
var tb; // Timer for buffer	
var video;//
var tab_fileNameListe;
var tab_position = 1;
//var vp = function(){
function PlayVideo() {
	var play;
	//////////////////////	
	//****progress barre******//
	//////////////////////	
	var barrePosition;
	var barrePreload;
	var totalTime;
	var currentTime;
	var that = this;

	this.setVars = function(){
		video = document.getElementById('video');
		play =  document.getElementById('play');
		barrePosition = document.getElementById('barrePosition');
		barrePreload = document.getElementById('barrePreload');	
		
		// je recupere la listes des file_name
		$.get('php/AJAX_manager.php', {
		file_liste:"rien"},
			function(data){
				tab_fileNameListe = data.split("-|-");
				//video.onended = onFinVideo;
				$('video').bind('ended',onFinVideo);
			});	
			
		// j'ecoute la fin de la video
		function onFinVideo (){
			//console.log(tab_position+" FIN "+long);
			window.clearInterval(t);
			var long = tab_fileNameListe.length-1;
			(tab_position < long)?tab_position++ : tab_position = 1;
			
			changeVideo(tab_position);
	    }		
	}
	
	
	this.setVars();//<-- init les vars de base
	this.startTimeBarre = function () {
		t = window.setInterval(function() {
		if (video.ended != true) {
			currentTime = video.currentTime;
			totalTime = video.duration;
			var percPosition = currentTime/totalTime ;
			var npos = $(window).width() * percPosition;
			barrePosition.style.width = npos+"px";
			//trace ('timer timeBar '+totalTime);
		} else {
			//play.firstChild.nodeValue = 'Play';
			window.clearInterval(t);
		}
		},500);		
	}
	// Function to pause the timeBarre
	this.pauseTimeBarre = function () {	window.clearInterval(t); }
	//////////////////////	
	//*******buffer barre******//
	//////////////////////		
	this.showBuffer = function () {
		tb = window.setInterval(function() {
			barrePreload.style.width = ($(window).width()*bufferedPercent())+"px";
			if(bufferedPercent()>=1){window.clearInterval(tb);}
		},100);	
	}
	this.showBuffer();
  	// Calculates amoutn of buffer is full
	function bufferedPercent(){ return (video.duration) ? video.buffered.end(0) / video.duration : 0; }
	//////////////////////	
	//****PLAY PAUSE****//
	//////////////////////	
	if (play.addEventListener != null){
		play.addEventListener('click',playControl,false);
		video.addEventListener('click',playControl,false);
	} else {
		play.attachEvent("click", playControl);
		video.attachEvent("click", playControl);
	}
	
	function playControl() {
		if (video.paused == false) {
			video.pause();
			that.pauseTimeBarre(); 
			$("#play").css("background-position",'bottom');
		} else {
			video.play();
			that.startTimeBarre(); 
			$("#play").css("background-position",'top');
		}
	}
	playControl(); //<-- autoplay
	
	this.startNewVideo = function(){ 
		//console.log("startNewVideo");
		if (video.removeEventListener != null){
			play.removeEventListener('click',playControl,false);
			video.removeEventListener('click',playControl,false);
		} else {
			play.removeEvent("click", playControl);
			video.removeEvent("click", playControl);
		}	
	
		video = document.getElementById('video');
		play =  document.getElementById('play');
		barrePosition = document.getElementById('barrePosition');
		barrePreload = document.getElementById('barrePreload');	
		video.play(); 
		//console.log("--?--");
		vp.startTimeBarre();
		vp.showBuffer();		
		
		if (play.addEventListener != null){
			play.addEventListener('click',playControl,false);
			video.addEventListener('click',playControl,false);
		} else {
			play.attachEvent("click", playControl);
			video.attachEvent("click", playControl);
		}		
		onResize();
	}
	//////////////////////	
	//****SEEKBAR*******//
	//////////////////////	
	var barreTemoins = document.getElementById('barreTemoins');	
	if (barrePosition.addEventListener != null){
		barrePosition.addEventListener('click',jumpTo,false);	
		barrePreload.addEventListener('click',jumpTo,false);
		barreTemoins.addEventListener('click',jumpTo,false);
	} else {
		barrePosition.attachEvent('click',jumpTo);	
		barrePreload.attachEvent('click',jumpTo);
		barreTemoins.attachEvent('click',jumpTo);
	}

	function jumpTo(e){
		var posX;
		if (document.layers||document.getElementById&&!document.all) {
			posX = e.pageX; //if NS
		}else if (document.all) {
			posX = window.event.clientX // if IE
		}
		var perc = posX / $(window).width();
		var newTime = perc * video.duration;
		video.currentTime = newTime;
		
		var currentTime = video.currentTime;
		var totalTime = video.duration;
		var percPosition = currentTime/totalTime ;
		var npos = $(window).width() * percPosition;
		barrePosition.style.width = npos+"px";
		
	}
	//
	//window.setTimeout("onResize()",500);
	
}//<------ FIN PLAYVID --------->//

////////////////////////////////////////////////////////////	
//					****onResize******					  //
////////////////////////////////////////////////////////////
function onResize()
{
	var video = document.getElementById('video');
	var barrePosition = document.getElementById('barrePosition');
	var barreTemoins = document.getElementById('barreTemoins');	
	var barrePreload = document.getElementById('barrePreload');
	var bufferedPercent = (video.duration) ? video.buffered.end(0) / video.duration : 0;
	
	barreTemoins.style.width = $(window).width()+"px";
	if(bufferedPercent>=1){barrePreload.style.width = $(window).width()+"px";}
	if(video.ended){barrePosition.style.width = $(window).width()+"px";}
	
	//pour le HoverScrollMenuVerticalChelou
	
	var wh = $(window).height(); 
	var fh = $("#uicontainer").height(); 
	var h = wh - fh - $("#barreTemoins").height(); 
	$("#listeVertical")[0].setHeight(h);
	//mv.setHeight(h);

	
	//recalcule de la page about
	var habout = $(window).height() -196;
	$("#aboutContainer").height(habout);
	
	//console.log("resized! " + $(window).width() +" -> "+ $("#video-container").width());
}
////////////////////////////////////////////////////////////	
			//Changement de video//
////////////////////////////////////////////////////////////
var firstChange = true;
function changeVideo(id){
	//console.log("ChangeVideo id-> "+id);
	if(supports_video()){
		// id dans la bdd ne doit pas avoir de trous...
		// je réinit l 'auto incré à chaque ajout
		/*
		$.get('php/AJAX_manager.php', {
		callvideo:id},
		function(data)
		{
			if (data != '0') {  
			 $('#video-container').empty();
			 $('#video-container').append(data); 
			 
			 window.clearInterval(t);		 
			 window.clearInterval(tb);
			 if(supports_video()){
				 vp.startNewVideo();
				 onResize();
				 $("body").ezBgResize({center: true});
			 }
			}else{
				 alert('FAIL de connexion à la BDD');  
			}	 
		})
		*/
		//console.log("supports_video");
		tab_position = id;
		if(Modernizr.video && Modernizr.video.h264) {
			//console.log('.mp4');
			var nav = navigator.appName;
			if( nav == "Microsoft Internet Explorer"){	
				$("source").remove();
				video.src='videos/'+tab_fileNameListe[id]+'.mp4';
			    //$('video').attr('src', 'videos/'+tab_fileNameListe[id]+'.mp4' ).attr('type','video/mp4'); 				
			}else{
				video.src='videos/'+tab_fileNameListe[id]+'.mp4';
			}
		} else if(Modernizr.video && Modernizr.video.webm) {
			//console.log('.webm');			
			video.src='videos/'+tab_fileNameListe[id]+'.webm';
		} else if(Modernizr.video && Modernizr.video.ogg) {
			//console.log('.ogg');			
			video.src='videos/'+tab_fileNameListe[id]+'.ogg';
		}
		//console.log("after Modernizr src->"+video.src);
		vp.startNewVideo();

	}else{
		$.get('php/AJAX_manager.php', {
		file_name:id},
			function(data){
				playNewVideoFlash(data);
			});	
		
	}
	
	$.get('php/AJAX_manager.php', {
	videoname:id},
	   function(data){
		 $('#titre').empty();
		 $('#titre').append(data); 		   
	   });
	$.get('php/AJAX_manager.php', {
	videodesc:id},
	   function(data){
		 $('#desc').empty();
		 $('#desc').append(data); 		   
	   });
	$.get('php/AJAX_manager.php', {
	soustitre:id},
	   function(data){
		 $('#soustitre').empty();
		 $('#soustitre').append(data); 		   
	   });	   
	   
	   

}
////////////////////////////////////////////////////////////	
			//Mouse Move hide show GUI//
////////////////////////////////////////////////////////////
var timerUI;
/**/
var BoolUIOn = false;
var hideMe = true;
function startUITimer() {
	timerUI = window.setInterval(function() {
		hideUI();
		window.clearInterval(timerUI);
	},3000);		
}
function showUI(){
	BoolUIOn = true;
	$("#uicontainer").fadeIn();
}
function hideUI(){
	BoolUIOn = false;
	$("#uicontainer").fadeOut(function (){
			$('#sidebarre').css("right",'-365px');
			$('#bt_top').css('right','0');
	});
}

function getMouseMV(e) {
	//trace ("ml");
	if(BoolUIOn == false){
		showUI();
	}
	window.clearInterval(timerUI);
	if(hideMe)startUITimer();	
}

if (document.addEventListener != null){
	document.addEventListener("mousemove", getMouseMV, false);
} else {
	document.attachEvent("mousemove", getMouseMV);
}


////////////////////////////////////////////////////////////	
			/*** SIDEBARRE OUVERTURE AU CLICK ***/
					/*** ROLLOVER MINI ***/
////////////////////////////////////////////////////////////
function openSideBarre(){
	$('#sidebarre').animate({right:0},{ duration: 500,  queue: false});
	$('#bt_top').animate({right:280+"px"},{ duration: 500,  queue: false});
}
function onMiniOver(a){
	$(a).find(".miniBG").css("background-color","#fff");
	$(a).find(".miniMasque").css("background-image","url(images/bg_mini_pic.png)");
	$(a).find("span").css("display","block");
}
function onMiniOut(a){
	$(a).find(".miniBG").css("background-color","#000");
	$(a).find(".miniMasque").css("background-image","");
	$(a).find("span").css("display","none");
}
////////////////////////////////////////////////////////////	
			/*** About OUVERTURE AU CLICK ***/
////////////////////////////////////////////////////////////
var vol = 0.5;
var timer_sound; 
function openAbout(){
	//hideUI();// cache la GUI
	// je calcule la height du machin - 196px $(window).height(); 
	var habout = $(window).height() -196;
	$("#aboutContainer").height(habout);
	clearInterval(timerUI);//coupe le timer
	if (document.removeEventListener != null){ // flingue le mouseMouse
		document.removeEventListener("mousemove", getMouseMV, false);
	} else {
		document.removeEvent("mousemove", getMouseMV);
	}	
	$("#aboutContainer").fadeIn();
	$("#bt_top").hide();
	
	
	timer_sound = setInterval(fadeOutSound, 50);
}
function aboutEnBas() {
	 $("#aboutContainer").animate({ scrollTop: $("#aboutContainer").prop("scrollHeight") }, 500);
	 $("#basAbout").hide();
};
function aboutEnHaut() {
	 $("#aboutContainer").animate({ scrollTop: 0 }, 500);
	 $("#hautAbout").hide();
};
function closeAbout(){
		$("#bt_top").show();
	$("#aboutContainer").fadeOut();
	if (document.addEventListener != null){
		document.addEventListener("mousemove", getMouseMV, false);
	} else {
		document.attachEvent("mousemove", getMouseMV);
	}	
	timer_sound = setInterval(fadeInSound, 50);
}

function fadeOutSound() {
	if(vol >= 0.1) {
		vol = vol - 0.05;
		//trace (vol);
		video.volume = vol;
	} else {
		clearInterval(timer_sound);
		vol = 0.1;
		video.volume = vol;
	}
	//trace("fadeoutSound")
} 

function fadeInSound() {
	if(vol < 1) {
		vol = vol + 0.05;
		//trace (vol);
		if(vol <= 1)video.volume = vol;
	} else {
		clearInterval(timer_sound);
		vol = 1;
	}
	//trace("fadeinSound")
}

////////////////////////////~~~~~~~BLOCAGE SCROLL BODY~~~~~~////////////////
window.onscroll = scroll;
function scroll(){	window.pageXOffset = 0;}

////////////////////////////~~~~~~~FIN~~~~~~////////////////
/// je cache tous avant le debut du pocess ready
$("#logo").hide();
$(document).ready(whenOnLoad);
//window.onload = whenOnLoad;
