<!--
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function send2panier(adresse) {
anim_visible("animation","elements/panier_animation.gif",500);
send2php(adresse);
}

function send2rss(adresse) { 

//alert(adresse);

anim_visible("animation","elements/rss_animation.gif",600);
send2php(adresse);
}


function send2php(adresse, confirmation_retour)	{
//	alert(adresse);

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("Désolé, votre navigateur ne supporte pas les objets XMLHTTPRequest...");
   return(false);   
 }  
xhr_object.open("GET", adresse, true);  
xhr_object.send(null); 
xhr_object.onreadystatechange = function() {   
    if(xhr_object.readyState == 4) {
    	if (confirmation_retour) {   		  		
			var pos_ok = xhr_object.responseText.search(/ok/);
			if (pos_ok !=-1) {		  		
			//if (xhr_object.responseText.substring(0,2)=='ok') {
						location.reload();
						//alert('Enregistrement effectué');
					} else {
						alert("Un problème à été rencontré avec le serveur\ndurant l\'enregistrement des données.\nVeuillez retenter l\'enregistrement dans quelque secondes SVP.");
						alert(xhr_object.responseText);	
					}				
		}
	}  
 } 
}

function anim_visible(div_anim_id, anim_filename, timer ) {
	anim = new Image;
	anim.src = anim_filename;
	coord_x = (Math.min(winDim().w,850)-anim.width)/2;		
	document.getElementById('img_'+div_anim_id).setAttribute("src", anim_filename);
	coord_y = ((winDim().h-anim.height)/2+document.documentElement.scrollTop);
	document.getElementById(div_anim_id).style.top = coord_y +"px";
	document.getElementById(div_anim_id).style.left =  coord_x+"px";
	document.getElementById(div_anim_id).style.visibility = "visible";
	if (timer>0) {	
		deactiv_anim = setTimeout("anim_cachee('"+div_anim_id+"')",timer);
	}
}

function anim_cachee(div_anim_id) 	{
		document.getElementById(div_anim_id).style.visibility = "hidden";
}

function eval_js( url ){ 	
	//alert('evaluation javascript');
 	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..."); 
     return; 
	} 
	 
	xhr_object.open("GET", url, true);
	xhr_object.onreadystatechange = function() { 
	   if(xhr_object.readyState == 4) {
			//alert(xhr_object.responseText); // DEBUG MODE
			//document.write(xhr_object.responseText);
			eval(xhr_object.responseText);  // execution du code
		 }
	} 
	 
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	var data = null;  //
	xhr_object.send(data);

     }



function o_switch_class(ancienne_classe, nouvelle_classe) {
//	var formulaire = document.form1.elements;
var formulaire = document.form1;
	for (var champ=0; champ < formulaire.elements.length; champ++) {
		if (formulaire.elements[champ].className==ancienne_classe) {
			formulaire.elements[champ].className=nouvelle_classe;		
		}
	}
}

function action_record(num_action){	
	var xhr_object = null;
	var data = null;
	var formulaire = document.form1;
	if(window.XMLHttpRequest) //pour Firefox
		xhr_object = new XMLHttpRequest();
	else if(window.ActiveXObject) //Internet Explorer
		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
	else{
		alert("Désolé, Opération impossible, votre navigateur ne supporte pas AJAX");
		return;
	}
	xhr_object.open("POST","p_appel.php",true);
	xhr_object.onreadystatechange = function() {
		if(xhr_object.readyState == 4) {
			
			var pos_ok = xhr_object.responseText.search(/ok/);
			
//			if (xhr_object.responseText.substring(0,2)=='ok') {
			if (pos_ok !=-1) {
				if (num_action==1) {
					switch_class('en_cours','enregistre');					
//alert('newid: '+xhr_object.responseText.substring(pos_ok+2));								
					newid=xhr_object.responseText.substring(pos_ok+2);
					if (newid.length>0)		 {						
											
		//			if (formulaire.elements['id'].value==0) {
		//			newid=xhr_object.responseText.substring(pos_ok+2);
					nature = formulaire.elements['nature'].value;
				//	alert('Ajout '+nature+newid);
					edite_fiche(nature, newid, '', true);
					}
										
				} else if (num_action==3) {

					document.forms['form3'].liste2.className='enregistre';
				}
			} else {
				alert("Un problème à été rencontré avec le serveur\ndurant l\'enregistrement des données.\nVeuillez retenter l\'enregistrement dans quelque secondes S.V.P.");
				alert(xhr_object.responseText);					
			}
		}
	}
	
	switch (num_action) {
		case 1 :	// ajout/modification
			switch_class('modif','en_cours');
			// Construction de la chaine de données
			data='';
			for (var champ=0; champ < formulaire.elements.length; champ++) {
				nom_champ = formulaire.elements[champ].name;	
				if (formulaire.elements[champ].className=='en_cours') {					
					// gestion de la case à cocher de validation
					if (nom_champ=='flag_cbo_Fiche_Validee') {											
						if (formulaire.elements['Fiche_Validee'].checked) {
							donnee = 'True';
						} else {
							donnee = 'False';
						}
						nom_champ='Fiche_Validee';
						data = data+'&champ_'+nom_champ+'='+donnee;						
					} else {
				
											
					if (formulaire.elements[champ].name.substr(0,5)=='flag_') {	// traitement des cases à cocher				
						tableau_champ = formulaire.elements[champ].name.substr(5); 
						
						
						for (i=0;i<formulaire.elements[tableau_champ].length;i++){
							nom_champ = formulaire.elements[tableau_champ][i].value;
							
				//		alert(nom_champ);								
							
							if (formulaire.elements[tableau_champ][i].checked==true) {
								donnee = 'True';
							} else {
								donnee = 'False';
							}
							data = data+'&champ_'+nom_champ+'='+donnee;
							
					//		alert(data);
						}	
					} else {													// traitement autres champs	
						//nom_champ = formulaire.elements[champ].name;
						donnee = protege(formulaire.elements[champ].value);							
						data = data+'&'+nom_champ+'='+donnee;
					}							
					}
					}
				}

				//	alert(formulaire.elements[champ].name);
				//	alert(data);
				
			// si des données ont été modifiées
			if (data.length>0) {
				data = 'id_action=200&id='+formulaire.elements['id'].value+'&nature='+formulaire.elements['nature'].value+data;
//alert(data);

			} else {
				return;
			}
		
			break;
	
		case 2 :	// suppression
  			data = 'id_action=201&id='+formulaire.elements['id'].value+'&nature='+formulaire.elements['nature'].value;	
			break;
		case 3 :	// Modification de la liste des themes ou  des mots cles 
				liste = document.form3.liste2;	
				liste.className='enregistre';
				var tab_liste = new Array();
				for (var i=0; i < liste.options.length; ++i) {
					tab_liste[i] = liste.options[i].value;
						//	alert(tab_liste[i]);				
				}
					
	  			data = 'id_action=203&id='+formulaire.elements['id'].value+'&nature='+formulaire.elements['nature'].value+'&liste='+serialize(tab_liste);
	  			
				//alert(data);	  			
	  			
			break;

		default :
			return;	
	}

	//alert(data);
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=iso-8859-15");
	xhr_object.setRequestHeader("Content-length", data.length);
	xhr_object.send(data);
}


function delete_image(img) {
  	if (confirm("Voulez-vous réellement supprimer cette image ?"+img)) {
		//anim_visible("animation","elements/enleve_fond_animation.gif",500);
		send2php('p_appel.php?id_action=205&img='+img, true);
       }
}




function save_new_item(nature, item_name) {	
	var item =document.getElementById(item_name).value;
	if  (item!='') {
		send2php('p_appel.php?id_action=204&nature='+nature+'&data='+item, true);
	}
}

function save_record() {
	anim_visible("animation","elements/ajoute_fond_animation.gif",900);
	//action_record(3);
	action_record(1);
	save_themes();
}
	
function save_themes(){
	if (document.form3.liste2.className=='modif'){		
		action_record(3);
	}
}

function delete_record() {
  	if (confirm("Voulez-vous réellement effacer cette fiche ?")) {
		anim_visible("animation","elements/enleve_fond_animation.gif",500);
		action_record(2);
       }
}

function cancel_record() {
	document.form1.reset()
	switch_class('modif','');
	switch_class('en_cours','');
	switch_class('enregistre','modif');	
}

function protege(string) {
	//	string = encodeURIComponent(string) // encode la chaine
	string = escape(string);
	return string;
}

function popup(page, fenetre) {
	var largeur=760;
	var hauteur=500;
	page+='&in_popup=1';
	anim_visible("animation","elements/loading.gif",900);
	var top=(screen.height-hauteur)/2;
	var left=(screen.width-largeur)/2;
	config='height='+hauteur+', width='+largeur+', left='+left+', top='+top+', toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no';
	fen = window.open(page, fenetre, config)
	if (fen !=null) fen.focus();
}

function edite_fiche(Nature, id, balise_div, no_popup) {
	switch (Nature)
	{
	  	case 'O':
	  		url="p_fiche_ouvrage_edition.php?id="+id;
			break;
		  case 'I':
			url="p_fiche_outil_edition.php?id="+id;
			break;
			
		  case 'S':
		  case 'SI':
		  case 'SR':
		  case 'S@': 
			url="p_fiche_structure_edition.php?id="+id;	
			break;
			
		  case 'R':
			url="p_fiche_article_edition.php?id="+id;			  
	}
	if (!no_popup) {
		popup(url,'edit');	
	} else {
		//location.href = url
		location.replace(url)
	}
}

function DeplacerItem(l1,l2) {
		if (l1.options.selectedIndex>=0) {
			do
				{
				o=new Option(l1.options[l1.options.selectedIndex].text,l1.options[l1.options.selectedIndex].value);
				l2.options[l2.options.length]=o;
				l1.options[l1.options.selectedIndex]=null;
				}
			while(l1.options.selectedIndex>=0);
			sortSelect(l2);
		} else {
			alert("Vous devez sélectionner un élement");
		}
}



function GereControle(Controleur, Controle, Masquer) {
	var objControleur = document.getElementById(Controleur);
	var objControle = document.getElementById(Controle);
//		if (isset(Controleur) &&  isset(Controle)) {
	if (Masquer=='1') {
		objControle.style.visibility=(objControleur.value==0)?'hidden':'visible';
		objControle.value=(objControleur.value==0)?0:objControle.value;}
	else {
		objControle.disabled=(objControleur.value==0)?true:false;
		objControle.value=(objControleur.value==0)?0:objControle.value;
		 }
//	}
	return true;
}


function ExisteDansListe(Liste, Valeur) {
	for(i=0;i< Liste.options.length ;i++){
        if(Liste.options[i].value == Valeur){
			return(true) ;          
			}	
    }
	return(false) ;
}

// simul en Javascript de isset PHP
function isset(variable){
if ( typeof( window[variable] ) != "undefined" ) {
     return true;
   }
else {
     return false;
   }
}

function strip_accent(chaine) {
  temp = chaine.replace(/[àâä]/gi,"a")
  temp = temp.replace(/[éèêë]/gi,"e")
  temp = temp.replace(/[îï]/gi,"i")
  temp = temp.replace(/[ôö]/gi,"o")
  temp = temp.replace(/[ùûü]/gi,"u")
  return temp
}

function chercheHTML(url, parametres, balise_div) {
		var myAjax = new Ajax.Updater(
			balise_div,
			url,
			{
			method: 'get',
			parameters: parametres,
			evalScripts: true
			}
		);

	}
	
function serialize( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

function ajoute_collection(balise_div) {
	flag_collection=(!flag_collection);
	if (!liste_collection) {
		liste_collection = document.getElementById(balise_div).innerHTML;	
	}	
	if (!flag_collection) {
		document.getElementById(balise_div).innerHTML=liste_collection;	
	}	
	else {
		htm = 'Nouvelle <input name="new_collection" type="text" id="new_collection" size="30" value="" title="Saisissez la nouvelle collection" />';
		htm=htm+ '<a href="#" onclick="javascript:save_new_item(\'C\', \'new_collection\');" >';
		htm=htm+ '<img src="elements/btn_save.gif" title ="Enregistrer" width="25" height="25" border="0" ></a>';
		document.getElementById(balise_div).innerHTML = htm;	
	}
}

function ajoute_theme(balise_div) {
	flag_theme=(!flag_theme);
	if (!liste_theme) {
		liste_theme = document.getElementById(balise_div).innerHTML;	
	}	
	if (!flag_theme) {
		document.getElementById(balise_div).innerHTML=liste_theme;	
	}	
	else {
		htm = 'Nouveau <input name="new_theme" type="text" id="new_theme" size="30" value="" title="Saisissez le nouveau theme" />';
		htm=htm+ '<a href="#" onclick="javascript:save_new_item(\'T\', \'new_theme\');" >';
		htm=htm+ '<img src="elements/btn_save.gif" title ="Enregistrer" width="25" height="25" border="0" ></a>';
		document.getElementById(balise_div).innerHTML = htm;	
	}	
}


function FF_preload_images(id) {
	// fonction de préchargement des images
    preload_image_object = new Image();
    image_url = new Array();
    var i = 0;    
	switch (id) {
        case 1: // resultats.php
	      	image_url[i++] = "elements/ajoute_fond_animation.gif";
		    image_url[i++] = "elements/enleve_fond_animation.gif";
		    image_url[i++] = "elements/loading.gif";
		    image_url[i++] = "elements/panier_animation.gif";
		    image_url[i++] = "elements/add_panier.gif";
		    image_url[i++] = "elements/voir_doc.gif";		    
		    image_url[i++] = "elements/editer.gif";			    
		    image_url[i++] = "elements/btn_supp.gif";			    
		    image_url[i++] = "elements/btn_ajout.gif";			    	    
        	break;
        case 2: // fiche visu simple
	      	image_url[i++] = "elements/imprimer.gif";
		    image_url[i++] = "elements/add_panier.gif";
		    image_url[i++] = "elements/btn_edite.gif";
		    image_url[i++] = "elements/panier_animation.gif";
        	break;        	
        case 3: // fiche mode edition
	      	image_url[i++] = "elements/imprimer.gif";
		    image_url[i++] = "elements/add_panier.gif";
		    image_url[i++] = "elements/btn_edite.gif";
		    image_url[i++] = "elements/panier_animation.gif";
		    image_url[i++] = "elements/btn_delete.gif";
		    image_url[i++] = "elements/btn_cancel.gif";
		    image_url[i++] = "elements/btn_save.gif";		    
        	break;      	
	}
    for(i=0; i<=image_url.lenght; i++) 
         preload_image_object.src = image_url[i];
}

function sortSelect(Obj){
	Liste= new Array();
	for(i=0;i<Obj.options.length;i++){
		Liste[i]=new Array()
		Liste[i][0]=Obj.options[i].text
		Liste[i][1]=Obj.options[i].value
	}
	Liste=Liste.sort()
	for(i=0;i<Obj.options.length;i++){
		Obj.options[i].text=Liste[i][0]
		Obj.options[i].value=Liste[i][1]
	}
}

function is_numeric(value){  
	return !isNaN(value);  
}  

function Impression() {
//	if (confirm('Désirez-vous imprimer les images')==true) {
//		document.getElementById('Image').class = '';
//	}
	window.print();
}

/**
 *
 * @author      Erwan Lefèvre <erwan.lefevre@aposte.net>
 * @copyright   Erwan Lefèvre 2009
 * @license     Creative Commons - Paternité 2.0 France - http://creativecommons.org/licenses/by/2.0/fr/
 * @version     2.0
 * 
 */

/** 
 * winDim() 
 * -----------------------------------------------------------------------------
 * retourne les dimentions intérieures de la fenêtre
 *
 * @return		{Object}		les mesures intérieures de la fenêtre : {'w', 'h'}
 */
function winDim() {
	var w,h;
	if ( window.innerWidth ) { // autres que IE
		w = window.innerWidth;
		h = window.innerHeight;
	} else if ( document.documentElement.clientWidth ) { // IE8
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if ( document.body.clientWidth ) { // IE6
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	} else {	// si inconnu alors valeurs par défaut
		w = 800;
		h = 600;		
		}

	return {'w':w, 'h':h} ;
}

function set_opacity(id, opacity)
{
        el = document.getElementById(id);
        el.style["filter"] = "alpha(opacity="+opacity+")";
        el.style["-moz-opacity"] = opacity/100;
        el.style["-khtml-opacity"] = opacity/100;
        el.style["opacity"] = opacity/100;
        return true;
}

function fade_out(id)
{
	for (i=100;i>=0;i--)
		{
		set_opacity(id, i)
		}
	return true;
}

function fade_in(id)
{
	for (i=0;i<=100;i++)
		{
		set_opacity(id, i)
		}
	return true;
}





/* ************************************************************************************************************************************************************************************************************ */
/*  Complément de fonction pour prise en compte questionnaire preps

/*  Compile les checkbox et place la ligne de résultat dans le champ caché (ex: ",1,2,3,") */
function Compile_Checklists(formulaire) {
	//formulaire= document.forms[form];
	champ_precedent = '-';
	for (i=0 ; i<= formulaire.length-1 ; i++) {
		if ((formulaire[i].name.substr(0,4)=='chk_')&& (formulaire[i].checked==true)){	// traitement des cases à cocher
			nom_champ = 'Champ_'+formulaire[i].name.substr(4,4);
			if (nom_champ!=champ_precedent) {
				document.getElementById(nom_champ).value=',';	
			}
			document.getElementById(nom_champ).value += formulaire[i].name.substr(9,2)+',';
			champ_precedent = nom_champ;	
			formulaire.elements[nom_champ].className='modif';
			//alert(document.getElementById(nom_champ).value);
		}
	}
	return true;
}

/*  Compile les boutons radio (rad_Champ_XXXX) et place la ligne de résultat dans le champ caché  */
function Compile_Radios(formulaire) {
	//formulaire= document.forms[form];
	for (i=0 ; i<= formulaire.length-1 ; i++) {
		if ((formulaire[i].name.substr(0,4)=='rad_')&& (formulaire[i].checked==true)){	// traitement des cases à cocher
			nom_champ = 'Champ_'+formulaire[i].name.substr(4,4);
			document.getElementById(nom_champ).value = formulaire[i].value;
			formulaire.elements[nom_champ].className='modif';
			//alert(document.getElementById(nom_champ).value);
		}
	}
	return true;
}


/*  Correction de switch_classe pour pointage sur premier formulaire si pas de précision. Sinon utilisation du 3ème paramètre optionnel */
function switch_class(ancienne_classe, nouvelle_classe) {
	if (switch_class.arguments[2]) {	// si le formulaire est précisé
		var f = switch_class.arguments[2];
	} else {
		var f = document.forms[0];	
		}	
	for (var champ=0; champ < f.elements.length; champ++) {
		if (f.elements[champ].className==ancienne_classe) {
			f.elements[champ].className=nouvelle_classe;		
		}
	}
}

/*  Correction de action_record */
function action_preps_record(num_action){	
	var xhr_object = null;
	var data = null;
	if (action_preps_record.arguments[1]) {	// si le formulaire est précisé
		var formulaire = action_preps_record.arguments[1];
	} else {
		var formulaire = document.forms[0];	
		}	
	// *** Correction ***	var formulaire = document.form1;
	//var formulaire = document.forms[0];
	if(window.XMLHttpRequest) //pour Firefox
		xhr_object = new XMLHttpRequest();
	else if(window.ActiveXObject) //Internet Explorer
		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
	else{
		alert("Désolé, Opération impossible, votre navigateur ne supporte pas AJAX");
		return;
	}
	xhr_object.open("POST","p_appel.php",true);
	xhr_object.onreadystatechange = function() {
		if(xhr_object.readyState == 4) {		
			var pos_ok = xhr_object.responseText.search(/ok/);
			if (pos_ok !=-1) {
				if (num_action==1) {
					switch_class('en_cours','enregistre', formulaire);												
					newid=xhr_object.responseText.substring(pos_ok+2);
					if (newid.length>0)		 {	// Nouvel enregistrement
							// alert(newid);
							formulaire.elements['id'].value = newid;
					} 
					//window.document.getElementById('div_dossier').innerHTML='Les renseignements ont été enregistrés sous le n°&nbsp;'+formulaire.elements['id'].value;
					window.document.getElementById('Titre').innerHTML='['+formulaire.elements['id'].value+'] - '+document.forms['form_demandeur'].elements['idStructure'].options[document.getElementById('idStructure').selectedIndex].text.substr(0,75);
				}
			} else {
				alert("Un problème à été rencontré avec le serveur\ndurant l\'enregistrement des données.\nVeuillez retenter l\'enregistrement dans quelque secondes S.V.P.");
				alert(xhr_object.responseText);					
			}
		}
	}
	switch (num_action) {
		case 1 :	// ajout/modification
			switch_class('modif','en_cours', formulaire);
			// Construction de la chaine de données
			data='';
			for (var champ=0; champ < formulaire.elements.length; champ++) {
				nom_champ = formulaire.elements[champ].name;	
				if (formulaire.elements[champ].className=='en_cours') {					
						//nom_champ = formulaire.elements[champ].name;
						donnee = protege(formulaire.elements[champ].value);							
						data = data+'&'+nom_champ+'='+donnee;
					}							
				}
//	alert(formulaire.elements[champ].name);
//	alert('Données : '+data+' longueur : '+data.length);
			// cas spécifique				
			if (formulaire.name=='form_demandeur') {	
				data = '&id_preps='+formulaire.elements['Preps'].value+'&id_structure='+formulaire.elements['idStructure'].value+'&id_contact='+formulaire.elements['idContact'].value+data;
			}		
			// si des données ont été modifiées			
			if (data.length>0) {				
				switch (formulaire.name) {
					case 'form_demandeur' :				
						data = 'id_action=601'+data;
						//alert(data);
						break;					
					case 'Form_1' :		
						data = 'id_action=602&id='+formulaire.elements['id'].value+data;
						//alert('Données : '+data);																
						break;							
					default :
						return;	
				}									
			} else {
				return;
			}
			break;
			
		default :
			return;	
	}
//alert(data);
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=iso-8859-15");
	xhr_object.setRequestHeader("Content-length", data.length);
	xhr_object.send(data);
}


// test si le champ est vide ou constitué d'un même chr répété 
function empty_field(champ, type) {
//	if (type <10 || type >6)  { // champ de type check ou ouinon
//		return false;	// non traités
//	}
	return (!champ || (champ.search(/^[\n\r]*(.)\1*[\n\r]*$/) >= 0));
}

function check_mel(mel) {
	var atom = "[!#-'*+\\-\\/-9=?A-Z^-~]+";
	var regex_adr =
		new RegExp("^"+atom+"(\\."+atom+")*@"+atom+"(\\."+atom+")*\\.[a-zA-Z]{2,4}$");
	if(mel.search(regex_adr) != 0)
		return false;	// mel contient des chr non valides
	return true;
}

function check_cp(cp) {
	 var vfcp = /^[0-9]{5}$/
	 if (vfcp.test(cp)==false)
		return false;	// cp incorrect
	return true;
}


function check_field(valeur, type) {
	switch (type) {
		case 1 :	// mèl
			if (check_mel(valeur)==false) {
				 return 'L\'adresse courriel est incorrecte !\r'; }
			return '';	
			break;	
		case 2 :	// Code postal
			if (check_cp(valeur)==false) {
				 return 'Le code postal est incorrect !\r'; }
			return '';	
			break;	
		case 3 :	// Date
			if (check_date(valeur)==false) {
				 return 'La date saisie est incorrecte, format autorisé : JJ/MM/AAAA !\r';		 
				 }
			return '';	
			break;				
			
			
		default :
			return '';	
	}
}


// Vérifie le format d'une date saisie
function check_date(valeur_date) {
	if (valeur_date.length == 0) {
		return true;
	}
	var tabDate = valeur_date.split('/');
	if (valeur_date.length>10) {
	 	return false;
	}
	for (i=0; i<valeur_date.length; i++) { 
		if (valeur_date.charAt(i) == ' ')
		return false;
	}	
	// suppression des 0 éventuels pour utilisation de parsint
	for (i=0; i<tabDate.length; i++)
		tabDate[i] = (tabDate[i].charAt(0)=='0')?tabDate[i].charAt(1):tabDate[i];	
	// date de test
	var datTest_Date = new Date(parseInt(tabDate[2]), parseInt(tabDate[1])-1, parseInt(tabDate[0]));
	if ((parseInt(tabDate[0]) != datTest_Date.getDate()) || (parseInt(tabDate[1]) != parseInt(datTest_Date.getMonth())+1)) {
		return false;
	}
	if ((tabDate[2].length != 4) || (parseInt(tabDate[2]) < 1980) || (parseInt(tabDate[2]) > 2099)) {
		return false;
	}
	return true;
}

// Retourne true si valeur_date est postérieure à la date du jour
function DateFuture(valeur_date)
	{var tabDate = valeur_date.split('/');
	var datAujourdhui = new Date();
	tabDate = ConvNum(tabDate);
	if (valeur_date.length > 0)
	{ var datTest_Date = new Date(parseInt(tabDate[2]), parseInt(tabDate[1])-1, parseInt(tabDate[0]));
	if (datTest_Date <= datAujourdhui) return false;
	}
	return true;
}

function timestamp(valeur_date) {
	var tabDate = valeur_date.split('/');
	if (valeur_date.length>10) {
	 	return '';
	}
	return "{ts '"+tabDate[2]+"-"+tabDate[1]+"-"+tabDate[0]+" 00:00:00'}";	
}

function trim(myString) {
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
} 

function openDiv(id_Div, nb_div){
   if (document.getElementById(id_Div).style.display=='none') {
	   document.getElementById(id_Div).style.display='block';
   } else {
   	document.getElementById(id_Div).style.display='none';	   
   }
}

function close_All_Div(nb){
	for(var i = 1; i < nb+1; i++) {		
	   document.getElementById("div_"+("000"+i).slice(-4)).style.display='none';
	}
}
