function changeSousFiche(id_form, id_input, select){
  //if(select && select.selectedIndex>0){
    var form=document.getElementById(id_form);
    if(form){
      var input=document.getElementById(id_input);
      if(input){
        input.value=select.value;
        form.submit();
      }
    }
  //}
}

/* Déplace un formulaire de façon a se qu'il ne soit pas imbriqué dans un autre
*  (A n'utiliser que sur des formulaire invisible)
*/
function moveForm(id_form){
  var div=document.getElementById(id_form);
  if(div){
    var body=document.getElementsByTagName('body')[0];
    if(body){
      var form=document.createElement('form');
      form.setAttribute('method',div.getAttribute('method'));
      form.setAttribute('action',div.getAttribute('action'));
      form.setAttribute('target',div.getAttribute('target'));
      var id=div.getAttribute('id');
      while(div.childNodes.length>0){
        form.appendChild(div.childNodes[0]);
      }
      div.parentNode.removeChild(div);
      form.setAttribute('id',id);
      body.appendChild(form);
    }
  }
}

/* Modifie la liste des commercialisateurs en fonction de la catégorie choisie
*/
function modifCategorie(){
  var l1    = document.getElementById('categorie');
  var l2    = document.getElementById('commercialisateur');
  if(l1 && l2){
  	var index = l1.selectedIndex;
  
  	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
	    return;
	  }
  	var url="module.php?module=fiche&page=recupCommercialisateur"
  	if(l1.selectedIndex==0){
  		/* Si aucune valeur de définie, on passe une variable spéciale */
			url+="&novalue=1";
		} else {
			url+="&id="+l1.options[index].value;
		}
  	xhr_object.open("POST", url, true);
  	xhr_object.onreadystatechange = function() {
	    if(xhr_object.readyState == 4){
	       
	      var nouvelle_liste = xhr_object.responseText.split("!");
	      l2.options.length = 0;
	      for (i=0;i<(nouvelle_liste.length-1);i++){
	        valeur_courante = nouvelle_liste[i].split("#");
	        l2.options[l2.options.length] = new Option(valeur_courante[1],valeur_courante[0]);
	      }

 	      cacheChargement();
	    }
	  }
	  xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  var data = "";
	  xhr_object.send(data);
	  afficheChargement();
	}
}

/* Modifie la liste des commercialisateurs en fonction de la catégorie choisie
*/
function interlocuteur(){

  var l1    = document.getElementById('categorie');
  var l2    = document.getElementById('commercialisateur');
  var l3    = document.getElementById('interlocuteur');
  if(l1 && l2 && l3){
  	var index = l1.selectedIndex;

  	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
	    return;
	  }
	  
  	var url='module.php?module=fiche&page=recupInterlocuteur'
  	if(l1.selectedIndex==0){
  		/* Si aucune valeur de définie, on passe une variable spéciale */
			url+='&novalue=1';
		} else {
			url+='&id='+l1.options[index].value;
		}
		
		var valSelect = l2.options[l2.selectedIndex].value;
		
    var tab=valSelect.split('\$\$');
		
		if (tab[0]!=0) {
		
		  url+='&commid='+tab[0];
    	xhr_object.open('POST', url, true);
      	xhr_object.onreadystatechange = function() {
    	    if(xhr_object.readyState == 4){
    	       
    	      var nouvelle_liste = xhr_object.responseText.split('!');
    	      l3.options.length = 0;
    	      for (i=0;i<(nouvelle_liste.length-1);i++){
    	        valeur_courante = nouvelle_liste[i].split('#');
    	        l3.options[l3.options.length] = new Option(valeur_courante[1],valeur_courante[0]);
    	      }
            if (l3.onchange) {
              l3.onchange();
            }
     	      cacheChargement();
    	    }
    	  }
    	  xhr_object.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	  var data = '';
    	  xhr_object.send(data);
    	  afficheChargement();
  	}
	}
}

/*
* Modifie liste2 en fonction de la valeurs de liste1
*/
function modifListe(id_fiche,liste1,liste2){
  var l1    = document.getElementById(liste1);
  var l2    = document.getElementById(liste2);
  if(l1 && l2){
  	var index = l1.selectedIndex;
  
  	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
	    return;
	  }
  	var url="module.php?module=fiche&page=action_liste&fiche[id_fiche]="+id_fiche+"&liste1="+liste1+"&liste2="+liste2
  	if(l1.selectedIndex==0){
  		/* Si aucune valeur de définie, on passe une variable spéciale */
			url+="&novalue=1";
		} else {
			url+="&champ="+l1.options[index].value;
		}
  	xhr_object.open("POST", url, true);
  	xhr_object.onreadystatechange = function() {
	    if(xhr_object.readyState == 4){
	      var nouvelle_liste = xhr_object.responseText.split("!");
	      l2.options.length = 0;
	      for (i=0;i<(nouvelle_liste.length-1);i++){
	        valeur_courante = nouvelle_liste[i].split("#");
	        l2.options[l2.options.length] = new Option(valeur_courante[1],valeur_courante[0]);
	      }
	      if(l2.onchange){
	        l2.onchange();
	      }
	      cacheChargement();
	    }
	  }
	  xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  var data = "";
	  xhr_object.send(data);
	  afficheChargement();
	}
}

/* Fonctions permettant l'affichage d'une infobulle pour avertir qu'un
*  chargement est en cours.
*/
var nbChargement=0;
function afficheChargement(){
  var charg=document.getElementById('message_chargement');
  if(!charg){
    charg=createChargement();
  }
  if(charg && nbChargement==0){
    charg.style.display='block';
  }
  nbChargement++;
}
function cacheChargement(){
  var charg=document.getElementById('message_chargement');
  nbChargement--;
  if(charg && nbChargement==0){
    charg.style.display='none';
  }
}
function createChargement(){
  var charg=document.createElement('div');
  charg.style.display='none';
  charg.style.position='absolute';
  charg.style.top='20px';
  charg.style.right='20px';
  charg.style.fontWeight='bold';
  charg.style.color='#EEE';
  charg.style.background='#555';
  charg.style.padding='2px 5px';
  charg.setAttribute('id','message_chargement');
  charg.innerHTML='Chargement en cours';
  document.getElementsByTagName('body')[0].appendChild(charg);
  return charg;
}

var tab_onload=new Array();

/* Exécute une liste de fonctions qui ne doivent être éxécuter qu'une fois que
*  le chargement de la page est terminé
*/
function myOnload(){
  for(var i=0;i<tab_onload.length;i++){
    tab_onload[i]();
  }
}
window.onload=function(){
  myOnload()
}















// Supprime un éléméent
function supprimeElement(id){
  if(confirm('Etes-vous sur de vouloir supprimer cet éléments ?')){
    var form=document.getElementById('form_sous_action')
    var input=document.createElement('input');
    input.setAttribute('type','hidden');
    input.setAttribute('name','fiche[action]');
    input.setAttribute('value','edition');
    form.appendChild(input);
    var input=document.createElement('input');
    input.setAttribute('type','hidden');
    input.setAttribute('name','fiche[sous_action]');
    input.setAttribute('value','supprimer');
    form.appendChild(input);
    var input=document.createElement('input');
    input.setAttribute('type','hidden');
    input.setAttribute('name','fiche[id_element]');
    input.setAttribute('value',id);
    form.appendChild(input);
    
    form.submit();
  }
}
// Edition d'un élément
function editeElement(id){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','editionElement');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[id_element]');
  input.setAttribute('value',id);
  form.appendChild(input);
  
  form.submit();
}
// Copie un élément
function copieElement(id){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','copier');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[id_element]');
  input.setAttribute('value',id);
  form.appendChild(input);
  
  form.submit();
}
// Coupe un élément
function coupeElement(id){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','couper');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[id_element]');
  input.setAttribute('value',id);
  form.appendChild(input);
  
  form.submit();
}
// Colle l'élément actuellement couper dans l'éléments "id" à la position "pos"
function colleElement(id,pos){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','coller');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[id_element]');
  input.setAttribute('value',id);
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[position]');
  input.setAttribute('value',pos);
  form.appendChild(input);
  
  form.submit();
}
function supprimeCopier(){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','effaceCopier');
  form.appendChild(input);
  
  form.submit();
}
// Ajout un élément à l'élément
function ajoutElement(id){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','choixAjout');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[id_element]');
  input.setAttribute('value',id);
  form.appendChild(input);
  
  form.submit();
}

function choixAjout(id,element){
  var form=document.getElementById('form_sous_action')
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[action]');
  input.setAttribute('value','edition');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[sous_action]');
  input.setAttribute('value','ajout');
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[id_element]');
  input.setAttribute('value',id);
  form.appendChild(input);
  var input=document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name','fiche[element]');
  input.setAttribute('value',element);
  form.appendChild(input);
  
  form.submit();
}

/* Met a jour les valeurs d'un menu déroulant selon la valeur d'un autre menu
*  déroulant. Utilisation seulement pour les noms de chmpas d'une table.
*  @param id_table string : id du menu déroulant contenant les noms des tables
*  @param id_champ string : id du menu déroulant qui contiendra les nom des
*       champs de la table sélectionner
*/
function listeChamps(id_table, id_champ){
  var l1    = document.getElementById(id_table);
  var l2    = document.getElementById(id_champ);
  var value=null;
  if(l1.nodeName.toLowerCase()=='select'){
    value = l1.value;
  } else {
    value = l1.value;
  }
  
  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;
  }
  var url="module.php?module=fiche&page=get_champs&table="+value;
  if(arguments.length==3 && arguments[2]==true){
    url+="&null=1";
  }
  xhr_object.open("POST", url, true);
  xhr_object.onreadystatechange = function() {
    if(xhr_object.readyState == 4){
      nouvelle_liste = xhr_object.responseText.split("!");
      var value2=l2.value;
      l2.options.length = 0;
      for(i=0;i<(nouvelle_liste.length-1);i++){
        valeur_courante = nouvelle_liste[i].split("#");
        var selected=false;
        if(valeur_courante[0]==value2){
        	selected=true;
				}
        l2.options[l2.options.length] = new Option(valeur_courante[1],valeur_courante[0],selected,selected);
      }
      if(l2.onchange){
        l2.onchange();
      }
    }
  }
  xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  var data = "";
  xhr_object.send(data);
}


/* Créer une sous-couche à une couche requetes
*  la couleur attibué à la sous-couche dépend des attributs de la couche de
*  requete : si la couc de requete possede un attribut "fill" qui a une valeur
*  différrente de "none", alors la sous-couche aura un attribut "fill" avec
*  pour valeur 'couleur'. Idem pour l'attibute "stroke".
*  @param id_parent string : id de la couche requete
*  @param id string : id de la couche à créer
*  @param couleur string : couleur à attribué à la couche (selon les attribut de
*       la couche requete) 
*/
function createSousCoucheRequete(id_parent,id,couleur){
  // Récupération de l'objet SVG
  var svgdoc=window.opener.document.embmainmap.getSVGDocument();
  // Test si l'id n'est pas déjà utilisé
  var sousCouche=svgdoc.getElementById(id);
  if(sousCouche){
    return sousCouche;
  } else {
    // Récupération de la couche contenant les requetes
    var parent=svgdoc.getElementById(id_parent);
    // Création de la couche qui va contenir les objets
    sousCouche=svgdoc.createElement('g');
    // On lui attribut l'id
    sousCouche.setAttribute('id',id);
    // Si la couche parent à un attribut "fill" qui est définit 
    if(parent.style.getPropertyValue('fill')!='' && parent.style.getPropertyValue('fill')!='none'){
     // On définit la couleur pour le "fill" de la sous-couche
      sousCouche.style.setProperty('fill',couleur);
    }
    // Si la couche parent à un attribut "stroke" qui est définit
    if(parent.style.getPropertyValue('stroke')!='' && parent.style.getPropertyValue('stroke')!='none'){
      // On définit la couleur pour le "stroke" de la sous-couche
      sousCouche.style.setProperty('stroke',couleur);
    }
    // Aucun click n'est possible sur la sous-couche
    sousCouche.setAttribute('pointer-events','none');
    sousCouche.setAttribute('req','1');
    //alert(parent.getStyle().getPropertyValue('stroke'));
    // On ajoute la sous-couche à la couche de requete
    parent.appendChild(sousCouche);
    return sousCouche;
  }
}

/* Créer une sous-couche à une couche requetes
*  la couleur attibué à la sous-couche dépend des attributs de la couche de
*  requete : si la couc de requete possede un attribut "fill" qui a une valeur
*  différrente de "none", alors la sous-couche aura un attribut "fill" avec
*  pour valeur 'couleur'. Idem pour l'attibute "stroke".
*  @param id_parent string : id de la couche requete
*  @param id string : id de la couche à créer
*  @param couleur string : couleur à attribué à la couche (selon les attribut de
*       la couche requete) 
*/
function createSousCoucheRequeteCercle(id_parent,id,diametre){
//alert(diametre);
  // Récupération de l'objet SVG
  var svgdoc=window.opener.document.embmainmap.getSVGDocument();
  // Test si l'id n'est pas déjà utilisé
  var sousCouche=svgdoc.getElementById(id);
  if(sousCouche){
    return sousCouche;
  } else {
    // Récupération de la couche contenant les requetes
    var parent=svgdoc.getElementById(id_parent);
    // Création de la couche qui va contenir les objets
    sousCouche=svgdoc.createElement('g');
    // On lui attribut l'id
    sousCouche.setAttribute('id',id);
    // Si la couche parent à un attribut "fill" qui est définit 
     // On définit la transformation pour le "stroke" de la sous-couche
      //sousCouche.setAttribute('transform','scale('+diametre/2+')');
    
    // Aucun click n'est possible sur la sous-couche
    sousCouche.setAttribute('pointer-events','none');
    sousCouche.setAttribute('req','1');
    //alert(parent.getStyle().getPropertyValue('stroke'));
    // On ajoute la sous-couche à la couche de requete
    parent.appendChild(sousCouche);
    return sousCouche;
  }
}

function fenetreCouleur(id){
  var couleur = document.getElementById(id).value; //Récupérer la couleur actuelle
  if (couleur.charAt(0) == "#") couleur = couleur.substring(1, couleur.length); //Enlever le #
  var fen = window.open("choix_couleur/couleurs.php?couleur="+couleur+"&id="+id, "", "width=370,height=340");
 	if (!fen.opener) fen.opener = self;
}

function changeCouleur(id,couleur){
  var elem=document.getElementById(id);
  if(elem){
    elem.style.backgroundColor=couleur;
  }
}

function coche(id){
  var checkbox=document.getElementById(id);
  if(checkbox){
    checkbox.checked=true;
  }
}

function addCouleurAnalyse(type){
  switch(type){
    case 'entier':
    case 'flottant':
      var tbody=document.getElementById('couleurAnalyse');
      if(tbody){
        var tr=document.createElement('tr');
        
        var td=document.createElement('td');
        var input=document.createElement('input');
        input.setAttribute('type','text');
        input.setAttribute('name','valeurs['+numAnalyse+'][min]');
        td.appendChild(input);
        tr.appendChild(td);
        
        var td=document.createElement('td');
        var input=document.createElement('input');
        input.setAttribute('type','text');
        input.setAttribute('name','valeurs['+numAnalyse+'][max]');
        td.appendChild(input);
        tr.appendChild(td);
        
        var td=document.createElement('td');
        td.setAttribute('align','center');
        var input=document.createElement('input');
        input.setAttribute('type','hidden');
        input.setAttribute('name','valeurs['+numAnalyse+'][couleur]');
        input.setAttribute('id','couleurs_'+numAnalyse);
        input.numAnalyse=numAnalyse;
        input.onchange=function(){
          changeCouleur('div_'+this.numAnalyse,this.value);
          coche('check_'+this.numAnalyse);
        }
        td.appendChild(input);
        var div=document.createElement('div');
        div.style.border='1px solid black';
        div.style.width='2em';
        div.style.height='1em';
        div.style.cursor='pointer';
        div.numAnalyse=numAnalyse;
        div.onclick=function(){
          fenetreCouleur('couleurs_'+this.numAnalyse);
        }
        div.setAttribute('id','div_'+numAnalyse+'');
        td.appendChild(div);
        tr.appendChild(td);
        
        var td=document.createElement('td');
        td.setAttribute('align','center');
        var input=document.createElement('input');
        input.setAttribute('type','checkbox');
        input.setAttribute('name','valeurs['+numAnalyse+'][analyse]');
        input.setAttribute('id','check_'+numAnalyse);
        td.appendChild(input);
        tr.appendChild(td);
        
        tbody.insertBefore(tr,document.getElementById('couleurAnalyseAjout'));
        //tbody.appendChild(tr);
        
        numAnalyse++;
      }
      break;
    case 'date':
    case 'time':
    case 'datetime':
      var tbody=document.getElementById('couleurAnalyse');
      if(tbody){
	      var tr=document.createElement('tr');
	      
	      /* Case contenant la valeur min  */
	      var td=document.createElement('td');
	      
	      var select=document.createElement('select');
	      select.setAttribute('name','valeurs['+numAnalyse+'][min][jour]');
	      select.options[0] = new Option('','');
	      for(var i=1;i<=31;i++){
	      	var num='';
	      	if(i<10){
	      		num='0'+i;
					} else {
						num=i;
					}
	      	select.options[select.options.length] = new Option(num,num);
				}
	      td.appendChild(select);
	      
	      var span=document.createElement('span');
	      span.innerHTML='&nbsp;/&nbsp;';
	      td.appendChild(span);
	      
	      var select=document.createElement('select');
	      select.setAttribute('name','valeurs['+numAnalyse+'][min][mois]');
	      select.options[0] = new Option('','');
	      for(var i=1;i<=12;i++){
	      	var num='';
	      	if(i<10){
	      		num='0'+i;
					} else {
						num=i;
					}
	      	select.options[select.options.length] = new Option(num,num);
				}
	      td.appendChild(select);
	      
	      var span=document.createElement('span');
	      span.innerHTML='&nbsp;/&nbsp;';
	      td.appendChild(span);
	      
	      var input=document.createElement('input');
	      input.setAttribute('type','text');
	      input.setAttribute('name','valeurs['+numAnalyse+'][min][annee]');
	      input.setAttribute('size','5');
	      input.setAttribute('maxlength','4');
	      td.appendChild(input);
	      
	      tr.appendChild(td);
	      
	      
	      /* Case contenant la valeur max  */
	      var td=document.createElement('td');
	      
	      var select=document.createElement('select');
	      select.setAttribute('name','valeurs['+numAnalyse+'][max][jour]');
	      select.options[0] = new Option('','');
	      for(var i=1;i<=31;i++){
	      	var num='';
	      	if(i<10){
	      		num='0'+i;
					} else {
						num=i;
					}
	      	select.options[select.options.length] = new Option(num,num);
				}
	      td.appendChild(select);
	      
	      var span=document.createElement('span');
	      span.innerHTML='&nbsp;/&nbsp;';
	      td.appendChild(span);
	      
	      var select=document.createElement('select');
	      select.setAttribute('name','valeurs['+numAnalyse+'][max][mois]');
	      select.options[0] = new Option('','');
	      for(var i=1;i<=12;i++){
	      	var num='';
	      	if(i<10){
	      		num='0'+i;
					} else {
						num=i;
					}
	      	select.options[select.options.length] = new Option(num,num);
				}
	      td.appendChild(select);
	      
	      var span=document.createElement('span');
	      span.innerHTML='&nbsp;/&nbsp;';
	      td.appendChild(span);
	      
	      var input=document.createElement('input');
	      input.setAttribute('type','text');
	      input.setAttribute('name','valeurs['+numAnalyse+'][max][annee]');
	      input.setAttribute('size','5');
	      input.setAttribute('maxlength','4');
	      td.appendChild(input);
	      
	      tr.appendChild(td);
	      
	      
        var td=document.createElement('td');
        td.setAttribute('align','center');
        var input=document.createElement('input');
        input.setAttribute('type','hidden');
        input.setAttribute('name','valeurs['+numAnalyse+'][couleur]');
        input.setAttribute('id','couleurs_'+numAnalyse);
        input.numAnalyse=numAnalyse;
        input.onchange=function(){
          changeCouleur('div_'+this.numAnalyse,this.value);
          coche('check_'+this.numAnalyse);
        }
        td.appendChild(input);
        var div=document.createElement('div');
        div.style.border='1px solid black';
        div.style.width='2em';
        div.style.height='1em';
        div.style.cursor='pointer';
        div.numAnalyse=numAnalyse;
        div.onclick=function(){
          fenetreCouleur('couleurs_'+this.numAnalyse);
        }
        div.setAttribute('id','div_'+numAnalyse+'');
        td.appendChild(div);
        tr.appendChild(td);
        
        var td=document.createElement('td');
        td.setAttribute('align','center');
        var input=document.createElement('input');
        input.setAttribute('type','checkbox');
        input.setAttribute('name','valeurs['+numAnalyse+'][analyse]');
        input.setAttribute('id','check_'+numAnalyse);
        td.appendChild(input);
        tr.appendChild(td);
	      
	      tbody.insertBefore(tr,document.getElementById('couleurAnalyseAjout'));
	      
        numAnalyse++;
	    }
      break;
  }
}

function enregistreRetour(id_retour, id_form){
  document.getElementById(id_retour).value="non";
  document.getElementById(id_form).submit();
}

function supprimeLigne(objet){
  if(objet.nodeName.toLowerCase()!='tr'){
    supprimeLigne(objet.parentNode);
  } else {
    objet.parentNode.removeChild(objet);
  }
}

function deleteZoomEncombre(){

 if (window.opener.document.getElementById("embmainmap")){
   pere = window.opener.mainmap.getElementById('zoom_encombre');
	}else{
  pere = window.opener.opener.mainmap.getElementById('zoom_encombre');
	 }
 	noeuds = pere.getChildNodes();
	j=noeuds.getLength()-1;
	while(j>=0){
		pere.removeChild(noeuds.item(j));
		j--;
	}
}


var fiche_borderBottom='1px rgb(153,153,153) solid';
var fiche_backgroundColor='white';
var fiche_selectedBorderBottom='1px solid rgb(245,245,245)';
var fiche_selectedBackgroundColor='rgb(245,245,245)';

var classeurs=new Array();
var onglets=new Array();
function afficheOnglet(idClasseur, onglet){
  var num=0;
  for(num=0;num<classeurs.length;num++){
    if(classeurs[num]==idClasseur){
      break;
    }
  }
  // On remet tout les styles des onglets par défaut et on cache toutes les fiches
  nbOnglet=onglets[num].length;
  for(i=0;i<nbOnglet;i++){
    document.getElementById(idClasseur+'_onglet_'+onglets[num][i]).style.borderBottom=fiche_borderBottom;
    document.getElementById(idClasseur+'_onglet_'+onglets[num][i]).style.backgroundColor=fiche_backgroundColor;

    document.getElementById(idClasseur+'_fiche_'+onglets[num][i]).style.display='none'; 
  }
  // On met l'onglet selectionné avec le bon style
  document.getElementById(idClasseur+'_onglet_'+onglet).style.borderBottom=fiche_selectedBorderBottom;
  document.getElementById(idClasseur+'_onglet_'+onglet).style.backgroundColor=fiche_selectedBackgroundColor;

  // On affiche la fiche selectionné
  document.getElementById(idClasseur+'_fiche_'+onglet).style.display='block';
  
  var classeur=document.getElementById(idClasseur);
  if(classeur){
  	classeur.value=onglet;
  }
}




//initialisation de la largeur par défaut mini
var ww=300;
//initialisation de la hauteur par défaut mini
var hh=200;
//incrément pour IE
var step=15;
function redimmention(){
// Premier redimensionement : garde des scolls bars, car ne tient pas compte du cadre du document
self.window.resizeTo(document.body.scrollWidth,document.body.scrollHeight);
// Valeurs arbitrairement grandes pour forcer un scroll maximum
document.body.scrollLeft=100000;
document.body.scrollTop=100000;
// Récupération du décalage à rajouter pour supprimer les scrollbars
var delta_x=document.body.scrollLeft;
var delta_y=document.body.scrollTop;
// Redimensionnement final
self.window.resizeTo(document.body.scrollWidth+delta_x,document.body.scrollHeight+delta_y);
 /* if(document.all){
    x=document.body.scrollWidth;
    ww=(x<(screen.width-step) && x>ww) ? x : ww;
    x=document.body.scrollHeight;
    hh=(x<(screen.height-step) && x>hh) ? x : hh;
    redim();
  } else if(document.layers){
    ww=(document.width>ww) ? (document.width+10):ww;
    hh=(document.height>hh) ? (document.height+10):hh;
    setTimeout("self.window.resizeTo(ww,hh);",100);
  }*/
}
/*
function redim(){
  ok=0;
  if(document.all){
    document.body.scrollLeft=2;
    if(document.body.scrollLeft>0 && ww<(screen.width-step)){
      ww+=step;
      self.window.resizeTo(ww,hh);
      ok=1;
    }
    document.body.scrollTop=2;
    if(document.body.scrollTop>0 && ww<(screen.height-step)){
      hh+=step;
      self.window.resizeTo(ww,hh);
      ok=1;
    }
    if(ok==1){
      setTimeout('redim();',10);
    };
  }
}
*/


function analyse_set_legende(tab,selon,lib_selon,unite){
  var mainmap=window.opener.mainmap;
  var legende=mainmap.getElementById('legende_analyse');
  if(legende==null){
    legende=mainmap.createElement('g');
    legende.setAttribute('id','legende_analyse');
    
    var tmp_legende=mainmap.getElementById('legende_color');
    tmp_legende.parentNode.insertBefore(legende,tmp_legende);
  }

  // Supression de la légende actuel
  while(legende.hasChildNodes()){
    legende.removeChild(legende.firstChild);
  }
  
  fond_legende=mainmap.createElement('rect');
  fond_legende.setAttribute("x",0);
  fond_legende.setAttribute("y",0);
  fond_legende.setAttribute("stroke","black");
  fond_legende.setAttribute("fill","white");
  fond_legende.setAttribute("id","rect_legende_analyse");
  legende.appendChild(fond_legende);
  
  var maxWidth=0;

  if(unite!=''){
    lib_selon=lib_selon+' ('+unite+')';
  }

  // Création du titre de la légende
  var titre_leg=mainmap.createElement('text');
  titre_leg.appendChild(mainmap.createTextNode(lib_selon));
  titre_leg.setAttribute('x',5);
  titre_leg.setAttribute('y',5+12);
  titre_leg.setAttribute('font-size',12);
  titre_leg.setAttribute('font-weight','normal');
  titre_leg.setAttribute('text-decoration','underline');
  titre_leg.setAttribute('fill','black');
  titre_leg.setAttribute('stroke','none');
  titre_leg.setAttribute('pointer-events','none');
  var trace=titre_leg.getBBox();
  maxWidth=trace.width-25;
  legende.appendChild(titre_leg);
  
  
  for(var i=0;i<tab.length;i++){
    var rect=mainmap.createElement('rect');
    rect.setAttribute('width',20);
    rect.setAttribute('height',20);
    rect.setAttribute('transform','translate('+(5)+' '+(25*i+5+22)+')');
    rect.setAttribute('pointer-events','none');
    rect.setAttribute('fill',tab[i][1]);
    legende.appendChild(rect); 
  
    var text=mainmap.createElement('text');
    text.appendChild(mainmap.createTextNode(tab[i][0]));
    text.setAttribute('x',30);
    text.setAttribute('y',25*(i+1)-4+22);
    text.setAttribute('font-size',12);
    text.setAttribute('font-weight','normal');
    text.setAttribute('fill','black');
    text.setAttribute('stroke','none');
    text.setAttribute('pointer-events','none');
    var trace=text.getBBox();
    if(trace.width>maxWidth){
      maxWidth=trace.width;
    }
    legende.appendChild(text); 
  }
   
  fond_legende.setAttribute('width',35+maxWidth);
  fond_legende.setAttribute('height',20*i+5*(i-1)+5*2+22);

  legende.setAttribute('onmousedown','mouse_down_legende(evt,0,0)');
  legende.setAttribute('onmouseup','mouse_up_legende()');
  legende.setAttribute('onmousemove','mouse_move_legende(evt,'+(35+maxWidth)+','+(20*i+5*(i-1)+5*2+22)+',"legende_analyse")');
  legende.setAttribute('onmouseover','creer_menu_legende(evt)');
  legende.setAttribute('onmouseout','enlevermenu()');
  
  legende.getStyle().setProperty('display','block');
}

function texteChoixValeur(id_fiche,element){
	var nom='';
	var url='module.php?module=fiche&page=get_valeurs&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+element;
  var param='directories=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no, width=100, height=100';
  var win=window.open(url,nom,param);
  win.focus();
}

function recupInfoSVG(id_svg){
  var element=window.opener.mainmap.getElementById(id_svg);
  var parent=element.parentNode;
  var grandParent=parent.parentNode;
  
  var tab_id=window.opener.fiche2_parseId(id_svg);
  
  document.getElementById('elem_table').value=grandParent.getAttribute('table');
  document.getElementById('elem_table2').value=grandParent.getAttribute('table2');
  document.getElementById('elem_idchamp').value=grandParent.getAttribute('idchamp');
  document.getElementById('elem_jointure').value=grandParent.getAttribute('jointure');
  document.getElementById('elem_clausew').value=grandParent.getAttribute('clausew');
  document.getElementById('elem_id').value=tab_id[1];
}


/* Fonctions spécifique au sous-fiche
*/

function sousFicheURL(url,data){
	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("POST", url, false);
  xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr_object.send(data);
  if(xhr_object.readyState == 4){
  	return xhr_object.responseText;
	}
  
}

function sousFiche_delier(id_select,source,id_fiche){
	var select=document.getElementById(id_select+'_select');
	if(select && select.selectedIndex>-1){
		if(confirm('Etes-vous sur de vouloir supprimer cette liaison ?')){
			var cible=select.value;
			source=encodeURIComponent(source);
			cible=encodeURIComponent(cible);
			var data=sousFicheURL('module.php','module='+module+'&page=sous_fiche_action&fiche[fiche_action]=delier&valeurs[source]='+source+'&valeurs[cible]='+cible+'&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+id_select);
			if(data=='OK'){
				select.options[select.selectedIndex]=null;
				select.selectedIndex=0;
				select.onchange();
			}
		}
	}
}



function sousFiche_lier(id_select,source,id_fiche,cible){
	if(cible==null || cible==undefined){
		var nom='';
		var url='module.php?module='+module+'&page=sous_fiche_action&fiche[fiche_action]=popup_lier&valeurs[source]='+source+'&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+id_select;
		var param='directories=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no, width=500, height=300';
		var win=window.open(url,nom,param);
	} else {
		var select=document.getElementById(id_select+'_select');
		source=encodeURIComponent(source);
		cible=encodeURIComponent(cible);
		var data=sousFicheURL('module.php','module='+module+'&page=sous_fiche_action&fiche[fiche_action]=lier&valeurs[source]='+source+'&valeurs[cible]='+cible+'&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+id_select);
    if(data.indexOf('OK')==0){
			var nom=data.substr(3);
			select.options[select.options.length]=new Option(nom,cible);
			select.selectedIndex=select.options.length-1;
			select.onchange();
		}
	}
}
function sousFiche_ajout(id_select,source,id_fiche,isModif){
	var select=document.getElementById(id_select+'_select');
	source=encodeURIComponent(source);
	var data=sousFicheURL('module.php','module='+module+'&page=sous_fiche_action&fiche[fiche_action]=ajouter&valeurs[source]='+source+'&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+id_select);
	var id_cible=null;
	if(data.indexOf('OK')==0){
		id_cible=data.substr(3);
	} else if(data=='CLE'){
		var id_cible=prompt('Identifiant ?','');
		if(trim(cible)!=''){
			var data=sousFicheURL('module.php','module='+module+'&page=sous_fiche_action&fiche[fiche_action]=ajouter&valeurs[source]='+source+'&valeurs[cible]='+id_cible+'&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+id_select);
			if(data.indexOf('OK')==0){
				id_cible=data.substr(3);
			}
		}
	}
	if(id_cible!=null){
		select.options[select.options.length]=new Option('',id_cible);
		select.selectedIndex=select.options.length-1;
		select.onchange();
	/*	if(isModif){
			select.onchange();
		} else {
			document.getElementById('id_form').submit()
		}*/
	}
}
function sousFiche_suppr(id_select,source,id_fiche){
	var select=document.getElementById(id_select+'_select');
	if(select && select.selectedIndex>-1){
		if(confirm('Etes-vous sur de vouloir le supprimer ?')){
			var cible=select.value;
			source=encodeURIComponent(source);
			cible=encodeURIComponent(cible);
			var data=sousFicheURL('module.php','module='+module+'&page=sous_fiche_action&fiche[fiche_action]=supprimer&valeurs[source]='+source+'&valeurs[cible]='+cible+'&fiche[id_fiche]='+id_fiche+'&fiche[fiche_element]='+id_select);
			if(data=='OK'){
				select.options[select.selectedIndex]=null;
				select.selectedIndex=0;
				select.onchange();
			}
		}
	}
}

function sousFiche_majSelect(id_select, value, name){
	var select=document.getElementById(id_select+'_select');
	if(select){
		for(var i=0;i<select.options.length;i++){
			if(select.options[i].value==value){
				select.options[i].text=name;
				break;
			}
		}
	}
}


/* Fonction supprimant les caractère blanc de début et fin de chaines (espace,
* retour chariot, tabulation, saut de ligne, saut de page). */
function trim(string){
	if(typeof(string)=='string'){
		return string.replace(/(^\s*)|(\s*$)/g,'');
	} else {
		return ''; 
	}
} 

/* Fonction spécifique pourles liste, ouvre une popup pour changer les valeurs
*  d'une liste contenu dans une table */
function liste_gestionValeur(){
	var table=document.getElementById('id_table_liste').value;
	var identifiant=document.getElementById('id_table_id').value;
	var champ=document.getElementById('id_table_champ').value;
	var couleur=document.getElementById('id_table_couleur').value;
	var limitation=document.getElementById('id_table_limitation').value;

	var nom='gestionListe';
	var url='module.php?module=fiche&page=gestion_liste&nom='+table+'&id='+identifiant+'&libelle='+champ+'&couleur='+couleur+'&limitation='+limitation;
  var param='directories=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no, width=100, height=100';
  var win=window.open(url,nom,param);
  win.focus();
}

/* Fonction obligeant a ce qu'un champ ait une taille minimal */
function taille_mini(input, nom, taille){
	var text=input.value;
	if(text.length>0 && text.length<taille){
		alert('Le champ "'+nom+'" ne peut être plus petit que '+taille+' caractère'+(taille>1 ? 's' : ''));
		input.focus();
	}
}

/* Fonction obligeant un champ à avoir une valeur dans une plage */
function plage(input, nom, min, min_inclu, max, max_inclu){
	var text=input.value;
	if(text.length>0){
		var value=parseFloat(text);
		var text_alert='Le champ "'+nom+'" doit avoir une valeur';
		var erreur=false;
		if(min!=null){
			if(max!=null){
				text_alert+=' entre '+min;
				if(min_inclu!=null){
					text_alert+=' (inclu)';
					if(value<min){
						erreur=true;
					}
				} else {
					if(value<=min){
						erreur=true;
					}
				}
				text_alert+=' et '+max;
				if(max_inclu!=null){
					text_alert+=' (inclu)';
					if(max<value){
						erreur=true;
					}
				} else {
					if(max<=value){
						erreur=true;
					}
				}
			} else {
				text_alert+=' supérieur à '+min;
				if(min_inclu!=null){
					text_alert+=' (inclu)';
					if(value<min){
						erreur=true;
					}
				} else {
					if(value<=min){
						erreur=true;
					}
				}
			}
		} else {
			if(max!=null){
				text_alert+=' inférieur à '+max;
				if(max_inclu!=null){
					text_alert+=' (inclu)';
					if(value<max){
						erreur=true;
					}
				} else {
					if(value<=max){
						erreur=true;
					}
				}
			}
		}
		
		if(erreur){
			alert(text_alert);
			input.focus();
		}
	}
}

/* Fonction qui ajoute une evenement sur l'appuie d'une touche : envoie le
*  formulaire si on appuie sur "Entrer", quand on est sur l'un des champs (sauf
*  les textarea). */
function valideAvecEntrer(){
	var inputs=document.getElementsByTagName('input');
	for(var i=0;i<inputs.length;i++){
		if(inputs[i].getAttribute('type')!='hidden'){
			if (inputs[i].addEventListener) {
			  inputs[i].addEventListener("keypress", function(evt){
				if(!evt) evt = window.event; 
				if (evt.keyCode==13)valid_recherche();
			}, false);
			} else if (inputs[i].attachEvent) {
			  inputs[i].attachEvent("onkeypress", function(evt){
				if(!evt) evt = window.event; 
				if (evt.keyCode==13)valid_recherche();
			});
			}
		}
	}
	var selects=document.getElementsByTagName('select');
	for(var i=0;i<selects.length;i++){

		if (selects[i].addEventListener) {
			  selects[i].addEventListener("keypress", function(evt){
				if(!evt) evt = window.event; 
				if (evt.keyCode==13)valid_recherche();
			}, false);
			} else if (selects[i].attachEvent) {
			  selects[i].attachEvent("onkeypress", function(evt){
				if(!evt) evt = window.event; 
				if (evt.keyCode==13)valid_recherche();
			});
			}
	}
}




/*==============================================================================
Ajout didier pour le processus de validation
==============================================================================*/

function ValidationFicheNonCarto() {

//Je r‚cupŠre toute les valeurs remplis de la fiche
    //en premier lieu les inputs
    var critere="";
    var mesinput=document.getElementsByTagName('input');
    for (var i = 0; i < mesinput.length; i++) {
        var h = mesinput[i];
        if (h.value!="") {
            separateur='&';
            //traitement des booleens
            if (h.name.substr(0,16)=="valeurs[booleen_") {
                if (h.checked) {
                    h.value="on";
                } else {
                    h.value="off";
                }
            }
            if (h.name.substr(0,6)=="userid") {
                monuserid=h.value;
            }
            critere=critere+separateur+h.name+'='+h.value;
        }
        

        
    }

alert(critere);
  //en second lieu les select    
   var critere2="";
   var meselect=document.getElementsByTagName('select');
   for (var i = 0; i < meselect.length; i++) {
        var h = meselect[i];
        if (h.value!="") {
             separateur='&';
            critere=critere+separateur+h.name+'='+h.value;
            
        }
   }

//alert(critere2);

  //en troisiŠme lieu les textarea
  var critere3="";
  var mestextarea=document.getElementsByTagName('textarea');
  for (var i = 0; i < mestextarea.length; i++) {
    var h = mestextarea[i];
    if (h.value!="") {
        separateur='&';
        critere=critere+separateur+h.name+'='+h.value;
    }
  /*  if (h.name.substr(0,16)=="commentairemodif") {
        commentairemodif=h.value;
    }*/
  }
//alert(critere3);

  //A ce niveau j'ai r‚cup‚r‚ toutes les valeurs du formulaire
//Rappel des variables qui existent dans tous les forumulaires avec un exemple
/*
module=fichenoncarto
page=index_fiche
fiche[fiche_action]=enregistrement
fiche[id_fiche]=25 --> id de la fiche xml
ajout=true
valeurs[identifiant]=93
valeurs["texte_7"]=xxxxxx
valeurs["flottant_1"]=00000
valeurs["booleen_1"]=on
valeurs=["liste_1"]=42
*/

    //d‚finition de l'url de traitement
    var url='./fiche/validation.php?';
    //definition des criteres
    //critere='userid='+monuserid+'&commentairemodif='+commentairemodif;
    //d‚finintion de la destination pour ‚crire
    var id_ecrire='idniv1';
    var id_niveau='idniv1';
    
    url=url+critere;
    
    alert(url);
    
         //MAJ de l'onglet critere    
	  var http_request = false;
		//cr‚er une instance (un objet) de la classe d‚sir‚e fonctionnant sur plusieurs navigateurs
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');//un appel de fonction suppl‚mentaire pour ‚craser l'en-tˆte envoy‚ par le serveur, juste au cas o— il ne s'agit pas de text/xml, pour certaines versions de navigateurs Mozilla
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        
        if (!http_request) {
            alert('Abandon :( Impossible de cr‚er une instance XMLHTTP');
            return false;
        }
        http_request.onreadystatechange = function() { traitementReponseCritere2(http_request,id_ecrire); } //affectation fonction appel‚e qd on recevra la reponse
    		// lancement de la requete
    		http_request.open('POST', url, true);
    		//changer le type MIME de la requˆte pour envoyer des donn‚es avec la m‚thode POST ,  !!!! cette ligne doit etre absolument apres http_request.open('POST'....
    		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');;
    		obj=document.getElementById(id_niveau);
        http_request.send(critere);
     
    
    //-->enregistrement de la demande de modification dans validation_fiche
    
    //-->enregistrement de la demande dans validation champs
      
  
  
  
}

function traitementReponseCritere2(http_request,id_ecrire) {
  	var affich="";
  	if (http_request.readyState == 4) {
    		if (http_request.status == 200) {
    			 // cas avec reponse de PHP en mode texte:
    			 //chargement des elements re‡us dans la liste
    			 var affich_list=http_request.responseText;
    			 obj = document.getElementById(id_ecrire); 
           obj.innerHTML = affich_list;
    		}	else {
           alert('Un problŠme est survenu avec la requˆte.');
        }
    }
}
