/* Principales fonctions JavaScript */

//Raccourci pour getElementById
function get_id(id)
{
	return document.getElementById(id);
}

//Renvoi la position absolue en x d'un élément
function pos_x(obj)
{
	var x=0;
	while (obj!=null)
	{
		x+=obj.offsetLeft-obj.scrollLeft;
		obj=obj.offsetParent;
	}
	return x;
}
//Renvoi la position absolue en y d'un élément
function pos_y(obj)
{
	var y=0;
	while (obj!=null)
	{
		y+=obj.offsetTop-obj.scrollTop;
		obj=obj.offsetParent;
	}
	return y;
}

//Convertit une dae en US ou inversement
function date_us_to_fr(date)
{
	if(date=='0000-00-00' || date.length<10)
		return '';
	return date.substr(8,2)+'-'+date.substr(5,2)+'-'+date.substr(0,4);
}
function date_fr_to_us(date)
{
	if(date=='00-00-0000' || date.length<10)
		return '';
	return date.substr(6,4)+'-'+date.substr(3,2)+'-'+date.substr(0,2);
}
var mth_array=new Array("","Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
var day_array = new Array("Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche");

function date_mois_annee(date,jour,nomjour)
{
	var jour=parseInt(date.substr(0,2));
	var mois=parseInt(date.substr(3,2));
	var annee=parseInt(date.substr(6));
	
	var d = new Date();
	d.setDate(jour);
	d.setMonth(mois-1);
	d.setFullYear(annee); 
	
	if(jour && nomjour)
		return(day_array[d.getDay()]+" "+jour+" "+mth_array[d.getMonth()+1]+" "+annee);
		
	if(jour)
		return(jour+" "+mth_array[d.getMonth()+1]+" "+annee);
		
	return(mth_array[d.getMonth()+1]+" "+annee);
}

//Retourne une date au format francais
function get_date(date)
{
	if(date)
	{
		var jour=date.getDate();
		var mois=date.getMonth()+1;
		if(jour<10)
			jour="0"+jour;
		if(mois<10)
			mois="0"+mois;
		
		return jour+"-"+mois+"-"+date.getFullYear();
	}
	
	var date=new Date();
	var jour=date.getDate();
	var mois=date.getMonth()+1;
	if(jour<10)
		jour="0"+jour;
	if(mois<10)
		mois="0"+mois;
	
	return jour+"-"+mois+"-"+date.getFullYear();
}

//Compare des valeurs dans un tableau
Array.prototype.inArray = function(val) 
{
   for(var i = 0; i < this.length; i++) 
      if(this[i] == val)
		return true;
   return false;
}

// Ajoute la fonction comme méthode de l'objet String
String.prototype.trim = function()
{ return this.replace(/(^\s*)|(\s*$)/g, ""); }
//Traite la chaine en fonction des caractères spéciaux présents
function rem_spec(str)
{
	var chaine=str.trim();
	chaine=chaine.replace(/\s\s+/, ' ');
	chaine=chaine.replace(/\n\s+/, ' ');
	//chaine=chaine.replace('\\', '\\\\');
	
	return chaine;
}
//Equivalent de la fonction PHP
function nl2br(str) 
{
	return str.replace(/\n/g,"<br/>");
}
//Equivalent de la fonction PHP
function htmlspecialchars(ch) 
{
	if(!ch)
		return '';
   ch = ch.replace(/&/g,"&amp;");
   ch = ch.replace(/\"/g,"&quot;");
   ch = ch.replace(/\'/g,"&#039;");
   ch = ch.replace(/</g,"&lt;");
   ch = ch.replace(/>/g,"&gt;");
   return ch;
}
//Equivalent de la fonction PHP
function htmlspecialchars_d(ch) 
{
   ch = ch.replace(/&lt;/g, '<');
   ch = ch.replace(/&gt;/g, '>');
   ch = ch.replace(/&quot;/g, '"');
   ch = ch.replace(/&#039;/g, '\'');
   ch = ch.replace(/&amp;/g, '&');
   return ch;
}
function stripslashes(ch) 
{
   return ch.replace(/(\\)([\\\'\"])/g,"$2")
}



//Renvoie le code touche en fonction du navigateur
function code_touche(evenement)
{
	for (prop in evenement)
	{
		if(prop == 'which') return(evenement.which);
	}
	return(evenement.keyCode);
}

//Affichage d'une boite modale de confirmation
function ouvre_boite(titre,mess,time,width,height)
{
	//masque_select(true);
	var div;
	if(!get_id("create_modal"))
	{
		div=document.createElement("DIV");
		document.body.appendChild(div);
	}
	else
		div=get_id("create_modal");
		
	div.id=div.className="create_modal";
	div.style.display='block';
	
	if(!get_id("modal"))
	{
		div=document.createElement("DIV");
		document.body.appendChild(div);
	}
	else
		div=get_id("modal");
		
	div.id=div.className="modal";
	div.style.display='block';
	div.innerHTML='<p class="modal_titre">'+titre+'</p><div class="mess_modal">'+mess+'</div><div><input type="button" class="bouton" id="modal_fermer" value="Fermer" onclick="ferme_boite();"/></div>';
	if(width && height && navigator.userAgent.indexOf("MSIE 6") != -1 )
	{
		masque_select(true);
		div.style.width=width+"px";
		div.style.height=height+"px";
		div.style.left=(parseInt(width/2))+"px";
		div.style.top="50px";
	}
	else if(width && height)
	{
		div.style.width=width+"px";
		div.style.marginLeft="-"+(parseInt(width/2))+"px";
		div.style.height=height+"px";
		div.style.marginTop="-"+(parseInt(height/2))+"px";
		div.style.top="50%";
	}
		
	if(time!=0)
		setTimeout("ferme_boite();",time);
}
//Suppression de la boite modale de confirmation
function ferme_boite()
{
	get_id("create_modal").style.display="none";
	get_id("modal").style.display="none";
	if(navigator.userAgent.indexOf("MSIE 6") != -1)
		masque_select(false);
	//window.location.replace(adresse);
}


//Initialisation des onglets
function init_onglets()
{
	var ul=get_id("onglets");
	var compt=0;
	var tab_href=new Array();
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) 
	{
		var itm = ul.childNodes[itemi];	//Récupère les LI
		if (itm.nodeName == "LI")	//Attribution des événements aux li
		{
			compt++;
			itm.val=compt;
			itm.onclick=function() { clic_onglet(this.val); }
			if(compt>1)	//Cache tous les divs sauf le premier
				get_id("onglet_div"+compt).style.display="none";
				
			var href=itm.childNodes[0].id;
			tab_href.push(href.substring(1));
		}
	}
	
	var url=window.location.href;
	url=url.substring(url.indexOf('#')+1);
	
	for(var i=1;i!=tab_href.length;i++)
		if(tab_href[i]==url)
		{
			clic_onglet(i+1);
			break;
		}
}

//Affiche le div correspondant à l'onglet cliqué 
var onglet_cur=1;
function clic_onglet(onglet)
{
	get_id("onglet"+onglet_cur).className="";
	get_id("onglet"+onglet).className="onglet_actif";
	get_id("onglet_div"+onglet_cur).style.display="none";
	get_id("onglet_div"+onglet).style.display="block";
	onglet_cur=onglet;
	
	window.location.href=window.location.href.substring(0,window.location.href.indexOf('#'))+"#"+get_id("onglet"+onglet).childNodes[0].id.substring(1);
}


//Envoi d'une requete grâce à AJAX
function call_ajax(fichier, param, func, obj, text)
{
	//Utilisation d'AJAX pour se connecter à la BDD
	var xhr_object = null;   
	
	if(window.XMLHttpRequest) // Firefox   
	   xhr_object = new XMLHttpRequest();   
	else if(window.ActiveXObject) // Internet Explorer   
	   xhr_object = new ActiveXObject("Microsoft.XMLHTTP");   
	else  // XMLHttpRequest non supporté par le navigateur   
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest.\nCertaines fonctionnalités JavaScript ne seront pas accessibles.");  
		
	//Connection au fichier comportant la requete
	xhr_object.open("POST", fichier+"?aleat="+Number(new Date()) , true); 
	
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
	//xhr_object.setRequestHeader("Content-type", "text/xml"); 
	if(param)
		xhr_object.setRequestHeader("Content-length", param.length);
	xhr_object.setRequestHeader("Connection", "close");

	xhr_object.onreadystatechange = function() 
	{ 
		if(xhr_object.readyState == 4) 
		{
			if(xhr_object.status==200)
			{
				if(text)
					var ret=xhr_object.responseText;
				else
					var ret=xhr_object.responseXML;
				eval(func);
			}
			else
			{
				alert("Erreur: "+xhr_object.status);
				eval(func);
			}
		}
	} 
	
	xhr_object.send(param);
}



/*---------------------------------------------------*/
/*---------Affichage d'infos supplémentaires---------*/
/*---------------------------------------------------*/

//Initialise les divs à cacher
function init_info_plus(actu)
{
	var divs = document.getElementsByTagName('DIV');
	var divCounter = 1;
	for(var nb=0;nb<divs.length;nb++)	//Cherche tous les divs à cacher
		if(divs[nb].className=='info_cache')
		{
			divs[nb].id = 'info_cache'+divCounter;	
			var contentDiv = divs[nb].getElementsByTagName('DIV')[0];	//Le div conteneur
			contentDiv.style.top = 0 - contentDiv.offsetHeight + 'px'; 	
			contentDiv.className='info_cache_content';
			contentDiv.id = 'info_cache_content'+divCounter;
			divs[nb].style.display='none';
			divs[nb].style.height='1px';
			
			if(actu)
			{
				var bout = divs[nb].previousSibling;	//Cherche le titre de l'actu
				while(bout && bout.tagName!='SPAN')
					bout = bout.previousSibling;
				bout.onclick = show_hide_info;
				bout.onmouseover=function () { this.style.borderBottom='#BB2222 solid 1px'; }
				bout.onmouseout=function () { this.style.borderBottom='0px'; }
				bout.id = 'info_plus'+divCounter;
			}
			else
			{
				var bout = divs[nb].nextSibling;	//Cherche le bouton 'plus d'infos'
				while(bout && bout.tagName!='P')
					bout = bout.nextSibling;
				bout=bout.getElementsByTagName('I')[0];
				bout.onclick = show_hide_info;
				bout.onmouseover=function () { this.style.borderBottom='#BB2222 solid 1px'; }
				bout.onmouseout=function () { this.style.borderBottom='0px'; }
				bout.id = 'info_plus'+divCounter;
			}
			
			divCounter++;
		}	
}

var slideSpeed = 10;
var timer = 10;
var objectIdToSlideDown = false;
var activeId = false;
var slideInProgress = false;
var inner_plus='<img src="img/plus.gif" alt="plus"/>Plus d\'infos...';

//Affiche / enlève les infos
function show_hide_info(e,inputId)
{
	if(slideInProgress)
		return;
	slideInProgress=true;
	if(!inputId)
		inputId=this.id;
	inputId=inputId+'';
	//Récupère le numéro
	var numericId = inputId.replace(/[^0-9]/g,'');
	var info_div = document.getElementById('info_cache'+numericId);

	objectIdToSlideDown = false;
	
	if(!info_div.style.display || info_div.style.display=='none')
	{		
		//Si activé, réduit une info lorsqu'on en affiche une autre
		if(this.tagName=="SPAN" && activeId &&  activeId!=numericId)
		{
			objectIdToSlideDown = numericId;
			slideContent(activeId,(slideSpeed*-1));
		}
		else
		{	
			info_div.style.display='block';
			info_div.style.visibility='visible';
			
			slideContent(numericId,slideSpeed);
		}
		if(this.tagName!="SPAN")
		{
			inner_plus=this.innerHTML;
			this.innerHTML='<img src="img/moins.gif" alt="moins"/>Réduire';
		}
	}
	else
	{	
		slideContent(numericId,(slideSpeed*-1));
		activeId = false;
		if(this.tagName!="SPAN")
			this.innerHTML=inner_plus;
	}	
	if(this.style)
		this.style.borderBottom='0px';
}

function slideContent(inputId,direction)
{
	var obj =document.getElementById('info_cache'+inputId);
	var contentObj = document.getElementById('info_cache_content'+inputId);
	height = obj.clientHeight;
	if(height==0)
		height = obj.offsetHeight;
	height = height+direction;
	rerunFunction = true;
	if(height>contentObj.offsetHeight)
	{
		height = contentObj.offsetHeight;
		rerunFunction = false;
	}
	if(height<=1)
	{
		height = 1;
		rerunFunction = false;
	}

	obj.style.height = height+'px';
	var topPos = height - contentObj.offsetHeight;
	if(topPos>0)
		topPos=0;
	contentObj.style.top = topPos+'px';
	if(rerunFunction)
		setTimeout('slideContent(' + inputId + ',' + direction + ')',timer);
	else
	{
		if(height<=1)
		{	
			obj.style.display='none'; 
			if(objectIdToSlideDown && objectIdToSlideDown!=inputId)
			{
				document.getElementById('info_cache' + objectIdToSlideDown).style.display='block';
				document.getElementById('info_cache' + objectIdToSlideDown).style.visibility='visible';
				slideContent(objectIdToSlideDown,slideSpeed);				
			}
			else
				slideInProgress = false;
		}
		else
		{	
			activeId = inputId;
			slideInProgress = false;
		}
	}
}

/*---------------------------------------------------*/




/*---------------------------------------------------*/
/*---------------Affichage d'infobulles--------------*/
/*---------------------------------------------------*/

var vis_bulle=false; //Visibilité de la bulle
var vis_bulle_static=false; //Visibilité de la bulle statique
var id_bulle;

//Créé l'infobulle
function init_bulle()
{
	id_bulle=document.createElement("DIV");
	id_bulle.id="info";
	id_bulle.className="infobulle";
	document.body.appendChild(id_bulle);
}

//Déplace la bulle en fonction de la souris
//Bugue si on 'scrolle'
function move(e) 
{
	if(vis_bulle) 
	{
		if (navigator.appName!="Microsoft Internet Explorer") 
		{
			id_bulle.style.left=e.pageX + 0+"px";
			id_bulle.style.top=e.pageY + 21+"px";
		}
		else 
		{
			if(document.documentElement.clientWidth>0) 
			{
				var y=19+event.y+document.documentElement.scrollTop;
				id_bulle.style.left=-2+event.x+document.documentElement.scrollLeft+"px";
				id_bulle.style.top=y+"px";
			}
			else 
			{
				var y=19+event.y+document.body.scrollTop;
				id_bulle.style.left=-2+event.x+document.body.scrollLeft+"px";
				id_bulle.style.top=y+"px";
			}
		}
	}
}


//Apparition de la bulle
function show(text, zindex) 
{
	hide_static();

	if(vis_bulle==false) 
	{
		if(zindex)
			id_bulle.style.zIndex=zindex;
		else
			id_bulle.style.zIndex="";
		id_bulle.style.display="block";
		id_bulle.innerHTML = text;
		vis_bulle=true;
	}
}

var timer;

//Apparition de la bulle statique
function show_static(text, x, y, hide, zindex)
{
	clearTimeout(timer);
	if(vis_bulle==false) 
	{
		id_bulle.style.display="block";
		id_bulle.innerHTML = text;
		id_bulle.style.left=x+"px";
		id_bulle.style.top=y+"px";
		if(zindex)
			id_bulle.style.zIndex=zindex;
		else
			id_bulle.style.zIndex="";
		vis_bulle_static=true;
		if(!hide)
			timer=setTimeout("hide_static();",2000);
	}	
}

//Disparition de la bulle
function hide() 
{
	if(vis_bulle==true) 
	{
		id_bulle.style.display="none";
		vis_bulle=false;
	}
}

//Disparition de la bulle statique
function hide_static() 
{
	if(vis_bulle_static==true) 
	{
		id_bulle.style.display="none";
		vis_bulle_static=false;
	}
}

document.onmousemove=move;

/*---------------------------------------------------*/

/*---------------------------------------------------*/
/*---------Upload de fichiers dynamiquement----------*/
/*---------------------------------------------------*/

//Déclaration de la classe
FileUpload = function(_form, _func)
{
	this.form=_form;
	this.func=_func;
	this.name="";
}

FileUpload.prototype.submit=function()
{
	this.set_frame();
	this.set_form();
	if (this.func && typeof(this.func.onStart) == 'function')
		return this.func.onStart();
	else
		return true;
}

FileUpload.prototype.set_frame=function()
{
	this.name='f' + Math.floor(Math.random() * 99999);
	var d = document.createElement('DIV');
	d.innerHTML = '<iframe style="display:none;" src="about:blank" id="'+this.name+'" name="'+this.name+'"></iframe>';
	document.body.appendChild(d);

	var i = document.getElementById(this.name);
	var point=this;
	
	if(window.attachEvent)
		i.attachEvent("onload", function() {point.loaded();});
	else
		i.onload=function() {point.loaded();};
		
	if (this.func && typeof(this.func.onComplete) == 'function')
		i.onComplete = this.func.onComplete;
}

FileUpload.prototype.set_form=function()
{
	this.form.setAttribute('target', this.name);
}

FileUpload.prototype.loaded=function()
{
	var i = document.getElementById(this.name);
	if (i.contentDocument)
		var d = i.contentDocument;
	else if (i.contentWindow)
		var d = i.contentWindow.document;
	else
		var d = window.frames[this.name].document;
		
	if (typeof(i.onComplete) == 'function')
	{
		i.onComplete(d.body.innerHTML);
	}
		
	this.form.setAttribute('target', '');
}

/*---------------------------------------------------*/

/*---------------------------------------------------*/
/*---------Auto-complétion d'un champ texte----------*/
/*---------------------------------------------------*/

//Déclaration de la classe
AutoComp = function(_chp, _func, _func2, _table)
{
	//Pointeur sur la classe
	var point=this;
	//Stocke le focus sur le select
	this.foc=false;
	//Stocke le dernier index séletionné
	this.sel_index=-1;
	//Fonction à appeler lors de la sélection d'une entrée
	this.func=_func;
	//Fonction 2
	this.func2=_func2;
	//Table de la requete
	this.table=_table;
	
	//Champ texte associé
	this.chp=get_id(_chp);
		
	//Création du div d'auto-complétion
	this.div_comp=document.createElement("DIV");
	this.div_comp.className="complete";
	this.div_comp.id=_chp+"_comp";
	var y=pos_y(this.chp)+this.chp.clientHeight+1;
	this.div_comp.style.left=pos_x(this.chp)+'px';
	this.div_comp.style.top=y+'px';
	document.body.appendChild(this.div_comp);
	
	//Création du select associé
	this.sel_comp=document.createElement("SELECT");
	this.sel_comp.className="sel_auto";
	this.sel_comp.id=_chp+"_sel";
	this.sel_comp.size=5;
	this.sel_comp.onclick=function() { point.set_value(); }
	this.sel_comp.onkeyup=function(event) { return point.event_comp(event?event:window.event); }
	this.sel_comp.onblur=function() { point.div_comp.style.display='none'; verif_vide(point.chp); point.foc=false; }
	this.sel_comp.onfocus=function() { point.foc=true; }
	this.div_comp.appendChild(this.sel_comp);
	
	this.chp.onblur=function() { setTimeout(function() { point.lost_focus(); verif_vide_ac(point.chp,point.div_comp); },50); }
	this.chp.onkeydown=function(event) { return point.key_down(event?event:window.event); }
	this.chp.ondblclick=function() { point.aff_div(false); }
	this.chp.onkeyup=function(event) { point.auto_complete(event?event:window.event); }
	
	call_ajax("php/requete_ajax_auto_comp.php", "table="+_table+"&val=", "obj.set_tab(ret);", this);
}

//Remplit le select
AutoComp.prototype.set_tab=function(ajax)
{
	if(!ajax || ajax.length<1)
		return;
		
	var items = ajax.getElementsByTagName("xml_enrg");
	
	//Vide le champ select
	while (this.sel_comp.options.length>0)
		this.sel_comp.options[0]=null;
		
	for (i=0,j=0;i<items.length;i+=2,j++)
		if(items.item(i).firstChild)
		{
			var itm2;
			if(!items.item(i+1) || !items.item(i+1).firstChild)
				itm2="";
			else
				itm2=items.item(i+1).firstChild.nodeValue;
			this.sel_comp.options[j] = new Option(nl2br(/*htmlspecialchars_d*/(items.item(i).firstChild.nodeValue)), itm2);
		}
	
	this.set_sel_size();
}

//Modifie la taille du select en fonction de son contenu
AutoComp.prototype.set_sel_size=function()
{
	var size=this.sel_comp.options.length;
	
	if(size>5)
	{
		this.sel_comp.size=5;
		this.sel_comp.style.height="auto";
		this.sel_comp.style.width="158px";
	}
	else if(size<2)
	{
		this.sel_comp.size=2;
		if (navigator.appName=="Microsoft Internet Explorer")
			this.sel_comp.style.height="25px";
		else
			this.sel_comp.style.height="17px";
		this.sel_comp.style.height="22px";
		this.sel_comp.style.width="158px";
	}
	else
	{
		this.sel_comp.size=size;
		this.sel_comp.style.height="auto";
		if(size==2)
			this.sel_comp.style.width="158px";
		else
			this.sel_comp.style.width="175px";
	}
}

//Affiche le div
AutoComp.prototype.aff_div=function(foc)
{
	var y=pos_y(this.chp)+this.chp.clientHeight+1;
	this.div_comp.style.left=pos_x(this.chp)+'px';
	this.div_comp.style.top=y+'px';
	
	if(this.sel_comp.options.length<1)
		return;
	this.div_comp.style.display="block";
	if(foc)
	{
		this.sel_comp.focus();
		//this.foc=true;
	}
	this.sel_index=this.sel_comp.selectedIndex=0;
}

//Actualise le select en fonction des lettres tapées
AutoComp.prototype.auto_complete=function(evt)
{
	var key_pressed=code_touche(evt);
	
	//Si appui sur la touche DOWN, ou PAGEDOWN
	if(key_pressed==40 || key_pressed==34)
	{
		this.aff_div(true);
		return;
	}
	
	//var ev='obj.set_tab(ret,obj); if(obj.sel_comp.options.length>0)  { obj.sel_index=obj.sel_comp.selectedIndex=0; obj.div_comp.style.display="block"; obj.sel_comp.focus(); } else obj.div_comp.style.display="none";';
	var ev='obj.set_tab(ret,obj); if(obj.sel_comp.options.length>0)  { obj.aff_div(false); } else obj.div_comp.style.display="none";  obj.verif_direct();';
	
	call_ajax("php/requete_ajax_auto_comp.php", "table="+this.table+"&val="+encodeURIComponent(this.chp.value), ev, this);
}

AutoComp.prototype.verif_direct=function()
{
	var bool=false;
	for(var i=0;i!=this.sel_comp.options.length;i++)
		if(this.chp.value==this.sel_comp.options[i].text)
		{
			if(this.func)
				this.func();
			bool=true;
			break;
		}
	if(!bool && this.func2)
		this.func2();
}

//Interception d'une touche dans le champ auto-complete
AutoComp.prototype.event_comp=function(evt)
{
	var key_pressed=code_touche(evt);

	//Si l'on est en début de liste et appui sur UP ou PAGEUP
	if((key_pressed==38 || key_pressed==33) && this.sel_index==0)
	{
		this.div_comp.style.display="none";
		this.chp.focus();
	}
	//Touche Entrée
	else if(key_pressed==13 || key_pressed==32)
	{
		this.set_value();
		return false;
	}
	this.sel_index=this.sel_comp.selectedIndex;
	
	return true;
}

//Assigne la valeur au champ texte
AutoComp.prototype.set_value=function()
{
	if(this.sel_comp.selectedIndex<0)
		return;
	this.chp.value=this.sel_comp.options[this.sel_comp.selectedIndex].text;
	this.div_comp.style.display="none";
	if(this.func)
		this.func();
	this.chp.focus();
}

//Perte du focus sur le div
AutoComp.prototype.lost_focus=function()
{
	if(!this.foc)
		this.div_comp.style.display="none";
	//else
		//this.foc=false;
}

//Intercepte l'appui sur 'Entrée' dans le champ texte
AutoComp.prototype.key_down=function(evt)
{
	if(code_touche(evt)==13)
	{
		this.set_value();
		return false;
	}
	return true;
}

