
  var newLogiciel = null;
  var numLogiciel = null;
  

 
window.addEvent('load', function() { 
	if($("totalInscription")){
		ajaxCredit();
	}
	if($("thematiq")){
		themeEffect();
	}



});


function addFriend(membre,id,action){
			if(action!='add' && action!='delete'){
				return false;
			}
			$$(".devenirfan .loader").setStyle("display","block");
			var url = base_url+'formateur/'+membre+'.htm';	
			if(action=='add'){
			 	var donne = {'add': id, 'ajax' :''};
			}
			else{
				var donne = {'delete': id, 'ajax' :''};
			}
			var myAjax = new Ajax(url, {
				method: 'post',
				data: donne,
				onFailure: function() {return false;}
			});
	
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				if(rep.match(/true$/i)){
					$$(".devenirfan .loader").setStyle("display","none");
					if(action=="add"){
						$("devenirfan").innerHTML="Merci !";
					}
					else{
						$("devenirfan").innerHTML="Vous ne le suivez plus";
					}
					$("devenirfan").addEvents({'click': function(){return false;}});
				}
				else{
					$$(".devenirfan .loader").setStyle("display","none");
					$("devenirfan").innerHTML="Une erreur est survenue...";
				}
			});	
			return false;
}


function themeEffect(){
	
	$$("#selec .produit").setStyle("height",45);
	
	$$("#selec .produit").addEvents({
    
    'mouseenter': function(){ 		
        $(this).morph({height:$(this).getElement(".description").offsetHeight+50});
     },
    'mouseleave': function(){ 		
        $(this).morph({height:45});
     }
	});
	
	// Anim Top ventes
	
	$$("#top-ventes .produit").addEvents({
    
    'mouseenter': function(){ 	
		$(this).getElement(".elem").set('morph', {duration:300});
		$(this).getElement(".elem").morph({top:-35});
     },
    'mouseleave': function(){ 		
		$(this).getElement(".elem").morph({top:0});
     }
	});
}

function ajaxCredit(){
	$$(".etape1 a").addEvent('click', function(event){
		var disparition = new Fx.Morph('totalInscription', {duration: 500, transition: Fx.Transitions.Quint.easeOut});
		
		disparition.start({
			'opacity':0
		}).chain(function() {
				$('totalInscription').setStyle("left",-372);
				disparition.start({
					'top':0,
					'opacity': 0.99
				});
		});	
		$$(".signin").morph({opacity: 0.3});
		return false;
		
	});
	$("btn-inscription").addEvent('click', function(event){
			$("ajaxLoading").setStyle("display","block");
			var url = base_url+'credits/inscriptionAjax/';	
			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'username':$('inscription-username').value,'email':$('inscription-email').value,'cgu':$("inscription-cgu").checked},
				onFailure: function() {return false;}
			});
	
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				if(rep=="ok"){
					$("ajaxLoading").setStyle("display","none");
					var disparition = new Fx.Morph('totalInscription', {duration: 500, transition: Fx.Transitions.Quint.easeOut});
					disparition.start({
						'opacity':0
					}).chain(function() {
						$('totalInscription').setStyle("left",-744);
						disparition.start({
							'top':0,
							'opacity': 0.99
						});
					});
				}
				else{
					$("ajaxLoading").setStyle("display","none");
					var tab = rep.split(",");
					$("error-username").innerHTML=tab[0];
					$("error-email").innerHTML=tab[1];
					$("error-cgu").innerHTML=tab[2];
				}
			});	
			
			return false;
			
	});
};
	function ajaxLogin(popup) {
	
			var popup = (popup) ? "-popup" : "";
			var myTransition = new Fx.Transition(Fx.Transitions.Elastic, 3);
			var myFx = $('sign-passwd'+popup).effect('margin-left', {duration: 1400,transition: myTransition.easeOut});

			var myEffects = new Fx.Style('sign-passwd'+popup, 'margin-left', {
				transition: Fx.Transitions.Elastic.easeOut
			});
			
			
			var url = base_url+'ajax/ajax_login/';

			
			/**
			 * The simple way for an Ajax request, use onRequest/onComplete/onFailure
			 * to do add your own Ajax depended code.
			 */
			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'sign-login':$('sign-login'+popup).value,'sign-passwd':$('sign-passwd'+popup).value,'page-uri':$("page-uri").value},
				onFailure: function() {return false;}
			});
			
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				if(rep != "error") {
					if(popup == "") {
						document.location.href=rep;
					} else {popupLegals();}
				} else { 			
					$('sign-passwd'+popup).style.marginLeft = "10px"; myFx.start(0); return false;
				}
			});
					
			return false;
			



	}
	
	
	function popupLegals() {
	
	
			var url = base_url+'screencast/getlegals/';

			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'fiche':$('screencast-id').value,'from':$('screencast-uri').value},
				onFailure: function() {return false;}
			});

			myAjax.request().chain(function() {
				var rep = myAjax.response.text;
				if(rep != "error") {
					$("overlay-box-buy").innerHTML = rep;
				}
			});
			return false;
	}

	function buy() {
			var url = base_url+'screencast/buy/';

			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'fiche':$('screencast-id').value,'from':$('screencast-uri').value},
				onFailure: function() {return false;}
			});
			myAjax.request().chain(function() {
				var rep = myAjax.response.text;
				if(rep != "error") {
					$("overlay-box-buy").innerHTML = rep;
					//downloadLast();
				}
			});
			return false;


	}

	function downloadLast() {	
		var url = base_url+'screencast/getlast/';
		var myAjax = new Ajax(url, {onFailure: function() {return false;}});
		myAjax.request().chain(function() {
			var rep = myAjax.response.text;
			if(rep != "error") {
				window.location = rep; // download
			}});
		}


	function ajoutLogiciel() {
	
			var id = numLogiciel;
	
			new Element('option',{'selected':'selected'}).setHTML($('new-logiciel').value).injectInside($("logiciel"+id));
			new Element('option',{'selected':'selected','value':'u'+$('new-version').value}).setHTML($('new-version').value).injectInside($("version"+id));
			
			var cat = ($('new-categorie').value).split(",");
			cat.each(function(c) {
				new Element('option',{'selected':'selected'}).setHTML(c).injectInside($("categorie"+id));
			});
			
			toggleOverlay("overlay-add-logiciel");
			
			return false;

	
	}

	
	function ajoutVersion(obj) {
	


			var id = obj.value;

			if(id == "Autre : spécifier ...") {

				var z = newLogiciel.selectedIndex;
				$("new-logiciel").value = newLogiciel.options[z].innerHTML; 
				$("new-version").value = "";
				$("new-categorie").value = "";
				//$("new-categorie").className = "";
				
				toggleOverlay("overlay-add-logiciel");
				return false;
			}



	}


	function ajoutCategorie() {
	
		//alert(numLogiciel+" "+newLogiciel);
		
		var z = $("logiciel"+numLogiciel).selectedIndex;
		$("new-logiciel").value = $("logiciel"+numLogiciel).options[z].innerHTML; 

		var z = $("version"+numLogiciel).selectedIndex;
		$("new-version").value = $("version"+numLogiciel).options[z].innerHTML; 
		
		toggleOverlay("overlay-add-logiciel");
		//return false;

	}
	
	
	
	
	function testLogiciel(rep) {
		eval(rep);
		
		if(insertion == true) {
			// feed du menu logiciel
			// fermeture de la popup
			var id = (newLogiciel.id).substr(8,2);
			
			new Element('option',{'selected':'selected'}).setHTML(logiciel).injectInside($("logiciel"+id));
			new Element('option',{'selected':'selected'}).setHTML(version).injectInside($("version"+id));
			
			var cat = categories.split(",");
			cat.each(function(c) {
				new Element('option',{'selected':'selected'}).setHTML(c).injectInside($("categorie"+id));
			});
			
			
		} else {
		
			// fermeture de la popup
		
		}
		
	}

window.addEvent('domready', function() {
	
	if($("form-login")) {
	$("form-login").addEvent("submit",function(e) {
		new Event(e).stop();
		ajaxLogin();
	});
	}

	
	if($("form-login-popup")) {
	$("form-login-popup").addEvent("submit",function(e) {
		new Event(e).stop();
		ajaxLogin("popup");
	});
	}
	
	
	if($("en-direct-blog")) {
		$$('#en-direct-blog li').each(function(el) {    
			var fx = new Fx.Morph(el,{ duration:300, link:'cancel' });  
			el.addEvents({  
					'mouseenter': function() { fx.start({ 'padding-left': 10 }); },  
					'mouseleave': function() { fx.start({ 'padding-left': 0 }); }  
			});  
		}); 
	}


	var scroller = new Fx.Scroll(document.body,{
			duration: 1200,
			transition: Fx.Transitions.Quint.easeInOut
		});
	$('link_to_top').addEvent('click', function(){
		scroller.toTop();
		

		
	});



	if($$(".more-link")) {
		$$('.more-link').each(function(el) {    
			el.addEvents({  
					'click': function() { el.style.display = "none"; el.getNext(".more").style.display="block";}
				});  
			});  
		}





	if($("toggle-promo")) {
		var togglePromo = new Fx.Morph('promo-infos', {duration: 700, transition: Fx.Transitions.Quint.easeOut});
		$("toggle-promo").addEvent("click",function(e) {
			if($("toggle-promo").checked == true) {
				togglePromo.stop();
				togglePromo.start({'height':80});
			} else {
				togglePromo.stop();
				togglePromo.start({'height':0});
			}
		});
	}






	if($("toggle-categories")) {
	
		var menuCatToggle = false;
		var toggleCat = new Fx.Morph('menu-categories', {duration: 300, transition: Fx.Transitions.Quint.easeOut});
		$("toggle-categories").addEvent("click",function(e) {
			e.stop();
			
			if(menuCatToggle == false) {
				toggleCat.stop();
				toggleCat.start({'height':$("liste-categories").offsetHeight});
				menuCatToggle = true;
			} else {
				toggleCat.stop();
				toggleCat.start({'height':20});
				menuCatToggle = false;
			}
		});


		$("wrapper").addEvent("click",function(e) {

			if(menuCatToggle == true) {
				toggleCat.stop();
				toggleCat.start({'height':20});
				menuCatToggle = false;
			}
		});


	}
	
	
	
	

	if($("toggle-parrainage")) {
		var togglePromo = new Fx.Morph('parrainage-infos', {duration: 700, transition: Fx.Transitions.Quint.easeOut});
		$("toggle-parrainage").addEvent("click",function(e) {
			if($("toggle-parrainage").checked == true) {
				togglePromo.stop();
				togglePromo.start({'height':65});
			} else {
				togglePromo.stop();
				togglePromo.start({'height':0});
			}
		});
	}


	if($('toggle-gratuit')) {
		$("toggle-gratuit").addEvent("click",function(e) {
			if($("toggle-gratuit").checked == true) {
			 return confirm("Attention, ce choix est définif. Veuillez confirmer que vous souhaitez rendre ce tutorial gratuit ?");
			}
		});
	}

		if($('formLogiciel')) {
    new FormCheck('formLogiciel', {
			display:{
				scrollToFirst: false
			},
			submitByAjax: true, 
				onAjaxSuccess: function(response) {
					ajoutLogiciel(); 
					//testLogiciel(response);
				}
			});
			
			
		$('formLogiciel').addEvent("submit",function(e) {
			//alert('ok');			
			ajoutLogiciel();
			new Event(e).stop();
			return false;	
		});		
	}





	if($('faqTextes')) {
	var accordionFaqTextes = new Accordion('h4.question', 'div.reponse', {
		opacity: false,
		onActive: function(toggler, element){
			toggler.setStyle('color', '#ff017d');
			element.setStyle('display', 'block');
		},
		onClick: function(toggler, element){
			toggler.setStyle('color', '#ff017d');
		},
	 
		onBackground: function(toggler, element){
			toggler.setStyle('color', '#7a7d8f');
		}
	}, $('faqTextes'));
	}
	
	var url = document.location.href.split("#q");	
	if(url.length > 1) {
		accordionFaqTextes.display(url[1]);
	}
	
	
	if($('btDeleteMessage')) {
	$('btDeleteMessage').addEvent('click', function() {
		if(confirm("T'en est sur ?")) {
			$('formInbox').submit();
		} else {
			return false;	
		}
	});
	}
	
	
	
	/*
	//fini
	
	var myEffects = new Fx.Style('zone-login', 'margin-top', {
		duration: 600,
		transition: Fx.Transitions.Quint.easeOut
	});
*/

		
	var signOpen = false;
	var pageEncours = document.getElementsByTagName("body");
	var pageId = pageEncours[0].id; 

	// si le membre n'est pas enregistrŽ, ben on affiche la barre avec action
	if($('sign-toggler')) {
	$('sign-toggler').addEvent('click', function() {
		signOpen = switchSignToggler(signOpen);
	});
	}
	
		
	
	// si y'a un bouton enregistrer dans la page, on lui colle un evenement.
	if($('sign-edito')) {
	$('sign-edito').addEvent('click', function() {
		signOpen = switchSignToggler(signOpen);
	});
	}

	if($('sign-popup')) {
	$('sign-popup').addEvent('click', function() {
		signOpen = switchSignToggler(signOpen);
	});
	}
	if($$('.sign-popup')) {
	$$('.sign-popup').addEvent('click', function() {
		signOpen = switchSignToggler(signOpen);
	});
	}

	
												 
	var toggleLogbar = new Fx.Morph('zone-login', {duration: 900, transition: Fx.Transitions.Quint.easeOut});
	function switchSignToggler(opened_sign) {
	
			if(opened_sign == false) {
				toggleLogbar.start({'margin-top':180});
				return true;
			} else {
				toggleLogbar.start({'margin-top':0});
				return false;
			}
			
		
	};
	


	/*
	 * ZONE LOGICIELS
	 */

	/*
	//fini
		var myLogEffects = new Fx.Style('zone-logiciels', 'height', {
			duration: 600,
			transition: Fx.Transitions.Quint.easeOut
		});
	
		*/	
		var logicielsOpen = false;
		 
		$('logiciels-toggler').addEvent('mouseover', function(e) {
			if(animLogicielActive == false && !logicielsOpen) {
				logicielsOpen = switchLogicielsToggler(logicielsOpen);
			}
		});



		$$('#menu li').addEvent('mouseenter', function(e) {
			if(logicielsOpen && this.get("class") != "logiciels") {
				logicielsOpen = switchLogicielsToggler(true);
			}
		});

		//fade('in'); 
		$('zone-logiciels').addEvent('mouseleave', function(e) {
			if(animLogicielActive == false) {
				logicielsOpen = switchLogicielsToggler(logicielsOpen);
			}
		});	

		var animLogicielActive = false;
		var toggleMenuEffect = new Fx.Morph('zone-logiciels', {duration: 300, transition: Fx.Transitions.Quint.easeOut});
												 
		function switchLogicielsToggler(opened_logiciels) {
				animLogicielActive = true;		
				if(opened_logiciels == false) {	 
					document.getElementById(pageId).id = "page-logiciels";
					toggleMenuEffect.start({'height': [0,$('menuLogiciels').offsetHeight],'opacity':1}).chain(function() {
						animLogicielActive = false;
					});
					return true;					
				} else {
					document.getElementById("page-logiciels").id = pageId;
					toggleMenuEffect.start({'height': [$('menuLogiciels').offsetHeight,0],'opacity':0}).chain(function() {
						animLogicielActive = false;	
					});
						return false;					
				}		
	
		};
			
		
		
	
	var myTips = new Tips($$('.toolTipMembres'), {
				maxTitleChars: 50,
				offsets: {'x': -10, 'y': -30},	//I like my captions a little long
				/*initialize:function(){
					//this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0) ;
				},*/
				onShow: function(toolTip) {
					this.fx1 = new Fx.Style(this.toolTip, 'opacity', {duration: 200, wait: false}).set(1) ;
					this.fx1.start(1);
				},
				onHide: function(toolTip) {
					this.fx2 = new Fx.Style(this.toolTip, 'opacity', {duration: 0, wait: false}).set(1) ;
					this.fx2.start(0);
				}
			});


	
		var myTips2 = new Tips($$('.toolTipStats'), {
				maxTitleChars: 50,
				offsets: {'x': 20, 'y': 10},	//I like my captions a little long
				/*initialize:function(){
					//this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0) ;
				},*/
				onShow: function(toolTip) {
					this.fx1 = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: 500}).set(0) ;
					this.fx1.start(1);
				},
				onHide: function(toolTip) {
					this.fx2 = new Fx.Style(this.toolTip, 'opacity', {duration: 0, wait: false}).set(1) ;
					this.fx2.start(0);
				}
			});



	
 
		
});


/*
 * GESTION DES <DIVS> A ONGLETS
 */

	window.addEvent('domready', function() {		
	
	

			
		if($$('.tabs').length > 0) MGFX.tabs = new MGFX.Tabs('.tabs','.mootabs_panel',{autoplay:false,transitionDuration:0});
		if($$('.tabsLogiciels').length > 0) MGFX.tabs = new MGFX.Tabs('.tabsLogiciels','.content-tabsLogiciels',{autoplay:false,transitionDuration:0});
		if($$('.tabsContrib').length > 0) MGFX.tabs = new MGFX.Tabs('.tabsContrib','.content-tabsContrib',{autoplay:false,transitionDuration:0});
		if($$('.tabsStat').length > 0) MGFX.tabs = new MGFX.Tabs('.tabsStat','.content-tabsStat',{autoplay:false,transitionDuration:0});
	
	});
	
	function text2pass(obj,defaut) {
		//obj.type = "password";
		toggleFocusValue(obj,defaut);
	}
	function pass2text(obj,defaut){
		if(obj.value == "") {
		//obj.type = "text"; 
		toggleBlurValue(obj,defaut);}
	}
	
	function toggleFocusValue(obj,defaut){
		if(obj.value == defaut) { obj.value="";}
	}
	function toggleBlurValue(obj,defaut){
		if(obj.value == "") {obj.value = defaut;}
	}
	
	function fillSearch(value) {
	
		$("grosChampRecherche").value = value;
		$("formRecherche").submit();
		
	}
	
	
	
	function confirmFriend(id,confirm) {
			
						
			
			

			var fadeEffect = new Fx.Style("n_friendReq", 'opacity', {
				duration: 250,
				transition: Fx.Transitions.Quint.easeOut
			});
			
			var myComEffects = new Fx.Style("f"+id, 'opacity', {
				duration: 400,
				transition: Fx.Transitions.Quint.easeOut
			});
					
			var myComEffects2 = new Fx.Style("f"+id, 'height', {
				duration: 600,
				transition: Fx.Transitions.Expo.easeOut
			});	
			var myComEffects4 = new Fx.Style("f"+id, 'width', {
				duration: 700,
				transition: Fx.Transitions.Expo.easeOut
			});	
			var myComEffects3 = new Fx.Style("f"+id, 'margin', {
				duration: 200,
				transition: Fx.Transitions.Expo.easeOut
			});
			
			
		
			myComEffects.start(0).chain(function() {
				myComEffects2.start(0);
				myComEffects3.start(0).chain(function() {
					myComEffects4.start(0).chain(function() {

							if(confirm) {


							var ficheMembre = $("fiche"+id).innerHTML;
							$("allMyFriends").innerHTML += '<div class="friendReq myFriend" id="fr'+id+'"><div>'+ficheMembre+'</div>'+
		 					"<p class='write'>"
		 +'<a href="" onclick="return false;"><span>&nbsp;</span>envoyer un message</a>'
		 +'</p>'
		 +'<p class="delete">'
		 +'<a href="" onclick="cancelFriend(\''+id+'\',true);return false;"><span>&nbsp;</span>annuler votre amitié</a>'
		 +'</p>'
		 +"</div>";

							++n_myFriend;
							var s = (n_myFriend > 1) ? "s" : "";
							if(n_myFriend > 0) {
							$("n_myFriend").innerHTML = 'Vous avez actuellement <span>'+n_myFriend+'</span> ami'+s+"";
							} else {
							$("n_myFriend").innerHTML = "Vous n'avez plus d'ami pour le moment";
							}

							// AJOUTER //decalCommentaire(id);

								var url = base_url+'ajax/updateFriend/'+id+'/1';
								var myAjax = new Ajax(url, {method: 'get',onFailure: function() {return false;}});
								myAjax.request();							
							
							} else {
							
								// SUPPRIMER //decalCommentaire(id);
						
		
								var url = base_url+'ajax/updateFriend/'+id+'/0';
								var myAjax = new Ajax(url, {method: 'get',onFailure: function() {return false;}});
								myAjax.request();
								
													
							}	

							--n_friendReq;
							var s = (n_friendReq > 1) ? "s" : "";
							if(n_friendReq > 0) {
							$("n_friendReq").innerHTML = 'Vous avez <span>'+n_friendReq+'</span> demande'+s+" d'amitié en attente de validation";
							} else {
							$("n_friendReq").innerHTML = "Vous n'avez plus de demande d'amitié en attente de validation";
							}
						

					});
				});
			});
			
			return false;
	
	}

	function cancelFriend(id) {
			

			var fadeEffect = new Fx.Style("n_myFriend", 'opacity', {duration: 250, transition: Fx.Transitions.Quint.easeOut});
			var myComEffects = new Fx.Style("fr"+id, 'opacity', {duration: 400, transition: Fx.Transitions.Quint.easeOut});
			var myComEffects2 = new Fx.Style("fr"+id, 'height', {duration: 600, transition: Fx.Transitions.Expo.easeOut });	
			var myComEffects4 = new Fx.Style("fr"+id, 'width', {duration: 700, transition: Fx.Transitions.Expo.easeOut});	
			var myComEffects3 = new Fx.Style("fr"+id, 'margin', {duration: 200,	transition: Fx.Transitions.Expo.easeOut});
		
			myComEffects.start(0).chain(function() {
				myComEffects2.start(0);
				myComEffects3.start(0).chain(function() {
					myComEffects4.start(0).chain(function() {

							--n_myFriend;
							var s = (n_myFriend > 1) ? "s" : "";
							if(n_myFriend > 0) {
							$("n_myFriend").innerHTML = 'Vous avez actuellement <span>'+n_myFriend+'</span> ami'+s+"";
							} else {
							$("n_myFriend").innerHTML = "Vous n'avez plus d'ami pour le moment";
							}
	
		
								var url = base_url+'ajax/updateFriend/'+id+'/0';
								var myAjax = new Ajax(url, {method: 'get',onFailure: function() {return false;}});
								myAjax.request();
								


							//alert("ok"); //decalCommentaire(id);
					});
				});
			});
			
			return false;
	
	}
	
		
	function confirmDelete(id) {
		if(confirm("T'en est sur ?")) {
			$('delete').value=id;
			$('formDelete').submit();
		} 
		else {
			return false;
		}
	}







	/*
	 * COMMENTAIRES
	 */

	function deleteCom(id,tuto) {
		
		if(confirm("T'en est sur ?")) {
			masquerCommentaire(id,tuto);
			return false;
		} 
		else {
			return false;
		}
	}
	
	
	
	function confirmAction() {
		
		if(confirm("T'en est sur ?")) {
			return true;
		} 
		else {
			return false;
		}
	}
	
			
	
												 
		function updateComment(id) {
			
			var myComEffects = new Fx.Style("c"+id, 'opacity', {
				duration: 600,
				transition: Fx.Transitions.Quint.easeOut
			});
					
			var myComEffects2 = new Fx.Style("c"+id, 'height', {
				duration: 600,
				transition: Fx.Transitions.Quint.easeOut
			});	
			var myComEffects3 = new Fx.Style("c"+id, 'margin', {
				duration: 600,
				transition: Fx.Transitions.Quint.easeOut
			});
			
			
		
			myComEffects.start(0).chain(function() {				
				myComEffects2.start(0);
				myComEffects3.start(0).chain(function() {
					decalCommentaire(id);
				});
			});
			
			return false;

		}		
			
												 
		function decalCommentaire(id) {

			if($("rep"+id)){
				var myComEffects4 = new Fx.Style("rep"+id, 'marginLeft', {
					duration: 600,
					transition: Fx.Transitions.Quint.easeOut
				});
	
				myComEffects4.start(0);
			}
			return false;
		}		
		
		 
		function masquerCommentaire(id,tuto) {

			var url = base_url+'ajax/updateComment/'+tuto+'/'+id;

			/**
			 * The simple way for an Ajax request, use onRequest/onComplete/onFailure
			 * to do add your own Ajax depended code.
			 */
			var myAjax = new Ajax(url, {
				method: 'get',
				onFailure: function() {return false;}
			});
			
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				if(rep == "true") { updateComment(id);} else { return false;}
			});
					
			return false;
			
	}
	
	
		var repEnCours = null;	
												 
		function switchReponseToggler(reponse) {
		
			var myReponseEffects = new Fx.Style(reponse, 'height', {
			duration: 600,
			transition: Fx.Transitions.Quint.easeOut
			});	
			
		
			if(repEnCours == reponse) {
				myReponseEffects.start(0);
				repEnCours = null;
			} else if(repEnCours == null) {
				myReponseEffects.start(230);
				repEnCours = reponse;
			} else {
				
				var myReponseEffects2 = new Fx.Style(repEnCours, 'height', {
				duration: 600,
				transition: Fx.Transitions.Quint.easeOut
				});		
				myReponseEffects.start(230);			
				myReponseEffects2.start(0);
				repEnCours = reponse;
			}		
		};
		
		

function sendForm(xhr_url,form,div,champs,func){
	if ( window.XMLHttpRequest ) {
		// Objet XmlHttpRequest pour les moteurs GECKO
		xhr_object = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		// Objet XmlHttpRequest pour Internet Explorer
		xhr_object = new ActiveXObject( 'Microsoft.XMLHTTP' );
	} else {
		// Navigateur non-compatible
		alert( 'Votre navigateur ne supporte pas les objets XMLHTTPRequest...' );
		return;
	}
	if(champs!=null){
		xhr_object.open("POST", xhr_url, true);
		xhr_object.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	}else{
		xhr_object.open("GET", xhr_url, true); 
	}
	// On lui donne le pointeur de fonction de retour
	xhr_object.onreadystatechange = function() {
		if (xhr_object. readyState  == 4) {
			document.getElementById(div).innerHTML = xhr_object.responseText;
			if(func!=null) eval(func)();
		}
	} 
	
	//data
	var data = null;
	if(champs!=null && form!=null){
		for(i in champs){
			if(document.forms[form].elements[champs[i]]){
				data +="&"+champs[i]+"="+document.forms[form].elements[champs[i]].value;
			}
		}
	}
	//alert(data);
	 xhr_object.send(data);
}



function toggleOverlay(popupId) {

	var id = (popupId != false) ? popupId : "overlay-box";
	var body = document.getElementsByTagName("body");
	
	$('main-fade').addEvent("click",function() {

			toggleOverlay(id);	
	});		
		
		
	id = (!(id===null)) ? id : "overlay-box";

	if(body[0].className == "") {
		$(id).style.opacity = 0;

		body[0].className = "overlay";
		$(id).style.display = "block";
		
		

		//IE6 - XML prolog problem.
		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		
	
		

		// positionnement vertical;
		$(id).style.top = ((st+(wh/2))-($(id).offsetHeight/2))+"px";
	
		var fx3 = new Fx.Styles($(id), {duration:300, wait:false});
		fx3.start({'opacity' : 1});
			
		var fx4 = new Fx.Styles($(id), {duration:300, wait:false});
		fx4.start({'top' : $(id).offsetTop-5+"px"});
	}
	else {
		$(id).style.visibility = "hidden";
		$(id).style.display = "none";
		body[0].className = "";
	}

}
     
     
     
  function changeCategorie(myChamp,obj) {
 
  
			newLogiciel = obj;
			numLogiciel = myChamp;
			var id = obj.value;
			
			if(id == "ugc") {
				$("new-logiciel").value = "";
				$("new-version").value = "";
				$("new-categorie").value = "";

				toggleOverlay("overlay-add-logiciel");
				return false;
			}

	
			var champC = document.getElementById("categorie"+myChamp);
			var champV = document.getElementById("version"+myChamp);
			var url = base_url+'ajax/updateCategorie/';


			/**
			 * The simple way for an Ajax request, use onRequest/onComplete/onFailure
			 * to do add your own Ajax depended code.
			 */
			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'logiciel':id},
				onFailure: function() {return false;},
				onComplete: function() {
					eval(this.response.text);
					champV.innerHTML = versions;
					champC.innerHTML = categories;
				}
			});
	
			
			myAjax.request().chain(function() {			
				
				var rep = myAjax.response.text;
				//if(rep == "true") { alert(champ.innerHTML); champ.innerHTML = rep;} else { return false;}
			});

					
			return false;
			  
  }   

	var nbLog = 1;
	
	function addLogiciel () {
	
	
	new Element('div').setHTML('<h2><span>*&nbsp; </span> Logiciel</h2><select name="logiciel['+nbLog+']" id="logiciel'+nbLog+'" class="champ" style="width: 420px; padding: 4px; margin-left: 14px;" onchange="changeCategorie(\''+nbLog+'\',this)">'+document.getElementById("logiciel0").innerHTML+'</select><br/><h2 style="margin: 10px 0 5px 100px"><span>*&nbsp; </span> Version</h2><select name="version['+nbLog+']" id="version'+nbLog+'" class="champ" style="width: 320px; padding: 4px; margin-left: 114px;" onchange=""><option>choissez un logiciel...</option></select><h2 style="margin: 10px 0 5px 100px"><span>*&nbsp; </span> Categorie(s)</h2><select id="categorie'+nbLog+'" class="champ" name="categorie['+nbLog+'][]"  style="overflow: hidden; width: 320px; padding: 4px; margin-left: 114px;" multiple size="5"><option>choissez un logiciel...</option></select>').injectAfter($('categorie'+(nbLog-1)));
		
	//$('logiciel0').remove();
	
	nbLog++;
	return false;
	
	}


window.addEvent('domready', function() {

	var form_items = $$('div.fieldbox');
	var bg = '#ff017d';
	var color = '#ffffff';
	
	//loop through each 'fieldbox' div
	form_items.each(function(element, index) {
	
		var theDesc = element.getElement('.field_desc');

		if(theDesc){
	
			var theLabel = element.getElement('label');
			var theInput = element.getElement('input');
			
			//handle the textarea
			if(theInput == null){
				theInput = element.getElement('textarea');	
			}
			//handle the textarea
			if(theInput == null){
				theInput = element.getElement('select');	
				bg = '#eeeeee';
				color = '#5c5c64';
			}		
			//set up animation for description box
			var desc_fx = new Fx.Styles(theDesc, {
						 duration:250, 
						 transition: Fx.Transitions.Quad.easeOut, 
						 wait:false
			});
			
			//set up animation for input/textarea
			var field_fx = new Fx.Styles(theInput, {
						 duration:250, 
						 transition: Fx.Transitions.Quad.easeOut, 
						 wait:false
			});
			
			//hide description box (immediately)
				theDesc.setStyle('opacity',0);	 
	
			
			theInput.addEvents({
				'focus': function(){
					desc_fx.start({
					'opacity': 1
					});
					
					field_fx.start({
					'background-color': bg,
					'color': color
					});
				},
				
				'blur': function(){
					desc_fx.start({
					'opacity': 0
					});
					
					field_fx.start({
					'background-color': '#eeeeee',
					'color': '#5c5c64'
					});
				}
				
			});
			
		}
	
	});

});


//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
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 ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	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;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}




/*!
	mediaboxAdvanced v0.9.0 - The ultimate extension of Mediabox into an all-media script
	(c) 2007-2007 John Einselen <http://iaian7.com>
		based on
	Slimbox v1.64 - The ultimate lightweight Lightbox clone
	(c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/

var Mediabox;

(function() {

	// Global variables, accessible to Mediabox only
	var state = 0, options, images, activeImage, prevImage, nextImage, top, fx, preload, preloadPrev = new Image(), preloadNext = new Image(),
	// State values: 0 (closed or closing), 1 (open and ready), 2+ (open and busy with animation)

	// DOM elements
	overlay, center, image, bottomContainer, bottom, captionSplit, title, caption, prevLink, number, nextLink,
	
	// Mediabox specific vars
	URL, WH, WHL, mediaWidth, mediaHeight, mediaType = "none", mediaSplit, mediaId = "mediaBox";

	/*
		Initialization
	*/

	window.addEvent("domready", function() {
		// Append the Mediabox HTML code at the bottom of the document
		$(document.body).adopt(
			$$([
				overlay = new Element("div", {id: "mbOverlay"}).addEvent("click", close),
				center = new Element("div", {id: "mbCenter"}),
				bottomContainer = new Element("div", {id: "mbBottomContainer"})
			]).setStyle("display", "none")
		);


		bottom = new Element("div", {id: "mbBottom"}).injectInside(center).adopt(
			new Element("a", {id: "mbCloseLink", href: "#"}).addEvent("click", close),
			nextLink = new Element("a", {id: "mbNextLink", href: "#"}).addEvent("click", next),
			prevLink = new Element("a", {id: "mbPrevLink", href: "#"}).addEvent("click", previous),
			title = new Element("div", {id: "mbTitle"}),
			number = new Element("div", {id: "mbNumber"}),
			caption = new Element("div", {id: "mbCaption"}),
			new Element("div", {styles: {clear: "both"}})
		);

		image = new Element("div", {id: "mbImage"}).injectInside(center);

		fx = {
			overlay: new Fx.Tween(overlay, {property: "opacity", duration: 360}).set(0),
			image: new Fx.Tween(image, {property: "opacity", duration: 360, onComplete: nextEffect}),
			bottom: new Fx.Tween(bottom, {property: "margin-top", duration: 240})
		};
	});

	/*
		API
	*/

	Mediabox = {
		open: function(_images, startImage, _options) {
			options = $extend({
				loop: false,					// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
												// Remember that Firefox 2 and Camino on the Mac require a .png file set in the CSS
				resizeDuration: 240,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// Default transition in mootools
				initialWidth: 720,				// Initial width of the box (in pixels)
				initialHeight: 405,				// Initial height of the box (in pixels)
				showCaption: true,				// Display the title and caption, true / false
				animateCaption: false,			// Animate the caption, true / false
				showCounter: false,				// If true, a counter will only be shown if there is more than 1 image to display
				counterText: '  ({x} of {y})',	// Translate or change as you wish
		// Global media options
			scriptaccess: 'true',		// Allow script access to flash files
			fullscreen: 'true',			// Use fullscreen
			fullscreenNum: '1',			// 1 = true
			autoplay: 'true',			// Plays the video as soon as it's opened
			autoplayNum: '1',			// 1 = true
			bgcolor: '#111111',			// Background color, used for both flash and QT media
		// Flash player settings and options
			playerpath: '../js/player.swf',	// Path to the mediaplayer.swf or flvplayer.swf file
			backcolor:  '111111',		// Base color for the controller, color name / hex value (0x000000)
			frontcolor: '999999',		// Text and button color for the controller, color name / hex value (0x000000)
			lightcolor: '000000',		// Rollover color for the controller, color name / hex value (0x000000)
			screencolor: '000000',		// Rollover color for the controller, color name / hex value (0x000000)
			controlbar: 'over',			// bottom, over, none (this setting is ignored when playing audio files)
		// Quicktime options (QT plugin used for partial WMV support as well)
			controller: 'true',			// Show controller, true / false
		// Flickr options
			flInfo: 'true',				// Show title and info at video start
		// Revver options
			revverID: '187866',			// Revver affiliate ID, required for ad revinue sharing
			revverFullscreen: 'true',	// Fullscreen option
			revverBack: '000000',		// Background colour
			revverFront: 'ffffff',		// Foreground colour
			revverGrad: '000000',		// Gradation colour
		// Youtube options
			ytColor1: '000000',			// Outline colour
			ytColor2: '333333',			// Base interface colour (highlight colours stay consistent)
		// Vimeo options
			vmTitle: '1',				// Show video title
			vmByline: '1',				// Show byline
			vmPortrait: '1',			// Show author portrait
			vmColor: 'ffffff'			// Custom controller colours, hex value minus the # sign, defult is 5ca0b5

			}, _options || {});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [[_images,startImage,_options]];
				startImage = 0;
			}

// Fixes Firefox 2 and Camino 1.5 incompatibility with opacity + flash
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
	var ffversion=new Number(RegExp.$1); // capture x.x portion and store as a number
	if (ffversion<3) {
		options.overlayOpacity = 1;
		overlay.className = 'mbOverlayFF';
	}
}
// Fixes IE6 support for transparent PNG
if (Browser.Engine.trident4) {
	options.overlayOpacity = 1;
	overlay.className = 'mbOverlayIE';
}

			images = _images;
			options.loop = options.loop && (images.length > 1);
			position();
			setup(true);
			top = window.getScrollTop() + (window.getHeight() / 15);
			fx.resize = new Fx.Morph(center, $extend({duration: options.resizeDuration, onComplete: nextEffect}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			center.setStyles({top: top, width: options.initialWidth, height: options.initialHeight, marginLeft: -(options.initialWidth/2), display: ""});
			fx.overlay.start(options.overlayOpacity);
			state = 1;
			return changeImage(startImage);
		}
	};

	Element.implement({
		mediabox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).mediabox(_options, linkMapper);

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Mediabox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 3 elements:
					the image URL and the image caption (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		mediabox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title, el.rel];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredLinks = links.filter(linksFilter, this);
				return Mediabox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
			});

			return links;
		}
	});


	/*
		Internal functions
	*/

	function position() {
		overlay.setStyles({top: window.getScrollTop(), height: window.getHeight()});
	}

	function setup(open) {
		["object", window.ie ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._mediabox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._mediabox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		window[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		switch(event.code) {
			case 27:	// Esc
			case 88:	// 'x'
			case 67:	// 'c'
				close();
				break;
			case 37:	// Left arrow
			case 80:	// 'p'
				previous();
				break;	
			case 39:	// Right arrow
			case 78:	// 'n'
				next();
		}
//		Prevent default keyboard action (like navigating inside the page)
//		return false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if ((state == 1) && (imageIndex >= 0)) {
			state = 2;
			image.set('html', '');
//			image.erase('html');
			activeImage = imageIndex;
			prevImage = ((activeImage || !options.loop) ? activeImage : images.length) - 1;
			nextImage = activeImage + 1;
			if (nextImage == images.length) nextImage = options.loop ? 0 : -1;

			$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
			fx.bottom.cancel().set(0);
			fx.image.set(0);
			center.className = "mbLoading";

// MEDIABOX FORMATING
			WH = images[imageIndex][2].match(/[0-9]+/g);
			if (WH) {
				WHL = WH.length;
				mediaWidth = WH[WHL-2]+"px";
				mediaHeight = WH[WHL-1]+"px";
			} else {
				mediaWidth=options.initialWidth;
				mediaWidth=options.initialWidth;
			}
			URL = images[imageIndex][0];
			captionSplit = images[activeImage][1].split('::');
// MEDIA TYPES
// IMAGES
			if (URL.match(/\.gif|\.jpg|\.png/i)) {
				mediaType = 'img';
				preload = new Image();
				preload.onload = nextEffect;
				preload.src = images[imageIndex][0];
// FLV, MP4
			} else if (URL.match(/\.flv|\.mp4/i)) {
				mediaType = 'obj';
//				preload = new Swiff(options.playerpath, {
				preload = new Swiff(''+options.playerpath+'?file='+URL+'&backcolor='+options.backcolor+'&frontcolor='+options.frontcolor+'&lightcolor='+options.lightcolor+'&screencolor='+options.screencolor+'&autostart='+options.autoplay+'&controlbar='+options.controlbar, {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
//					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen, flashvars: 'file='+URL+'&backcolor='+options.backcolor+'&frontcolor='+options.frontcolor+'&lightcolor='+options.lightcolor+'&screencolor='+options.screencolor+'&controlbar='+options.controlbar+'&autostart='+options.autoplay);
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// MP3, AAC
			} else if (URL.match(/\.mp3|\.aac/i)) {
				mediaType = 'obj';
				preload = new Swiff(''+options.playerpath+'?file='+URL+'&backcolor='+options.backcolor+'&frontcolor='+options.frontcolor+'&lightcolor='+options.lightcolor+'&screencolor='+options.screencolor+'&autostart='+options.autoplay, {
//				preload = new Swiff(''+options.playerpath+'?file='+URL+'&autostart='+options.autoplay+'&backcolor='+options.backcolor+'&frontcolor='+options.frontcolor+'&lightcolor='+options.lightcolor, {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// SWF
			} else if (URL.match(/\.swf/i)) {
				mediaType = 'obj';
				preload = new Swiff(URL, {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// SOCIAL SITES
// DailyMotion
			} else if (URL.match(/dailymotion\.com/i)) {
				mediaType = 'obj';
				preload = new Swiff(URL, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Flickr
			} else if (URL.match(/flickr\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://www.flickr.com/apps/video/stewart.swf', {
					id: mediaId,
					classid: 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
					width: mediaWidth,
					height: mediaHeight,
					params: {flashvars: 'photo_id='+mediaId+'&amp;show_info_box='+options.flInfo, wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Google Video
			} else if (URL.match(/google\.com\/videoplay/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://video.google.com/googleplayer.swf?docId='+mediaId+'&autoplay='+options.autoplayNum, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Metacafe
			} else if (URL.match(/metacafe\.com\/watch/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[4];
				preload = new Swiff('http://www.metacafe.com/fplayer/'+mediaId+'/.swf', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// MyspaceTV
			} else if (URL.match(/myspacetv\.com|vids\.myspace\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[2];
				preload = new Swiff('http://lads.myspace.com/videos/vplayer.swf?m='+mediaId+'&v=2&type=video', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Revver
			} else if (URL.match(/revver\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[4];
				preload = new Swiff('http://flash.revver.com/player/1.0/player.swf?mediaId='+mediaId+'&affiliateId='+options.revverID+'&allowFullScreen='+options.revverFullscreen+'&backColor=#'+options.revverBack+'&frontColor=#'+options.revverFront+'&gradColor=#'+options.revverGrad+'&shareUrl=revver', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Seesmic
			} else if (URL.match(/seesmic\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://seesmic.com/Standalone.swf?video='+mediaId, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// YouTube
			} else if (URL.match(/youtube\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://www.youtube.com/v/'+mediaId+'&autoplay='+options.autoplayNum+'&fs='+options.fullscreenNum+'&color1=0x'+options.ytColor1+'&color2=0x'+options.ytColor2, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Veoh
			} else if (URL.match(/veoh\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('videos/');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://www.veoh.com/videodetails2.swf?permalinkId='+mediaId+'&player=videodetailsembedded&videoAutoPlay='+options.AutoplayNum, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Viddler
			} else if (URL.match(/viddler\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[4];
				preload = new Swiff('http://www.viddler.com/player/e5398221/', {
					name: 'viddler_'+mediaId+'_'+mediaSplit[6],
					id: mediaId,
					classid: 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Vimeo
			} else if (URL.match(/vimeo\.com/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[3];
				preload = new Swiff('http://www.vimeo.com/moogaloop.swf?clip_id='+mediaId+'&amp;server=www.vimeo.com&amp;fullscreen='+options.fullscreenNum+'&amp;show_title='+options.vmTitle+'&amp;show_byline='+options.vmByline+'&amp;show_portrait='+options.vmPortrait+'&amp;color='+options.vmColor, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// 12seconds
			} else if (URL.match(/12seconds\.tv/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://embed.12seconds.tv/players/remotePlayer.swf', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {flashvars: 'vid='+mediaId+'', wmode: 'opaque', bgcolor: '#ffffff', allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// CONTENT TYPES
// INLINE
			} else if (URL.match(/\#mb_/i)) {
				mediaType = 'inline';
				URLsplit = URL.split('#');
				preload = $(URLsplit[1]).get('html');
				nextEffect();
// HTML
			} else {
				mediaType = 'url';
				mediaId = "mediaId_"+new Date().getTime();	// Safari will not update iframe content with a static id.
				preload = new Element('iframe', {
					'src': URL,
					'id': mediaId,
					'width': mediaWidth,
					'height': mediaHeight,
					'frameborder': 0
					});
				nextEffect();
			}
		}
		return false;
	}

	function nextEffect() {
		switch (state++) {
			case 2:
				if (mediaType == "img"){
					mediaWidth = preload.width;
					mediaHeight = preload.height;
					image.setStyles({backgroundImage: "url("+URL+")", display: ""});
				} else if (mediaType == "obj") {
					if (Browser.Plugins.Flash.version<8) {
						image.setStyles({backgroundImage: "none", display: ""});
						image.set('html', '<div id="mbError"><b>Error</b><br/>Adobe Flash is either not installed or not up to date,<br/>please visit <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" title="Get Flash" target="_new">Adobe.com</a> to download the free player.</div>');
					} else {
						image.setStyles({backgroundImage: "none", display: ""});
						preload.inject(image);
					}
				} else if (mediaType == "inline") {
					image.setStyles({backgroundImage: "none", display: ""});
					image.set('html', preload);
				} else if (mediaType == "url") {
					image.setStyles({backgroundImage: "none", display: ""});
					preload.inject(image);
				} else {
					alert('this file type is not supported\n'+URL+'\nplease visit iaian7.com/webcode/Mediabox for more information');
				}
				$$(image, bottom).setStyle("width", mediaWidth);
				image.setStyle("height", mediaHeight);
//				$$(image, prevLink, nextLink).setStyle("height", mediaHeight);

				title.set('html', (options.showCaption && (captionSplit.length > 1)) ? captionSplit[0] : images[activeImage][1]);
				caption.set('html', (options.showCaption && (captionSplit.length > 1)) ? captionSplit[1] : "");
				number.set('html', (options.showCounter && (images.length > 1)) ? options.counterText.replace(/{x}/, activeImage + 1).replace(/{y}/, images.length) : "");

				if ((prevImage >= 0) && (images[prevImage][0].match(/\.gif|\.jpg|\.png/i))) preloadPrev.src = images[prevImage][0];
				if ((nextImage >= 0) && (images[nextImage][0].match(/\.gif|\.jpg|\.png/i))) preloadNext.src = images[nextImage][0];

				state++;
			case 3:
				center.className = "";
				fx.resize.start({height: image.offsetHeight, width: image.offsetWidth, marginLeft: -image.offsetWidth/2});
				break;
				state++;
			case 4:
				bottomContainer.setStyles({top: top + center.clientHeight, marginLeft: center.style.marginLeft, visibility: "hidden", display: ""});
				fx.image.start(1);
				break;
			case 5:
				if (prevImage >= 0) prevLink.style.display = "";
				if (nextImage >= 0) nextLink.style.display = "";
				if (options.animateCaption) {
					fx.bottom.set(-bottom.offsetHeight).start(0);
				}
				bottomContainer.style.visibility = "";
				state = 1;
		}
	}

	function close() {
		if (state) {
			state = 0;
			preload.onload = $empty;
			image.set('html', '');
			for (var f in fx) fx[f].cancel();
			$$(center, bottomContainer).setStyle("display", "none");
			fx.overlay.chain(setup).start(0);
		}

		return false;
	}

})();

// AUTOLOAD CODE BLOCK
Mediabox.scanPage = function() {
	var links = $$("a").filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	});
	$$(links).mediabox({/* Put custom options here */}, null, function(el) {
		var rel0 = this.rel.replace(/[[]|]/gi," ");
		var relsize = rel0.split(" ");
		return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
	});
};
window.addEvent("domready", Mediabox.scanPage);

window.addEvent('load', function() {  
    if(pageTracker) {  
        $$('.download').addEvent('click',function() { 
            //pageTracker._trackPageview('/downloads/' + this.get('href').replace('http://')); 
            pageTracker._trackPageview('/downloads/' + this.get('href').replace('http://www.weecast.fr/get/',''));  
        });  
    }  
});  




window.addEvent('load', function() {  


	if($('box6')) {
	//SAMPLE 6 (on "mouseenter" walk)
		var sampleObjectItems =[
			{title:'Détecteur corporel : les textures procédurales en animation', autor:'e-tribArt', prix:'<span>5</span> Crédits', logiciel:'Maya', link:'http://www.weecast.fr/maya/detecteur-corporel-les-textures-procedurales-en-animation,2191.html'},
			{title:'Créer une application Air avec flash CS3', autor:'video2brain', prix:'<span>1</span> Crédit', logiciel:'Air / Flex', link:'http://www.weecast.fr/flex_air/creer-une-application-air-avec-flash-cs3,1639.html'},
			{title:'Tutorom atelier numérique', autor:'VTC', prix:'<span>89</span> Crédits', logiciel:'photoshop', link:'http://www.weecast.fr/photoshop/tutorom-atelier-numerique,2180.html'},
			{title:'L'+"'"+'exportation vidéo', autor:'formationvideo', prix:'<span>4</span> Crédits', logiciel:'premiere', link:'http://www.weecast.fr/premiere/l-exportation-video,707.html'},
			{title:'Le HDR', autor:'artfx', prix:'<span>15</span> Crédits', logiciel:'Stitcher', link:'http://www.weecast.fr/stitcher/le-hdr,747.html'},
		];

		var info6 = $('box6').getNext().set('opacity',1);
		var nS6 = new noobSlide({
			mode: 'vertical',
			box: $('box6'),
			autoPlay: true,
			interval: 5000,
			items: sampleObjectItems,
			size: 212,
			addButtons: {
				previous: $('prev6'),
				play: $('play6'),
				stop: $('stop6'),
				playback: $('playback6'),
				next: $('next6')
			},
			button_event: 'click',
			fxOptions: {
				duration: 1000,
				transition: Fx.Transitions.Back.easeOut,
				wait: false
			},
			onWalk: function(currentItem,currentHandle){
				info6.empty();
				new Element('h4').set('html','<em>tutorial vidéo '+currentItem.logiciel+'</em>"'+currentItem.title+'"').inject(info6);
				new Element('p').set('html','<a class="extrait" href="'+currentItem.link+'"><img src="/images/interface/boutons/bt_voir_extrait.png"></a>').inject(info6);
				new Element('strong').set('html',currentItem.prix).inject(info6);
				new Element('span').set('html',"un tutorial vidéo de<br/>"+currentItem.autor).set("class","auteur").inject(info6);
			}
		});
		//walk to next item
		//nS6.next();
		//nS6.walk(0);
		//$('play6').fireEvent("click");
		}
});  




function deleteTag(obj,idT,idF) {

		var parent = obj.getParent();
		var fx = new Fx.Tween(parent, {property: "opacity", duration: 400});
		var fx2 = new Fx.Tween(parent, {property: "width,padding,margin", duration: 400});




			var url = base_url+'ajax/delete_keyword/';


			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'fiche':idF,'mot':idT},
				onFailure: function() {return false;}
			});
			
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				if(rep != "error") { 					
					fx.start(0).chain(function() {
						parent.morph({padding: 0, margin: 0, height: 0, width: 0});
					}).chain(function() {
						parent.destroy();
					});
				} else { 
					// erreur;
				}
			});
			
			



		
		

}

function addTag() {

	var tags = $('myNewTags').value;
	var tabTags = tags.split(",");
	
	tabTags.each(function(el) {
		//alert(el);



			var url = base_url+'ajax/add_keyword/';


			var myAjax = new Ajax(url, {
				method: 'post',
				data: {'fiche':$('ficheId').value,'mot':el},
				onFailure: function() {return false;}
			});
			
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				
				if(rep != "error") { 					
					var myTag = new Element('li', {'html': el+'<span onclick="deleteTag(this,'+rep+','+$('ficheId').value+')">x</span>',
					'styles': {
							'opacity': '0'
					}});
					$("tagList").grab(myTag);
					var fx = new Fx.Tween(myTag, {property: "opacity", duration: 400});
					fx.start(1);
				} else { 
					// erreur;
				}
			});

			$('myNewTags').value = "";

    
	
	});
	
	
	
		
}


function checkAndSubmit(id,value,form) {

	$(id).checked = "checked";
	$(id).value = value;
	$(form).submit();

}


if ( window.addEventListener ) {
var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
window.addEventListener("keydown", function(e){
kkeys.push( e.keyCode );
if ( kkeys.toString().indexOf( konami ) >= 0 )
window.location = "http://www.weecast.fr";
}, true);
}

window.addEvent('domready', function() {  
      
      
    //store titles and text  
    $$('a.tipz').each(function(element,index) {  
        var content = element.get('title').split('::');  
        element.store('tip:title', content[0]);  
        element.store('tip:text', content[1]);  
    });  
      
    //create the tooltips  
    var tipz = new Tips('.tipz',{  
        className: 'tipz',  
        fixed: false,  
				offsets: {x: -46, y: -56},
        hideDelay: 50,  
        showDelay: 50  
    });  
    
    tipz.addEvents({  
    'show': function(tip) {  
        tip.fade('in');  
    },  
    'hide': function(tip) {  
        tip.fade('out');  
    }  
		});  
      
});  
      

function finExtrait(){
	$("mbCenter").setStyle('display',"none");
	$("mbOverlay").setStyle('display',"none");
	toggleOverlay('overlay-box-buy');
	return false;
}

/* temoignage comptage de caractere */


window.addEvent("domready", function() {
 

	if($("comment0")){
    
    var textArea = $("comment0");
    var maxChars = textArea.get("data-maxChars");
    
    // create a custom focused property so that we only capture keystrokes when it is
    textArea.addEvents({
        focus: function() {
            this.focused = true;
        },
        blur: function() {
            this.focused = false;
        }
    });
    
    // attach a key listener
    window.addEvent("keydown", function(e) {
        if (textArea.focused) {
            // should really compare e.key against alpha numerics and whatever allowed chars we have 
            // so it does not fire when they backspace or delete or use arrow keys to move

            // current count is...
            var chars = textArea.get("value").trim().length;

            // allowed?
            if (chars >= maxChars) {
                // kill keyboard event...
                // e.stop();
                
                // inform them its full!
                $("warning0").set("html", "<strong>Vous avez atteint la limite</strong>");
                
                // remove surplus chars
                textArea.set("value", textArea.get("value").substring(0,maxChars));
            }
            else {
                // reset warning field
                $("warning0").set("html", "");   
            }
            // inform how much left
			var restant=maxChars-chars;
           // $("left").set("text", chars);
			$("left0").set("text", restant);
        }
    });
    
    }
});


window.addEvent("domready", function() {


	if($("comment1")){
    
    var textArea = $("comment1");
    var maxChars = textArea.get("data-maxChars");
    
    // create a custom focused property so that we only capture keystrokes when it is
    textArea.addEvents({
        focus: function() {
            this.focused = true;
        },
        blur: function() {
            this.focused = false;
        }
    });
    
    // attach a key listener
    window.addEvent("keydown", function(e) {
        if (textArea.focused) {
            // should really compare e.key against alpha numerics and whatever allowed chars we have 
            // so it does not fire when they backspace or delete or use arrow keys to move

            // current count is...
            var chars = textArea.get("value").trim().length;

            // allowed?
            if (chars >= maxChars) {
                // kill keyboard event...
                // e.stop();
                
                // inform them its full!
                $("warning1").set("html", "<strong>Vous avez atteint la limite</strong>");
                
                // remove surplus chars
                textArea.set("value", textArea.get("value").substring(0,maxChars));
            }
            else {
                // reset warning field
                $("warning1").set("html", "");   
            }
            // inform how much left
			var restant=maxChars-chars;
           // $("left").set("text", chars);
			$("left1").set("text", restant);
        }
    });
    
    
    }
});




function getPageLogiciel(num){

	var loader = new Element('img', {src: base_url+'images/interface/loader-bleu.gif','class':'loader'});
	$$('.entries')[0].adopt(loader);

	var url = $('more-entries').get('rel')+num;

	var myAjax = new Ajax(url, {
		method: 'get',
		data: {},
		onFailure: function() {return false;}
	});
	
	myAjax.request().chain(function() {			
		var rep = myAjax.response.text;
		var div = new Element('div').setHTML(rep);
		$$('.entries')[0].adopt(div);
		div.setStyle("opacity","0");
		div.morph({opacity: 0.99});
		loader.remove();

		
	});	
			
	return false;
	
};





function getPageTutoFormateur(num){

	var loader = new Element('img', {src: base_url+'images/interface/loader-bleu.gif','class':'loader'});
	$$('.entries')[0].adopt(loader);

	var url = $('more-entries').get('rel')+num;

	var myAjax = new Ajax(url, {
		method: 'get',
		data: {},
		onFailure: function() {return false;}
	});
	
	myAjax.request().chain(function() {			
		var rep = myAjax.response.text;
		var div = new Element('div').setHTML(rep);
		$$('.entries')[0].adopt(div);
		div.setStyle("opacity","0");
		div.morph({opacity: 0.99});
		loader.remove();

		
	});	
			
	return false;
	
};



function getPageGratuit(num){

	var loader = new Element('img', {src: base_url+'images/interface/loader-bleu.gif','class':'loader'});
	$$('.entries')[0].adopt(loader);

	var url = $('more-entries').get('rel')+num;

	var myAjax = new Ajax(url, {
		method: 'get',
		data: {},
		onFailure: function() {return false;}
	});
	
	myAjax.request().chain(function() {			
		var rep = myAjax.response.text;
		var div = new Element('div').setHTML(rep);
		$$('.entries')[0].adopt(div);
		div.setStyle("opacity","0");
		div.morph({opacity: 0.99});
		loader.remove();

		
	});	
			
	return false;
	
};





window.addEvent('load', function() {  
    if($("top-formateurs")) {  
        $$('.navigation span').addEvent('click',function() { 
            var periode = this.get("rel");
            
            
			this.getParent("p").getChildren("span").setProperty("class","");
			this.setProperty("class","actif");
			
			var ul = this.getParent("div").getChildren("ul");
	

			var url = "/formateur/ajax/"+ul.get('rel')+"/"+periode;
		
			var myAjax = new Ajax(url, {
				method: 'get',
				data: {},
				onFailure: function() {return false;}
			});
			
			myAjax.request().chain(function() {			
				var rep = myAjax.response.text;
				ul.setHTML(rep);
			});	
		
        });  
    }  
});  



/**
 * Observer - Observe formelements for changes
 *
 * - Additional code from clientside.cnet.com
 *
 * @version		1.1
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var Observer = new Class({

	Implements: [Options, Events],

	options: {
		periodical: false,
		delay: 1000
	},

	initialize: function(el, onFired, options){
		this.element = $(el) || $$(el);
		this.addEvent('onFired', onFired);
		this.setOptions(options);
		this.bound = this.changed.bind(this);
		this.resume();
	},

	changed: function() {
		var value = this.element.get('value');
		if ($equals(this.value, value)) return;
		this.clear();
		this.value = value;
		this.timeout = this.onFired.delay(this.options.delay, this);
	},

	setValue: function(value) {
		this.value = value;
		this.element.set('value', value);
		return this.clear();
	},

	onFired: function() {
		this.fireEvent('onFired', [this.value, this.element]);
	},

	clear: function() {
		$clear(this.timeout || null);
		return this;
	},

	pause: function(){
		if (this.timer) $clear(this.timer);
		else this.element.removeEvent('keyup', this.bound);
		return this.clear();
	},

	resume: function(){
		this.value = this.element.get('value');
		if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
		else this.element.addEvent('keyup', this.bound);
		return this;
	}

});

var $equals = function(obj1, obj2) {
	return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};/**
 * Autocompleter
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var Autocompleter = new Class({

	Implements: [Options, Events],

	options: {/*
		onOver: $empty,
		onSelect: $empty,
		onSelection: $empty,
		onShow: $empty,
		onHide: $empty,
		onBlur: $empty,
		onFocus: $empty,*/
		minLength: 1,
		markQuery: true,
		width: 'inherit',
		maxChoices: 10,
		injectChoice: null,
		customChoices: null,
		emptyChoices: null,
		visibleChoices: true,
		className: 'autocompleter-choices',
		zIndex: 42,
		delay: 0,
		observerOptions: {},
		fxOptions: {},

		autoSubmit: false,
		overflow: false,
		overflowMargin: 25,
		selectFirst: false,
		filter: null,
		filterCase: false,
		filterSubset: false,
		forceSelect: false,
		selectMode: true,
		choicesMatch: null,

		multiple: false,
		separator: ', ',
		separatorSplit: /\s*[,;]\s*/,
		autoTrim: false,
		allowDupes: false,

		cache: true,
		relative: false
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.build();
		this.observer = new Observer(this.element, this.prefetch.bind(this), $merge({
			'delay': this.options.delay
		}, this.options.observerOptions));
		this.queryValue = null;
		if (this.options.filter) this.filter = this.options.filter.bind(this);
		var mode = this.options.selectMode;
		this.typeAhead = (mode == 'type-ahead');
		this.selectMode = (mode === true) ? 'selection' : mode;
		this.cached = [];
	},

	/**
	 * build - Initialize DOM
	 *
	 * Builds the html structure for choices and appends the events to the element.
	 * Override this function to modify the html generation.
	 */
	build: function() {
		if ($(this.options.customChoices)) {
			this.choices = this.options.customChoices;
		} else {
			this.choices = new Element('ul', {
				'class': this.options.className,
				'styles': {
					'zIndex': this.options.zIndex
				}
			}).inject(document.body);
			this.relative = false;
			if (this.options.relative) {
				this.choices.inject(this.element, 'after');
				this.relative = this.element.getOffsetParent();
			}
			this.fix = new OverlayFix(this.choices);
		}
		if (!this.options.separator.test(this.options.separatorSplit)) {
			this.options.separatorSplit = this.options.separator;
		}
		this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, $merge({
			'property': 'opacity',
			'link': 'cancel',
			'duration': 200
		}, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
		this.element.setProperty('autocomplete', 'off')
			.addEvent((Browser.Engine.trident || Browser.Engine.webkit) ? 'keydown' : 'keypress', this.onCommand.bind(this))
			.addEvent('click', this.onCommand.bind(this, [false]))
			.addEvent('focus', this.toggleFocus.create({bind: this, arguments: true, delay: 100}))
			.addEvent('blur', this.toggleFocus.create({bind: this, arguments: false, delay: 100}));
	},

	destroy: function() {
		if (this.fix) this.fix.destroy();
		this.choices = this.selected = this.choices.destroy();
	},

	toggleFocus: function(state) {
		this.focussed = state;
		if (!state) this.hideChoices(true);
		this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
	},

	onCommand: function(e) {
		if (!e && this.focussed) return this.prefetch();
		if (e && e.key && !e.shift) {
			switch (e.key) {
				case 'enter':
					if (this.element.value != this.opted) return true;
					if (this.selected && this.visible) {
						this.choiceSelect(this.selected);
						return !!(this.options.autoSubmit);
					}
					break;
				case 'up': case 'down':
					if (!this.prefetch() && this.queryValue !== null) {
						var up = (e.key == 'up');
						this.choiceOver((this.selected || this.choices)[
							(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')
						](this.options.choicesMatch), true);
					}
					return false;
				case 'esc': case 'tab':
					this.hideChoices(true);
					break;
			}
		}
		return true;
	},

	setSelection: function(finish) {
		var input = this.selected.inputValue, value = input;
		var start = this.queryValue.length, end = input.length;
		if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
		if (this.options.multiple) {
			var split = this.options.separatorSplit;
			value = this.element.value;
			start += this.queryIndex;
			end += this.queryIndex;
			var old = value.substr(this.queryIndex).split(split, 1)[0];
			value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
			if (finish) {
				var tokens = value.split(this.options.separatorSplit).filter(function(entry) {
					return this.test(entry);
				}, /[^\s,]+/);
				if (!this.options.allowDupes) tokens = [].combine(tokens);
				var sep = this.options.separator;
				value = tokens.join(sep) + sep;
				end = value.length;
			}
		}
		this.observer.setValue(value);
		this.opted = value;
		if (finish || this.selectMode == 'pick') start = end;
		this.element.selectRange(start, end);
		this.fireEvent('onSelection', [this.element, this.selected, value, input]);
	},

	showChoices: function() {
		var match = this.options.choicesMatch, first = this.choices.getFirst(match);
		this.selected = this.selectedValue = null;
		if (this.fix) {
			var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto';
			this.choices.setStyles({
				'left': pos.left,
				'top': pos.bottom,
				'width': (width === true || width == 'inherit') ? pos.width : width
			});
		}
		if (!first) return;
		if (!this.visible) {
			this.visible = true;
			this.choices.setStyle('display', '');
			if (this.fx) this.fx.start(1);
			this.fireEvent('onShow', [this.element, this.choices]);
		}
		if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
		var items = this.choices.getChildren(match), max = this.options.maxChoices;
		var styles = {'overflowY': 'hidden', 'height': ''};
		this.overflown = false;
		if (items.length > max) {
			var item = items[max - 1];
			styles.overflowY = 'scroll';
			styles.height = item.getCoordinates(this.choices).bottom;
			this.overflown = true;
		};
		this.choices.setStyles(styles);
		this.fix.show();
		if (this.options.visibleChoices) {
			var scroll = document.getScroll(),
			size = document.getSize(),
			coords = this.choices.getCoordinates();
			if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x;
			if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y;
			window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top));
		}
	},

	hideChoices: function(clear) {
		if (clear) {
			var value = this.element.value;
			if (this.options.forceSelect) value = this.opted;
			if (this.options.autoTrim) {
				value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator);
			}
			this.observer.setValue(value);
		}
		if (!this.visible) return;
		this.visible = false;
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.observer.clear();
		var hide = function(){
			this.choices.setStyle('display', 'none');
			this.fix.hide();
		}.bind(this);
		if (this.fx) this.fx.start(0).chain(hide);
		else hide();
		this.fireEvent('onHide', [this.element, this.choices]);
	},

	prefetch: function() {
		var value = this.element.value, query = value;
		if (this.options.multiple) {
			var split = this.options.separatorSplit;
			var values = value.split(split);
			var index = this.element.getSelectedRange().start;
			var toIndex = value.substr(0, index).split(split);
			var last = toIndex.length - 1;
			index -= toIndex[last].length;
			query = values[last];
		}
		if (query.length < this.options.minLength) {
			this.hideChoices();
		} else {
			if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
				if (this.visible) return false;
				this.showChoices();
			} else {
				this.queryValue = query;
				this.queryIndex = index;
				if (!this.fetchCached()) this.query();
			}
		}
		return true;
	},

	fetchCached: function() {
		return false;
		if (!this.options.cache
			|| !this.cached
			|| !this.cached.length
			|| this.cached.length >= this.options.maxChoices
			|| this.queryValue) return false;
		this.update(this.filter(this.cached));
		return true;
	},

	update: function(tokens) {
		this.choices.empty();
		this.cached = tokens;
		var type = tokens && $type(tokens);
		if (!type || (type == 'array' && !tokens.length) || (type == 'hash' && !tokens.getLength())) {
			(this.options.emptyChoices || this.hideChoices).call(this);
		} else {
			if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
			tokens.each(this.options.injectChoice || function(token){
			
				var res = token.split('|');
				var s = ((int)res[2] > 1) ? "s" : "";
				var choice = new Element('li', {'html': '<a href="'+res[1]+'">'+this.markQueryValue(res[0])+' <em>'+res[2]+' résultat'+s+'</em></a>'});
				choice.inputValue = res[0];
				this.addChoiceEvents(choice).inject(this.choices);
			}, this);
			this.showChoices();
		}
	},

	choiceOver: function(choice, selection) {
		if (!choice || choice == this.selected) return;
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.selected = choice.addClass('autocompleter-selected');
		this.fireEvent('onSelect', [this.element, this.selected, selection]);
		if (!this.selectMode) this.opted = this.element.value;
		if (!selection) return;
		this.selectedValue = this.selected.inputValue;
		if (this.overflown) {
			var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin,
				top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height;
			if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
			else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
		}
		if (this.selectMode) this.setSelection();
	},

	choiceSelect: function(choice) {
		if (choice) this.choiceOver(choice);
		this.setSelection(true);
		this.queryValue = false;
		this.hideChoices();
	},

	filter: function(tokens) {
		return (tokens || this.tokens).filter(function(token) {
			return this.test(token);
		}, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
	},

	/**
	 * markQueryValue
	 *
	 * Marks the queried word in the given string with <span class="autocompleter-queried">*</span>
	 * Call this i.e. from your custom parseChoices, same for addChoiceEvents
	 *
	 * @param		{String} Text
	 * @return		{String} Text
	 */
	markQueryValue: function(str) {
		return (!this.options.markQuery || !this.queryValue) ? str
			: str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>');
	},

	/**
	 * addChoiceEvents
	 *
	 * Appends the needed event handlers for a choice-entry to the given element.
	 *
	 * @param		{Element} Choice entry
	 * @return		{Element} Choice entry
	 */
	addChoiceEvents: function(el) {
		return el.addEvents({
			'mouseover': this.choiceOver.bind(this, [el]),
			'click': this.choiceSelect.bind(this, [el])
		});
	}
});

var OverlayFix = new Class({

	initialize: function(el) {
		if (Browser.Engine.trident) {
			this.element = $(el);
			this.relative = this.element.getOffsetParent();
			this.fix = new Element('iframe', {
				'frameborder': '0',
				'scrolling': 'no',
				'src': 'javascript:false;',
				'styles': {
					'position': 'absolute',
					'border': 'none',
					'display': 'none',
					'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
				}
			}).inject(this.element, 'after');
		}
	},

	show: function() {
		if (this.fix) {
			var coords = this.element.getCoordinates(this.relative);
			delete coords.right;
			delete coords.bottom;
			this.fix.setStyles($extend(coords, {
				'display': '',
				'zIndex': (this.element.getStyle('zIndex') || 1) - 1
			}));
		}
		return this;
	},

	hide: function() {
		if (this.fix) this.fix.setStyle('display', 'none');
		return this;
	},

	destroy: function() {
		if (this.fix) this.fix = this.fix.destroy();
	}

});

Element.implement({

	getSelectedRange: function() {
		if (!Browser.Engine.trident) return {start: this.selectionStart, end: this.selectionEnd};
		var pos = {start: 0, end: 0};
		var range = this.getDocument().selection.createRange();
		if (!range || range.parentElement() != this) return pos;
		var dup = range.duplicate();
		if (this.type == 'text') {
			pos.start = 0 - dup.moveStart('character', -100000);
			pos.end = pos.start + range.text.length;
		} else {
			var value = this.value;
			var offset = value.length - value.match(/[\n\r]*$/)[0].length;
			dup.moveToElementText(this);
			dup.setEndPoint('StartToEnd', range);
			pos.end = offset - dup.text.length;
			dup.setEndPoint('StartToStart', range);
			pos.start = offset - dup.text.length;
		}
		return pos;
	},

	selectRange: function(start, end) {
		if (Browser.Engine.trident) {
			var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
			start = this.value.substr(0, start).replace(/\r/g, '').length;
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd('character', start + diff);
			range.moveStart('character', start);
			range.select();
		} else {
			this.focus();
			this.setSelectionRange(start, end);
		}
		return this;
	}

});

/* compatibility */

Autocompleter.Base = Autocompleter;/**
 * Autocompleter.Request
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

Autocompleter.Request = new Class({

	Extends: Autocompleter,

	options: {/*
		indicator: null,
		indicatorClass: null,
		onRequest: $empty,
		onComplete: $empty,*/
		postData: {},
		ajaxOptions: {},
		postVar: 'value'

	},

	query: function(){
		var data = $unlink(this.options.postData) || {};
		data[this.options.postVar] = this.queryValue;
		var indicator = $(this.options.indicator);
		if (indicator) indicator.setStyle('display', '');
		var cls = this.options.indicatorClass;
		if (cls) this.element.addClass(cls);
		this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
		this.request.send({'data': data});
	},

	/**
	 * queryResponse - abstract
	 *
	 * Inherated classes have to extend this function and use this.parent()
	 */
	queryResponse: function() {
		var indicator = $(this.options.indicator);
		if (indicator) indicator.setStyle('display', 'none');
		var cls = this.options.indicatorClass;
		if (cls) this.element.removeClass(cls);
		return this.fireEvent('onComplete', [this.element, this.request]);
	}

});

Autocompleter.Request.JSON = new Class({

	Extends: Autocompleter.Request,

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.request = new Request.JSON($merge({
			'url': url,
			'link': 'cancel'
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},

	queryResponse: function(response) {
		this.parent();
		this.update(response);
	}

});

Autocompleter.Request.HTML = new Class({

	Extends: Autocompleter.Request,

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.request = new Request.HTML($merge({
			'url': url,
			'link': 'cancel',
			'update': this.choices
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},

	queryResponse: function(tree, elements) {
		this.parent();
		if (!elements || !elements.length) {
			this.hideChoices();
		} else {
			this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
				var value = choice.innerHTML;
				choice.inputValue = value;
				this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
			}, this);
			this.showChoices();
		}

	}

});

/* compatibility */

Autocompleter.Ajax = {
	Base: Autocompleter.Request,
	Json: Autocompleter.Request.JSON,
	Xhtml: Autocompleter.Request.HTML
};


document.addEvent('domready', function() {

	var inputWord = $('grosChampRecherche');

	// Our instance for the element with id "demo-word"
	new Autocompleter.Request.JSON(inputWord, '/system/plugins/autocomplete/request.php', {
		'indicatorClass': 'autocompleter-loading',
        'postVar': 'search'

	});

});

