/*******************************************************
* Interoge la base de données et remet un tableau pour une action précise
********************************************************/
function tableauAction(cmpId, i,j) {

	var descr = tableau[i][j];
	var wind = Ext.getCmp(cmpId);
	var titre = "description de l'action";

    if (Ext.isObject(wind)){
        wind.show();
        wind.expand();
        wind.body.update(descr);
    }else{
        var wind = new Ext.Window({
            id:cmpId,
			title:titre,
			border:false,
            closable:true,
            layout:'fit',
            width:800,
//            collapsible:true,
            html:descr
        });
        wind.show();
        wind.expand();
        wind.center();
    }
}


/*******************************************************
* Change les paramètres selon le système de coordonnées choisi
********************************************************/
function changeSystemCoord (EPSG, test) {
	var depart;
	var fin = new Proj4js.Proj('EPSG:' + EPSG);
	if (test) {
		depart = new Proj4js.Proj('EPSG:' + EPSG);
	} else {
		depart = new Proj4js.Proj('EPSG:4326');
	}
	var temp;
	// conversion de la vue de départ
	temp = new Proj4js.Point(coordVueDepart[0], coordVueDepart[3]);
	Proj4js.transform(depart, fin, temp);
	coordVueDepart[0] = temp.x;
	coordVueDepart[3] = temp.y;
	temp = new Proj4js.Point(coordVueDepart[2], coordVueDepart[1]);
	Proj4js.transform(depart, fin, temp);
	coordVueDepart[2] = temp.x;
	coordVueDepart[1] = temp.y;
	
	// conversion du rectangle de recherche
	temp = new Proj4js.Point(coordRecherche[0], coordRecherche[3]);
	Proj4js.transform(depart, fin, temp);
	coordRecherche[0] = temp.x;
	coordRecherche[3] = temp.y;
	temp = new Proj4js.Point(coordRecherche[2], coordRecherche[1]);
	Proj4js.transform(depart, fin, temp);
	coordRecherche[2] = temp.x;
	coordRecherche[1] = temp.y;
	
	//Conversion des zoom pour les CLBV
	for (var i=0; i<centreCLBV.length; i++) {
		temp = new Proj4js.Point(centreCLBV[i][0], centreCLBV[i][3]);
		Proj4js.transform(depart, fin, temp);
		centreCLBV[i][0] = temp.x;
		centreCLBV[i][3] = temp.y;
		temp = new Proj4js.Point(centreCLBV[i][2], centreCLBV[i][1]);
		Proj4js.transform(depart, fin, temp);
		centreCLBV[i][2] = temp.x;
		centreCLBV[i][1] = temp.y;
	}
} 

/*******************************************************
* Sépare les mots d'une chaine de caractère et les met dans une array
********************************************************/
function separeArray(texte) {
var mot;
var array=[];
var debRecherche = 0;
// On remplace les "-" par des " "
texte = texte.replace(/-/g," ");
// On remplace les accents et les cédilles
var caracDeb = ["à","À","â","Â","é","É","è","È","ê","Ê","ë","Ë","ï","Ï","ô","Ô","ç","Ç"];
var caracFin = ["a","A","a","A","e","E","e","E","e","E","e","E","i","I","o","O","c","C"];
for(var i=0; i <= caracDeb.length-1; i++) {
	while(texte.indexOf(caracDeb[i]) >= 0){
		texte = texte.replace(caracDeb[i], caracFin[i]);
	}
}

//On parcours le texte recherché pour trouver les blancs
while(texte.indexOf(" ", debRecherche) >= 0){
	mot = texte.substring(debRecherche, texte.indexOf(" ", debRecherche));
	mot = mot.replace(/\s+/g,"");
	// tous les mots du résultats ont la première lettre en majuscule, il faut donc le faire aussi
	array[array.length] = mot.substring(0,1).toUpperCase() + mot.substring(1);
	debRecherche = texte.indexOf(" ", debRecherche) + 1;
}
mot = texte.substring(debRecherche);
	mot = mot.replace(/\s+/g,"");
array[array.length] = mot.substring(0,1).toUpperCase() + mot.substring(1);

return array;
}

/*******************************************************
* Ajouter une couche dans map au bon endroit selon son emplacement dans layers
********************************************************/
function addLayerChecked(node) {
	if (map.layers.length >= maxCouches) {
		var msg = "OpenLayers ne permet pas l'affichage d'un trop grand nombre de couches. ";
		msg += "Nous avons donc limité ce nombre à 70 et vous avez atteint cette limite. ";
		msg += "Avez-vous vraiment besoin d'afficher toutes ces couches? ";
		msg += "<br>Enlevez d'autres couches avant de pouvoir afficher celle-ci";
		Ext.Msg.alert("limite dépassée", msg);
		return;
	}
	var layer = getLayerByIdentFromMap(node);
	if (!layer) {
		for (var i=0; i<layers.length; i++) {
			if (layers[i].name == node) {
				map.addLayer(layers[i]);
				var j = 0;
				var deb = 0;
				while (map.layers[deb].name != layers[0].name) {
					 deb= deb+1;
				}
				while (j < i) {
					if (layers[j].visibility == true) {
						deb += 1;
					}
					j += 1;
				}
				var essai = map.getLayersByName(layers[i].name);
				map.setLayerIndex(map.getLayersByName(layers[i].name)[0], deb);
				if (nACTIVELAYER == node) {
					gACTIVELAYER = map.getLayerIndex(map.getLayersByName(node)[0]);
				}
				break;
			}
		}
	}
}

/*******************************************************
* Supprimer une couche dans map au bon endroit selon son emplacement dans layers
********************************************************/
function removeLayerChecked(node) {
	if (map.layers.length == maxCouches + 1) {
		return;
	}
	for (var i=0; i<layers.length; i++) {
		if (layers[i].name == node) {
			if (nACTIVELAYER == node) {
				gACTIVELAYER = -1;
			}
			map.removeLayer(layers[i]);
			break;
		}
	}
}

/*******************************************************
* Ajouter les couches visibles dans map
Pour limiter le nombre de couches ouvertes dans openlayer (le nombre maximal est environ 75)
********************************************************/
function addLayersVisible() {
	for (var i=0; i<layers.length; i++) {
		if (cVisible[i]) {
			map.addLayer(layers[i]);
		}
	}
}

/*******************************************************
* détruire une couche dans openlayer
********************************************************/
function ajouterCouche() {
	map.removeLayer
}
/*******************************************************
* Change la position du curseur d'opacité en fonction de la couche sélectionnée
********************************************************/
function adjustOpacityCursor(){
    if (gACTIVELAYER != -1) {
		var lop = map.layers[gACTIVELAYER].opacity;
	} else {
		var lop = 1;
	}
    sLayerOpacity.setValue(lop * 100);
}

/*******************************************************
* Recherche les informations sur la carte (position, projection, couches actives...)
********************************************************/
function getMapInfos(){
    var mapInfos = '';

    // get the informations about currently active layers
    activeLayers = map.getLayersBy('visibility', true);
    activeLayersList = '';
    baseLayersList = '';
    for (i=0; i<activeLayers.length; i++) {
        n = activeLayers[i].titleInfos ? activeLayers[i].titleInfos : activeLayers[i].name;
        o = ' (' + Math.round((activeLayers[i].opacity * 100)) + '%)';
        txt = n + o;
        if (activeLayers[i].isBaseLayer){
            baseLayersList += txt;
        }else{
            activeLayersList += txt + '<br>';
        }
    }

    mapInfos  = '<p><table>';
//    mapInfos += '<tr><td id="infosLabel">COUCHE ACTIVE</td><td id="infosValue">' + gACTIVELAYER + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Échelle de la carte</td><td id="infosValue">1 / ' + addCommas(Math.round(map.getScale())) + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Coordonnées ouest</td><td id="infosValue">' + map.getExtent().toArray()[0] + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Coordonnées sud</td><td id="infosValue">' + map.getExtent().toArray()[1] + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Coordonnées est</td><td id="infosValue">' + map.getExtent().toArray()[2] + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Coordonnées nord</td><td id="infosValue">' + map.getExtent().toArray()[3] + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Point centre : Longitude</td><td id="infosValue">' + map.getCenter().lon + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Point centre : Latitude</td><td id="infosValue">' + map.getCenter().lat + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Niveau de zoom</td><td id="infosValue">' + map.getZoom() + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Nombre de couches de données actives</td><td id="infosValue">' + (activeLayers.length) + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Fond de carte sélectionné</td><td id="infosValue">' + baseLayersList + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Couches sélectionnées</td><td id="infosValue">' + activeLayersList.slice(0, -4) + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Projection de la carte</td><td id="infosValue">' + map.getProjection() + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Largeur de la carte</td><td id="infosValue">' + map.getSize().w + ' pixels' + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Hauteur de la carte</td><td id="infosValue">' + map.getSize().h + ' pixels' + '</td></tr>';
    mapInfos += '<tr><td id="infosLabel">Unités de la carte</td><td id="infosValue">' + map.getUnits() + '</td></tr>';

    mapInfos += '</table></p>';

    return mapInfos;
}

/*******************************************************
* Met à jour les informations sur la carte (position, projection, couches actives...)
********************************************************/
function updateMapInfos(){
    // Update map infos panel content to reflect new content.
    var mapInfos = getMapInfos();
    var wMapInfos = Ext.getCmp('wMapInfos');

    if (Ext.isObject(wMapInfos)){
        wMapInfos.body.update(mapInfos);
    }
}

/*******************************************************
* Affiche les information sur la carte dans une fenêtre
********************************************************/
function displayMapInfos(){
    cmpId = 'wMapInfos';

    mapInfos = getMapInfos();

    var wMapInfos = Ext.getCmp(cmpId);
    if (Ext.isObject(wMapInfos)){
        wMapInfos.body.update(mapInfos);
//        wMapInfos.center();
    }else{
        wMapInfos = new Ext.Window({
             id:cmpId
            ,title:'Map Informations'
            ,border:false
            ,closable:true
            ,layout:'fit'
            ,width:350
            ,height:400
            ,autoScroll:true
            ,html:mapInfos
            ,plain:true
        });
        wMapInfos.show();
        wMapInfos.expand();
        wMapInfos.center();
    }
}

/*******************************************************
* Agrandir la vue au zoom demandé
********************************************************/
function getZoomToScale(){
    cmpId = 'wGetZoomToScale';

    wGetZoomToScale = new Ext.Window({
         id:cmpId
        ,title:'Entrez l\'échelle ...'
        ,border:false
        ,closable:true
        ,layout:'fit'
        ,width:200
        ,height:100
        ,plain:true
        ,items:[
            new Ext.form.NumberField({
                 name:"tfGetZoomToScale"
                ,id:"tfGetZoomToScale"
                ,width:20
                ,allowDecimals:false
                ,allowNegative:false
                ,maxLength:8
                ,maxLengthtext:'Please, enter maximum of 8 digits'
                ,nanText:'Invalid character(s). Please, only use digits'
            })
        ]
        ,buttons: [{
                 text: 'Changer la vue'
                ,id:'bzoomToScale'
                ,handler:function(){
                    var search = Ext.get('tfGetZoomToScale').dom.value;
                    map.zoomToScale(search);
                    wGetZoomToScale.close();
                }
            }]
        });
        wGetZoomToScale.show();
        wGetZoomToScale.expand();
        wGetZoomToScale.center();
        Ext.getCmp('tfGetZoomToScale').on("specialkey",function(t,e){
            if(e.getKey()==Ext.EventObject.RETURN){
                var search = Ext.get('tfGetZoomToScale').dom.value;
                map.zoomToScale(search);
                wGetZoomToScale.close();
            }
        });
}

/***********************************************************
* Called every time map is zoomed in or out
*************************************************************/
function mapHasZoomed(event){
    document.getElementById("dfScale").innerHTML = 'Scale : 1 / ' + addCommas(Math.round(map.getScale()));
}

/***********************************************************
* Called each time map is moved. This occurs very often.
* **TODO: filter type of move
*************************************************************/
function mapHasMoved(event){
    updateMapInfos();
}

/***********************************************************
*  Met à jour la légende Non utilisée pour l'instant mais en attente
*************************************************************/
function updateLegend(){
    legend = '<table>';

    // Loop through OpenLayers layers list to select visible ones.
    // If layer is visible, add entry into legend.
    for (i=0; i<map.layers.length; i++){
        if (map.layers[i].visibility){
            n = map.layers[i].titleInfos ? map.layers[i].titleInfos : map.layers[i].name;
            tr = '<tr><td id="infosLabel">' + '<img src="images/home.png">' + '</td><td id="infosValue">' + n + '</td></tr>';
            legend += tr;
        }
    }
    legend += '</table>';

    // Update legend panel content to reflect selected layers.
    var c = Ext.getCmp('wLegend');
    if (Ext.isObject(c)){
        displayMsg(c, legend);
    }
}

/***********************************************************
*  Creer la couche des marqueurs et l'afficher sur la carte
*************************************************************/
function ajouterMarqueur(x,y){
	markers.clearMarkers();
	var size = new OpenLayers.Size(20,34);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    var icon = new OpenLayers.Icon('images/aqua.png',size,offset);
	
	markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(x,y),icon));
	markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(x,y),icon.clone()));
}
	
/***********************************************************
*  Fonction d'affichage du fond de carte sélectionné
*************************************************************/
function displayBaseMap(baseMap){
	map.setCenter(map.getCenter(), map.getZoom());
	map.setBaseLayer(baseMap);
	map.baseLayer.setVisibility(true);
	//updateLegend();
	updateMapInfos();
}

/***********************************************************
*  Fonction d'affichage d'une description d'un item de légende
*************************************************************/
function afficherDescription(item, largeur, icone) { // isaide permet de déterminer si la fonction est appelée depuis le menu aide. Si oui il ne faut pas afficher d'icone
    titre = item.titre;
    cmpId = item.ident;
    descr= item.descr;

    var wind = Ext.getCmp(cmpId);
	
	// n'affiche pas l'icone si il n'y a pas d'icone
	if (!icone){
		titre = titre + '<br><img src="images/legende/' + cmpId + '.png">';
	}

    if (Ext.isObject(wind)){
        wind.show();
        wind.expand();
        wind.body.update(descr);
    }else{
        var wind = new Ext.Window({
            id:cmpId,
			title:titre,
			border:false,
            closable:true,
            layout:'fit',
            width:largeur,
//            collapsible:true,
            html:descr
        });
        wind.show();
        wind.expand();
        wind.center();
    }
}

/***********************************************************
* Fonction pour zoomer sur une entitée à un niveau de zoom
*************************************************************/
function focusMapToPoint(lon, lat, niveauZoom) {
//        var niveauZoom = map.getZoom() > 7 ? map.getZoom() : 7;
//        jQuery.scrollTo(jQuery('a[name="viewer"]'), 300);
  var lieu = new OpenLayers.LonLat(lon,lat);
  map.setCenter(lieu, niveauZoom);
//		  ajouterMarque(lieu);
}

/**********************************************************
* détermine si le point est dans la vue avant de centrer
************************************************************/
function isInMap(x,y){
	if(x > map.getExtent().toArray()[0] && x < map.getExtent().toArray()[2] && y > map.getExtent().toArray()[1] && y < map.getExtent().toArray()[3]){
		return true;
	}else{
		return false;
	}
}

/**********************************************************
* cadrer sur un point selon ESPG
************************************************************/
function cadrerPointEPSG(p_x, p_y, epsg){
//clearMarkers();
ajouterMarqueur(p_x,p_y);
if (!isInMap(p_x,p_y)){
	map.setCenter(new OpenLayers.LonLat(p_x, p_y), map.getZoom());
}
//map.setCenter(new OpenLayers.LonLat(p_x, p_y), 11);
}

/**********************************************************
* cadrer au centre d'un rectangle
************************************************************/
function cadrerCentreEtendue(p_xmin, p_ymin, p_xmax, p_ymax, epsg)
{
	if (Number(p_xmin)<0){
	  var x=Number(p_xmin)-((Number(p_xmin)-Number(p_xmax))/2);
	}else{
	  var x=Number(p_xmin)+((Number(p_xmax)-Number(p_xmin))/2);
	}
	var y=Number(p_ymin)+((Number(p_ymax)-Number(p_ymin))/2);
	ajouterMarqueur(x,y);
	if (!isInMap(x,y)){
		map.setCenter(new OpenLayers.LonLat(x, y), map.getZoom());
	}
}

/**********************************************************
* cadrer sur un rectangle
************************************************************/
function cadrerEtendue(p_xmin, p_ymin, p_xmax, p_ymax, epsg)
{
	if (Number(p_xmin)<0){
	  var x=Number(p_xmin)-((Number(p_xmin)-Number(p_xmax))/2);
	}else{
	  var x=Number(p_xmin)+((Number(p_xmax)-Number(p_xmin))/2);
	}
	var y=Number(p_ymin)+((Number(p_ymax)-Number(p_ymin))/2);
	ajouterMarqueur(x,y);
	map.zoomToExtent(new OpenLayers.Bounds(p_xmin,p_ymin, p_xmax,p_ymax));
}

/**********************************************************
* Afficher la réponse GetFeatureInfo dans un popup
************************************************************/
function setHTML(response) {

	if (response == "false") {
		reponse = "Sélectionnez et affichez la couche que vous voulez interroger. <br> <br> Voir le <a href='http://70.38.64.90:8080/video/metadonnees.swf' target='_blank'>démo</a> pour sélectionner une couche";
	} else {
		var couche = map.layers[gACTIVELAYER];
		var reponse = html_entity_decode(response.responseText)
		if (reponse.indexOf("GetFeatureInfo") < 0 ) {
			reponse = "Aucune couche sélectionnée ou pas de métadonnées disponible pour '" + couche.titleInfos + "'.  </br> </br> Si vous voulez intérroger une autre couche, </br> il faut d'abord la sélectionner";
		} else if (reponse.indexOf("Layer") > 0) {
			reponse = parseFeatureInfo(reponse);
			// si la couche est un CLBV Mettre CLBV en titre
			var couchename = couche.name.substring(0,5);
			if (couchename == "clbv_") {
				reponse = "CLBV" + "</br></br>" + reponse;
			} else {
				reponse = couche.titleInfos + "</br></br>" + reponse;
			}
		} else {
			reponse = "Aucune information à cet endroit pour la couche '" + couche.titleInfos + "'.  </br> </br> Vérifiez que la couche est bien sélectionnée</br> et que vous avez cliqué au bon endroit";
		}
	}
	var popup = new OpenLayers.Popup.FramedCloud(
			"chicken", 
			map.getLonLatFromPixel(clic),
			null,
			reponse,
			null,
			true
		);
	
	map.addPopup(popup);
}
/**********************************************************
* Arranger la forme de la réponse avant l'affichage
************************************************************/
function isInArray (array, param) {
	var test = false;
	for (var i=0; i<array.length; i++) {
		if (array[i] == param) {
			test = true;
		}
	}
	return test
}


/**********************************************************
* Arranger la forme de la réponse avant l'affichage
************************************************************/
function parseFeatureInfo(reponse){
	var posdeb;
	var posfin;
	var temp;
	var tableau = "<table>";
	var champ = new Array();
	var type = new Array();
	var layer = new Array();
	var couche = map.layers[gACTIVELAYER];
	var reponseInt;
	var push;
	
	posdeb = reponse.indexOf("Layer '");
	while (posdeb > 0) {
		posdeb = posdeb + 7;
		posfin = reponse.indexOf("'", posdeb);
		push = reponse.substring(posdeb,posfin);
		posfin = reponse.indexOf("Layer '", posdeb);
		if (posfin == -1) {
			reponseInt = reponse.substring(posdeb);
		} else {
			reponseInt = reponse.substring(posdeb,posfin);
		}
		temp = posdeb;
		posdeb = reponseInt.indexOf("=")
		while (posdeb > 0) {
			posfin = reponseInt.lastIndexOf(" ", posdeb-2);
			champ.push(reponseInt.substring(posfin+1,posdeb-1));
			posfin = reponseInt.indexOf("'", posdeb + 3);
			type.push(reponseInt.substring(posdeb+3,posfin));
			posdeb = reponseInt.indexOf("=", posdeb + 1);
			layer.push (push);
		}
		posdeb = reponse.indexOf("Layer '", temp + 1);
	}
	if (couche.name == "BASSIN_ORDRE3_2" || couche.name == "BASSIN_ORDRE4_2" || couche.name == "BASSIN_ORDRE5_2") {
		tableau += "<tr> <td id='infoFeatureTitle'>" + champ[champ.length-1] + "</td> <td id='infoFeatureDescr'>" + type[type.length-1] + "</td> </tr>";
		tableau += "<tr> <td id='infoFeatureTitle'> BV d'ordre 2 </td> <td id='infoFeatureDescr'>" + type[0] + "</td> </tr>";
	} else if (couche.name == "MUNICIPALITE_2" || couche.name == "MRC_COMTE_2") {
		tableau += "<tr> <td id='infoFeatureTitle'>" + champ[champ.length-2] + "</td> <td id='infoFeatureDescr'>" + type[type.length-2] + "</td> </tr>";
		tableau += "<tr> <td id='infoFeatureTitle'>" + champ[champ.length-1] + "</td> <td id='infoFeatureDescr'>" + type[type.length-1] + "</td> </tr>";
		if (couche.name == "MUNICIPALITE_2") {
			tableau += "<tr> <td id='infoFeatureTitle'> MRC </td> <td id='infoFeatureDescr'>" + type[2] + "</td> </tr>";
		}
		tableau += "<tr> <td id='infoFeatureTitle'> Région administrative </td> <td id='infoFeatureDescr'>" + type[0] + "</td> </tr>";
	} else if (couche.name == "hydrographie") {
		var test = false;
		for (var i=0; i<layer.length; i++) {
			if (layer[i] == "REGIONHYDRO_3" && type[i]!="") {
				tableau += "<tr> <td id='infoFeatureTitle'> Nom </td> <td id='infoFeatureDescr'>" + type[i] + "</td> </tr>";
				test = true;
				break;
			}
		}
		if (test == false) {
			for (var i=0; i<layer.length; i++) {
				if (layer[i] == "RIVIERENOMME_1" && type[i]!="") {
					tableau += "<tr> <td id='infoFeatureTitle'> Nom </td> <td id='infoFeatureDescr'>" + type[i] + "</td> </tr>";
					break;
				}
				if (layer[i] == "COURSDEAUNOMME_1" && type[i]!="") {
					tableau += "<tr> <td id='infoFeatureTitle'> Nom </td> <td id='infoFeatureDescr'>" + type[i] + "</td> </tr>";
					break;
				}
			}
		}
	} else {
		for (var i=0; i < champ.length; i++) {
			if (type[i] == "nomcouche") {
				tableau += "</table></br>" + champ[i] + "</br></br><table>";
			} else {
				tableau += "<tr> <td id='infoFeatureTitle'>" + champ[i] + "</td> <td id='infoFeatureDescr'>" + type[i] + "</td> </tr>";
			}
		}
	}
	tableau += "</table>";
	
	var base = 	["Annee",	"codepost",		"COTE", "COTE_3", 	"COTE_6", 	"Cours_eau", 	"Descriptio", 	"Fac_limita", 		"Fournisseu", 	"FOURNISSEU",	"LATITUDE", "LONGITUDE", "MES_mg_l", 	"MUNICIPALI", 	"NOM", "NomBassin", "NOM_LAC", 	"NOM_CLBV", "PERIMETRE", 	"PLAN_EAU", 	"PTOT_mg_l", 				"SECCHI_cm", 	"SOURCE", "SupKm2", 			"SUP_KM2", 			"SUP_M2",			"TEMP_C", 			"TYPE_MH", 	"TypeTexte",				"CF_ufc" ];
	var nom = 	["Année",	"Code postal", 	"Côte", "Côte", 	"Côte", 	"Cours d'eau",	"Description", 	"Facteur Limitant", "Fournisseur", 	"Fournisseur",	"Latitude", "Longitude", "MES (mg/l)", 	"Municipalité", "Nom", "Nom", 		"Nom", 		"Nom",		"Périmètre", 	"Plan d'eau", 	"Phosphore total (mg/l)", 	"Secchi (cm)", 	"Source", "Superficie (km2)", 	"Superficie (km2)", "Superficie (km2)",	"Température (°C)", "Type", 	"Type de milieu humide",	"UFC (100ml)"];
	
	for (var i=0; i<base.length; i++) {
		test = base[i] + "<";
		
		while (tableau.indexOf(test) > 0) {
			tableau = tableau.replace(test,nom[i]+"<");
		}
	}
	return tableau;
}

function ajoutpopup(texte, xcoord, ycoord, epsg, paramaction) {
	var depart = new Proj4js.Proj('EPSG:' + epsg);
	var fin = new Proj4js.Proj('EPSG:' + systemeCoord); // systemecoord est définit dans cogesaf.js
	var temp = new Proj4js.Point(xcoord, ycoord);
	var table;
	
	if (paramaction) {
		table = paramaction.split("/");
		texte = "<a href='javascript:tableauAction(\"" + table[0] + "/" + table[1] + "\"," + table[2] + "," + table[3] + ")' >" + texte + "</a>";
	}
	
	Proj4js.transform(depart, fin, temp);
	xcoord = temp.x;
	ycoord = temp.y;
	var popup = new OpenLayers.Popup.FramedCloud(
			"chicken", 
			new OpenLayers.LonLat(xcoord,ycoord),
			null,
			texte,
			null,
			true
		);
	map.addPopup(popup);
}
