/**
 * @author bphilippot
 */

var URL_WEB       = 'http://www.parcdesbauges.com:8080/pnrbauges_site/web/app';
var URL_MAPSERV   = 'http://www.parcdesbauges.com:8080/cgi-bin/mapserv';
var URL_TILECACHE = 'http://www.parcdesbauges.com:8080/cgi-bin/tilecache-2.01/tilecache_http_server.py';
var DIR_MAP       = '/var/www/wwwroot/pnrbauges_site/web/app/map';

OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
OpenLayers.ImgPath   = URL_WEB+'/../openlayers/img/';

var map, tree, selectedFeature, popup, popupRando, selectControl, ortho_opacity, orthoLayer, url, pixel;

var style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
style_mark.externalGraphic = URL_WEB+"/icons/transparent.gif";
style_mark.graphicWidth = 20;
style_mark.graphicHeight = 20;
style_mark.graphicOpacity = 1;

var select_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
select_style.externalGraphic = URL_WEB+"/icons/speedcamera.png";
select_style.graphicWidth = 20;
select_style.graphicHeight = 20;
select_style.graphicOpacity = 1;

var pointStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
pointStyle.fillColor = "red";

var randoStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
randoStyle.strokeWidth = 3;
randoStyle.strokeOpacity = 1;

var cpt_layer = 0;
var wfs_categories;
var poi_to_select = [];
var disable_anim = true;

function changeBaseLayer()
{
	var fondLayer = map.getLayersByName("Fond cartographique")[0];
	if (fondLayer.isBaseLayer)
	{
		map.setBaseLayer(orthoLayer);
		fondLayer.isBaseLayer = false;
		orthoLayer.setVisibility(true);
		orthoLayer.isBaseLayer = true;
		map.raiseLayer(map.getLayersByName("Rando")[0], 1);
		map.raiseLayer(map.getLayersByName("poi")[0], 2);
	} else {
		map.setBaseLayer(fondLayer);
		orthoLayer.isBaseLayer = false;
		fondLayer.setVisibility(true);
		fondLayer.isBaseLayer = true;
		map.raiseLayer(map.getLayersByName("Rando")[0], 1);
		map.raiseLayer(map.getLayersByName("poi")[0], 2);
	}
}

OpenLayers.loadURL(
  URL_WEB+"/script/categories.php", null, null, 
  function(request){
    var format = new OpenLayers.Format.JSON();
	  var features = format.read(request.responseText);
	  wfs_categories = features.object;
	}, function(request) {
		alert('Impossible de déterminer les catégories SITRA de POI disponibles');
	}
);

OpenLayers.Control.Hover = OpenLayers.Class(OpenLayers.Control, {                

  defaultHandlerOptions: {
    'delay': 10,
    'pixelTolerance': 4,
    'stopMove': false
  },

  initialize: function(options)
  {
    this.handlerOptions = OpenLayers.Util.extend(
      {}, this.defaultHandlerOptions
    );
    OpenLayers.Control.prototype.initialize.apply(
      this, arguments
    ); 
    this.handler = new OpenLayers.Handler.Hover(
      this,
      {'pause': this.onPause, 'move': this.onMove},
      this.handlerOptions
    );
  }, 

  onPause: function(evt)
  {
  	pixel = evt.xy;
  	if (map.getLayersByName('Rando')[0].visibility)
  	{
      url =  map.getLayersByName('Rando')[0].getFullRequestString({
    		SERVICE: "WMS",
    		VERSION: "1.1.1",
        REQUEST: "GetFeatureInfo",
        EXCEPTIONS: "application/vnd.ogc.se_xml",
        BBOX: map.getExtent().toBBOX(),
        X: evt.xy.x,
        Y: evt.xy.y,
        QUERY_LAYERS: "Rando",
        LAYERS: "Rando",
        INFO_FORMAT: 'application/vnd.ogc.gml',
        WIDTH: map.size.w,
        HEIGHT: map.size.h
      });
      OpenLayers.loadURL(url, '', this, popup_rando);
    }
  },

  onMove: function(evt) {
    // if this control sent an Ajax request (e.g. GetFeatureInfo) when
    // the mouse pauses the onMove callback could be used to abort that
    // request.
    if (map.div.style.cursor == "pointer")
    	map.div.style.cursor = "auto";
  }
  
});

function popup_rando(response)
{
	var format = new OpenLayers.Format.XML();
  var doc = format.read(response.responseText);
  var fid = OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("ogc_fid")[0]);
  var feature;
  if (fid)
  	feature = getFeatureById(fid);
  	
  if (feature)
  {
  	if (map.div.style.cursor == "auto")
  		map.div.style.cursor = "pointer";

  	var id = OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("id")[0]);
  	var nom = OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("nom")[0]);
  	var description = OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("description")[0]);
  	var nb_jours = OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("nb_jours")[0]);
    var deniv;
    if (OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("denivele")[0]) == "1") {
    	deniv = "< 600m";
    } else if (OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("denivele")[0]) == "2"){
    	deniv = "600m &agrave; 1000m";
    } else {
    	deniv = "> 1000m";
    }
    var rando_terroir;
    if (OpenLayers.Util.getXmlNodeValue(doc.getElementsByTagName("fromage")[0]) == "t") {
    	rando_terroir = "Oui";
    } else {
    	rando_terroir = "Non";
    }
	    
	    
	    
    if (popupRando != null)
    {
		  map.removePopup(popupRando);
	    popupRando.destroy();
	    popupRando = null;
    }
    if (popupRando == null && popup == null)
    {
      var styledFeature = map.getLayersByName('Rando')[0].styledFeatures[0];
      if (styledFeature)
      {
        styledFeature.style.strokeOpacity = 1;
	      styledFeature.style.strokeColor = "#" + styledFeature.attributes.web;
	      styledFeature.style.strokeWidth = 3;
	      map.getLayersByName('Rando')[0].drawFeature(styledFeature);
	      map.getLayersByName('Rando')[0].styledFeatures = [];
      }
      feature.style.strokeOpacity = 0.6;
      feature.style.strokeColor = "#" + feature.attributes.web;
      feature.style.strokeWidth = 3;
      map.getLayersByName('Rando')[0].drawFeature(feature);
      map.getLayersByName("Rando")[0].styledFeatures.push(feature);
      popupRando = new OpenLayers.Popup.Anchored(
        "popup_rando", 
	      map.getLonLatFromPixel(pixel),
        new OpenLayers.Size(170,84),
        '<div id="infobulle"><a id="infobulle_fermeture" onclick="close_popupRando_fct()"><img src="/templates/pnr_navigation/images/bouton_fermeture.gif"/></a><p id="infobulle_titre">'+nom+'</p><p id="infobulle_desc">Dur&eacute;e : '+nb_jours+' jour(s) <br>D&eacute;nivel&eacute; : '+deniv+'<br>Randonn&eacute;e Terroir : '+rando_terroir+'</p><p id="infobulle_lien"><a id="popupBox" class="thickbox" href="/php/fichepostgre.php?objet='+id+'&KeepThis=true&TB_iframe=true&height=480&width=860">Plus d\'infos</a></p></div>',
        null, false, onPopupRandoClose
      );	    

      map.addPopup(popupRando);
      TB_init_carto();
      popupRando.events.register("mouseout", popupRando, close_popupRando); 
    }
  } // end if (feature)
  
}


function TB_init_carto()
{
	$("a.thickbox").click(function(event){
		event.preventDefault();
		this.blur();
		var caption = this.title || this.name || "";
		var group = this.rel || false;
		TB_show(caption, this.href, group);
	}); 
}
    
/*
 * When a popup is closed, unselect the feature
 */
function onPopupRandoClose(evt)
{
    map.removePopup(popupRando);
    popupRando.destroy();
    popupRando = null;
}

/*
 * Close a popup on mouseout
 */
function close_popupRando(evt)
{
  if (!__hbsCheckMouseLeave(popupRando.div, evt))
    return;

  map.removePopup(popupRando);
  popupRando.destroy();
  popupRando = null;
  OpenLayers.Util.safeStopPropagation(evt);
    
  var feature = map.getLayersByName('Rando')[0].styledFeatures[0];
	if (feature)
	{
		feature.style.strokeOpacity = 1;
  	feature.style.strokeColor = "#" + feature.attributes.web;
  	feature.style.strokeWidth = 3;
  	map.getLayersByName('Rando')[0].drawFeature(feature);
  }
  map.getLayersByName('Rando')[0].styledFeatures = [];
}

/*
 * Close a rando popup 
 */
function close_popupRando_fct()
{
  map.removePopup(popupRando);
  popupRando.destroy();
  popupRando = null;
    
  var feature = map.getLayersByName('Rando')[0].styledFeatures[0];
	if (feature)
	{
		feature.style.strokeOpacity = 1;
  	feature.style.strokeColor = "#" + feature.attributes.web;
  	feature.style.strokeWidth = 3;
  	map.getLayersByName('Rando')[0].drawFeature(feature);
  }
  map.getLayersByName('Rando')[0].styledFeatures = [];
}

/*
 * Triggers when rando features are loaded
 */
function on_rando_load()
{
  if (document.getElementById('chargement'))
    document.getElementById('chargement').innerHTML='';
    
  if (randoZoom)
    recenter_on_rando();
    
  randoZoom = false;
}

/*
 * Recenter the map on Randos ids
 */
function recenter_on_rando()
{
  var geomArray = [];
  var featuresRandoLayer = map.getLayersByName("Rando")[0].features;
  for(var i=0; i < featuresRandoLayer.length; i++) {
    geomArray.push(featuresRandoLayer[i].geometry);
  }
  var geomCollection = new OpenLayers.Geometry.Collection(geomArray);
  geomCollection.calculateBounds();
  var randoBounds = geomCollection.bounds;
  recenter(randoBounds.toBBOX());
}

/*
 * Recenter the map on a specific area 
 */
function recenter(coords)
{
	disable_anim = false;
	if (coords != "null")
	{
		var bboxArray = coords.split(",");
		var bounds = new OpenLayers.Bounds(
		  bboxArray[0],bboxArray[1],bboxArray[2],bboxArray[3]
		);
		var center = bounds.getCenterLonLat();
    if (map.baseLayer.wrapDateLine)
    {
      var maxExtent = map.getMaxExtent();
      bounds = bounds.clone();
      while (bounds.right < bounds.left) {
        bounds.right += maxExtent.getWidth();
      }
      center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
    }
    map.setCenter(center, map.getZoomForExtent(bounds, true));  
	}
} 

/*
 * Recenter the map on GPS coordinates
 */
function recenter_gps(lon, lat)
{
	var gps_style = OpenLayers.Util.extend({}, style_mark);
	gps_style.externalGraphic = URL_WEB+"/icons/souris_fleche.gif";
	gps_style.graphicWidth = 30;
	gps_style.graphicHeight = 30;
	gps_style.graphicOpacity = 1;
	var gpsLayer = new OpenLayers.Layer.Vector("GPS", {style: gps_style});
	
	OpenLayers.loadURL(
	  URL_WEB+"/script/transform.php?x="+lon+"&y="+lat, 
	  null, 
	  null, 
	  function(request){
	    var format = new OpenLayers.Format.GeoJSON();
      var features = format.read(request.responseText);
      gpsLayer.addFeatures(features);
      gpsLayer.setVisibility(true);
	    map.addLayer(gpsLayer);
	    map.setCenter(
	      new OpenLayers.LonLat(features[0].geometry.x,features[0].geometry.y),0
	    );
		}, function(request) {
	    alert('ajax request failed');
		}
  );
}

/*
 * Highlight POIs and display specified layers
 */
function select_id(ids)
{
	if (document.getElementById('selection') == null)
	{
		document.getElementById('zone_tree').innerHTML = document.getElementById('zone_tree').innerHTML 
		  +"<INPUT id='selection' TYPE=CHECKBOX NAME=\"selection\" CHECKED onclick=\"change_visibility('selection')\">Sélection<Br>";
	}
	var idArray = ids.split(",");
	poi_to_select = idArray;
	var filter_string = "<Filter>";
	for (var i=0; i < idArray.length - 1; i++)
	{
		filter_string= filter_string + "<Or>";
	}
	for (var i=0; i < idArray.length; i++)
	{
		filter_string = filter_string 
		  +"<PropertyIsEqualTo><PropertyName>id</PropertyName><Literal>"
		  +idArray[i]+"</Literal></PropertyIsEqualTo>";
		if (i > 0)
			filter_string = filter_string + "</Or>";
	} 
	filter_string = filter_string + "</Filter>";
	var filter = {filter: filter_string};
	map.getLayersByName("poi")[0].mergeNewParams(filter);
	map.getLayersByName("poi")[0].setVisibility(true);
}

/*
 * Display only specified rando
 */
function select_rando_id(ids) {
	var idArray = ids.split(",");
	var filter_string = " IN ("+ids+")";
	var filter = {Id_FILTER: filter_string};
	map.getLayersByName("Rando")[0].mergeNewParams(filter);
	map.getLayersByName("Rando")[0].setVisibility(true);
	display_poi(["Rando"],ids);
	map.setCenter(new OpenLayers.LonLat(897000, 2084000),0);
}

/*
 * Given a feature id, return the feature if it exists in the features array
 */
function getFeatureById(featureId)
{
  var feature = null;
  for (var j=0; j < map.layers.length; j++)
  {
  	if (map.layers[j].CLASS_NAME == "OpenLayers.Layer.WFS")
  	{
      for(var i=0; i < map.layers[j].features.length; ++i)
      {
        if(map.layers[j].features[i].fid == featureId) {
          feature = map.layers[j].features[i];
          break;
        }
      }
    }
  }
  return feature;
}
  
/*
 * Test if a string is in an array
 */  
function is_in_array(tab,string)
{
	for (i=0; i < tab.length; i++)
	{
		if (tab[i] == string)
			return true;
	}
	return false;
}

/*
 * Tool to print extent of the visualized map
 */
function on_move()
{
	var xmin = map.getExtent().left;
	var ymin = map.getExtent().bottom;
	var xmax = map.getExtent().right;
	var ymax = map.getExtent().top;
	document.getElementById('extent').textContent = "Extent actuel de la carte : xmin="+xmin+" ymin="+ymin+" xmax="+xmax+" ymax="+ymax
	if (window.document.anim && disable_anim) {
		window.document.anim.SetVariable("desactiver", "1");
	}
	disable_anim = true;
}


/* 
 * Initialize scriptaculous slider
 */    
function init_slider()
{
  if (document.getElementById('id_handle_ortho'))
  { 
    // from the author's first demo of a vertical slider.  It begins disabled.
    var s2 = new Control.Slider(
      'id_handle_ortho',
      'id_track_ortho', 
      { axis:'horizontal' }
    );
    
    // Setting the callbacks later on
    ortho_opacity=0.001;
    s2.options.onChange = function(value){
      ortho_opacity=value;
      orthoLayer.setVisibility((ortho_opacity>=0.1));
      orthoLayer.setOpacity(ortho_opacity);
    };

    s2.options.onSlide = function(value){                                  
      ortho_opacity=value;
      orthoLayer.setVisibility((ortho_opacity>=0.1));
      orthoLayer.setOpacity(ortho_opacity);
    };
  }
} 

function loadMap() {

	/*** Map creation ***/
    map = new OpenLayers.Map('map', {
          controls: [
/*            new OpenLayers.Control.Navigation({zoomWorldIcon:true}),
            new OpenLayers.Control.PanPanel({zoomWorldIcon:true}),
            new OpenLayers.Control.ZoomPanel({zoomWorldIcon:true})*/
            new OpenLayers.Control.PanZoomBar({zoomWorldIcon:true})
          ],
          maxExtent: new OpenLayers.Bounds(854164, 2054948, 938831, 2111393),
          scales: [400000, 200000, 100000, 50000, 25000, 10000, 5000],
          projection:'EPSG:27582',    
          units: 'm',
          restrictedExtent: new OpenLayers.Bounds(854164, 2054948, 938831, 2111393)
      });      
          
   var urlParams = OpenLayers.Util.getParameters();    
   
	if (urlParams['id'] != null) {
		ids = urlParams['id'];
		document.getElementById('zone_tree').innerHTML = document.getElementById('zone_tree').innerHTML + "<INPUT TYPE=CHECKBOX NAME=\"selection\" CHECKED onclick=\"change_visibility('selection')\">Sélection<Br>"
	}
   
  /*** Layers initialization ***/
  var communesLayer = new OpenLayers.Layer.WMS(
    'Communes', 
    URL_MAPSERV, 
    {
      map: DIR_MAP+'/layers.map' ,
      layers: ['communes'],
      format: 'image/png',
      transparent: true
    },
    { 'isBaseLayer':false }
  );
  
  communesLayer.setVisibility(false);
  map.addLayer(communesLayer);   
  
  randoLayer = new OpenLayers.Layer.WFS(
    'Rando', 
    URL_MAPSERV, 
    {
      map: DIR_MAP+'/layers.map' ,
      typename: 'rando',
      ID_FILTER: ' is not null'
    },
    {
      'isBaseLayer':false,
      extractAttributes: true,
      styleMap: new OpenLayers.StyleMap({ 'default': randoStyle})
    }
  );
  randoLayer.setVisibility(false);
  map.addLayer(randoLayer);
  randoLayer.events.register("featuresadded", randoLayer.features, on_rando_load);
  
  //Modify feature style according to its specified color
  randoLayer.preFeatureInsert = function(feature){
	randoStyle.strokeColor = "#"+ feature.attributes.web ;
	feature.style = randoStyle;    
  }
  randoLayer.styledFeatures = [];
    
  var fondcartoLayer = new OpenLayers.Layer.WMS("Fond cartographique", 
        URL_TILECACHE, 
        {
            map: DIR_MAP+'/layers.map' ,
            layers: ['fondcarto'],
            format: 'image/jpeg'},
            {
                'isBaseLayer':true,
                buffer: 1
            } );
  fondcartoLayer.setVisibility(true);
  map.addLayer(fondcartoLayer);  
  
  orthoLayer = new OpenLayers.Layer.WMS("Ortho", 
        URL_TILECACHE, 
        {
            map: DIR_MAP+'/layers.map' ,
            layers: ['ortho'],
            format: 'image/jpeg'},
            {
                'isBaseLayer':false
            } );
  orthoLayer.setVisibility(false);
  map.addLayer(orthoLayer);  
    
        
    /*** POI layers ***/
    
    /*var selectionLayer = new OpenLayers.Layer.Vector("selection", 
	{ 
	styleMap: new OpenLayers.StyleMap({
        "default": select_style,
        "select": select_style})
    });
    selectionLayer.setVisibility(true);
    map.addLayer(selectionLayer);*/
        
  poiLayer =  new OpenLayers.Layer.WFS("poi", 
    URL_MAPSERV, 
    {
    	map: DIR_MAP+'/layers.map' ,
    	typename: "poi",
    	ID_FILTER: " is not null"
    },
    { 
      extractAttributes: true
    });
  poiLayer.styledFeatures = []; 
  poiLayer.setVisibility(false);      
  map.addLayer(poiLayer); 
  poiLayer.events.register("loadend", poiLayer, on_load());
  
  //Modify feature style according to its specified icon
  poiLayer.preFeatureInsert = function(feature){
  	if (map.getZoom() == 0)
  	{
  		style_mark.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_off_nom ;
		  style_mark.graphicWidth = parseInt(feature.attributes.picto_largeur) ;
		  style_mark.graphicHeight =  parseInt(feature.attributes.picto_hauteur) ;
		  feature.style = style_mark;
  	} else {
		style_mark.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_off_zoom_nom ;
		style_mark.graphicWidth = parseInt(feature.attributes.picto_zoom_largeur) ;
		style_mark.graphicHeight = parseInt(feature.attributes.picto_zoom_hauteur) ;	
		feature.style = style_mark;    
	}
  	if (document.getElementById('selection') != null
  		&& document.getElementById('selection').checked) {
    	if (poi_to_select.length > 0 && is_in_array(poi_to_select,feature.fid)) {
    		if (map.getZoom() == 0) {
    			style_mark.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_on_nom ;
				feature.style = style_mark; 
			} else {
				style_mark.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_on_zoom_nom ;
				feature.style = style_mark; 
			}  
    	}
  	}
  }
    
  /*** Controls initialization ***/
  var navigationControl =  new OpenLayers.Control.Navigation({
    title:'Se déplacer dans la carte'
  });
  map.addControl(navigationControl);    
  navigationControl.activate();
  
  selectControl = new OpenLayers.Control.SelectFeature(
    poiLayer,
    {
       hover: true,
       multiple: false,
       onSelect: onFeatureSelect,
       onUnselect: onFeatureUnselect,
       title: "Sélection par click"
     }
  ); 
  map.addControl(selectControl);
  selectControl.activate(); 

  var hoverControl = new OpenLayers.Control.Hover({
    handlerOptions: { 'delay': 500 }
  });
  map.addControl(hoverControl); 
  hoverControl.activate(); 
  
  // if zoom changes, call the matching function
  map.events.register("moveend", map, on_move);       
  
  // change_visibility of layers specified in parameters
  if (urlParams['id_layers'] != null) {
  	var layerParams = urlParams.id_layers;
  	display_poi(layerParams);
  }
    
  // recenter the map on the specified bbox
  if (urlParams['bbox'] != null && urlParams['bbox'] != "")
  {
  	var bboxArray = urlParams.bbox;
  	var bbox = new OpenLayers.Bounds(bboxArray[0],bboxArray[1],bboxArray[2],bboxArray[3]);
  	map.zoomToExtent(bbox);
  } 
  else 
    map.setCenter(new OpenLayers.LonLat(897000, 2084000),0);
    
  on_move();
  
  // Initialize slider
  init_slider();
    
	if (map.div.style) {
		map.div.style.cursor = "auto";
	}
}

/* 
 * fonction provenant du plugin tooltip de cartoweb pour vérifier
 * si un événement correspond à un déplacement d'un élément vers
 * un autre que le premier contient
 */
function __hbsCheckMouseLeave(element, evt) {
  if (element.contains && evt.toElement) 
    return !element.contains(evt.toElement);
  else if (evt.relatedTarget) 
    return !__hbsContainsDOM(element, evt.relatedTarget);
}

function __hbsContainsDOM(container, containee)
{
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  } while (containee != null);
  return isParent;
}


/*
 * When a feature is selected, display a popup
 */
function onFeatureSelect(feature)
{
	if (popup != null)
	{
	  var styledfeature = map.getLayersByName("poi")[0].styledFeatures[0];
    if (styledfeature)
    {	
    	if (map.getZoom == 0)   	 
			  styledfeature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ styledfeature.attributes.picto_off_nom ;
		  else
			  styledfeature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ styledfeature.attributes.picto_off_zoom_nom ;
		  map.getLayersByName("poi")[0].drawFeature(styledfeature);
		}
		map.getLayersByName("poi")[0].styledFeatures = [];
		map.removePopup(popup);
    popup.destroy();
    popup = null;
  }
  
	if (map.getLayersByName("poi")[0].styledFeatures.length == 0 && popup == null && popupRando == null)
	{
		if (map.getZoom() == 0) 
			feature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_on_nom ;
		else 
			feature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_on_zoom_nom ;
		
		map.getLayersByName("poi")[0].drawFeature(feature);
		map.getLayersByName("poi")[0].styledFeatures.push(feature);
    selectedFeature = feature;

    popup = new OpenLayers.Popup.Anchored(
      'popup_tableau', 
      feature.geometry.getBounds().getCenterLonLat(),
      new OpenLayers.Size(170,84),
      '<div id="infobulle"><a id="infobulle_fermeture" onclick="close_popup_fct()"><img src="/templates/pnr_navigation/images/bouton_fermeture.gif" /></a><p id="infobulle_titre">'+feature.attributes.titre+'</p><p id="infobulle_desc">'+feature.attributes.texte+'</p><p id="infobulle_lien"><a id="popupBox" class="thickbox" href="/php/fichesitra.php?objet='+feature.attributes.idsitra+'&KeepThis=true&TB_iframe=true&height=480&width=860">Plus d\'infos</a></p></div>',
      null, false, onPopupClose
    );	    
	  feature.popup = popup;
	  map.addPopup(popup);
	  TB_init_carto();	     
    popup.events.register("mouseout", popup, close_popup); 
  } 
}

function onFeatureUnselect(feature)
{
	if (map.getZoom() == 0) 
		feature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_off_nom ;
	else 
		feature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_off_zoom_nom ;
}

/*
 * When a popup is closed, unselect the feature
 */
function onPopupClose(evt) {
    //selectControl.unselect(selectedFeature);
    map.removePopup(popup);
    popup.destroy();
    popup = null;
}

/*
 * Close a popup on mouseout
 */
function close_popup(evt)
{
  if (!__hbsCheckMouseLeave(popup.div, evt))
    return;
  var feature = map.getLayersByName("poi")[0].styledFeatures[0];
	if (feature)
	{
    if (map.getZoom == 0) 
			feature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_off_nom ;
    else 
			feature.style.externalGraphic = URL_WEB+"/../../data/iconesPOI/"+ feature.attributes.picto_off_zoom_nom ;
		map.getLayersByName("poi")[0].drawFeature(feature);
	}
  map.removePopup(popup);
  popup.destroy();
  popup = null;
  map.getLayersByName("poi")[0].styledFeatures = [];
  OpenLayers.Util.safeStopPropagation(evt);
}

/*
 * Close a poi popup 
 */
function close_popup_fct() {
  map.removePopup(popup);
  popup.destroy();
  popup = null;
    
  var feature = map.getLayersByName('poi')[0].styledFeatures[0];
	if (feature)
	{
		feature.style.strokeOpacity = 1;
  	feature.style.strokeColor = "#" + feature.attributes.web;
  	feature.style.strokeWidth = 3;
  	map.getLayersByName('poi')[0].drawFeature(feature);
  }
  map.getLayersByName('poi')[0].styledFeatures = [];
}


/**
 * Creates a WFS filter to display only some categories of POI
 */
function display_poi(wfsToDisplay, randos_ids) {
	var layer = map.getLayersByName("poi")[0];
	if (typeof(wfsToDisplay) == "object" && wfsToDisplay.length != 0){
		var filter_string = "<Filter>";
		var id_filter = " is not null";
		for (var i=0; i < wfsToDisplay.length - 1; i++) {
			filter_string= filter_string + "<Or>";
		}
		for (var i=0; i < wfsToDisplay.length; i++) {
			if (wfsToDisplay[i] == "selection") {
				for (var j=0; j < poi_to_select.length - 1; j++) {
					filter_string= filter_string + "<Or>";
				}
				for (var j=0; j < poi_to_select.length; j++) {
					filter_string = filter_string + "<PropertyIsEqualTo><PropertyName>id</PropertyName><Literal>"+poi_to_select[j]+"</Literal></PropertyIsEqualTo>";
					if (j > 0) {
						filter_string = filter_string + "</Or>";
					} 
				}
			} else if (wfsToDisplay[i] == "Rando") {
				if (randos_ids) {
					id_filter = " = rando_poi.poi_id AND rando_poi.rando_id in ("+ randos_ids + ")";
				}
				filter_string = filter_string + "<PropertyIsEqualTo><PropertyName>rando</PropertyName><Literal>t</Literal></PropertyIsEqualTo>";
			} else {
				filter_string = filter_string + "<PropertyIsEqualTo><PropertyName>categorie</PropertyName><Literal>"+wfsToDisplay[i]+"</Literal></PropertyIsEqualTo>";
			}
			if (i > 0) {
				filter_string = filter_string + "</Or>";
			} 
		} 
		filter_string = filter_string + "</Filter>";
		var filter = {filter: filter_string, ID_FILTER: id_filter};
		layer.mergeNewParams(filter);
		layer.setVisibility(true);
	} else if (typeof(wfsToDisplay) != "object") {
		var id_filter = " is not null";
		if (wfsToDisplay[i] == "selection") {
			var filter_string = "<Filter>";
			for (var i=0; i < poi_to_select.length - 1; i++) {
				filter_string= filter_string + "<Or>";
			}
			for (var i=0; i < poi_to_select.length; i++) {
				filter_string = filter_string + "<PropertyIsEqualTo><PropertyName>id</PropertyName><Literal>"+poi_to_select[i]+"</Literal></PropertyIsEqualTo>";
				if (i > 0) {
					filter_string = filter_string + "</Or>";
				} 
			}
			filter_string = filter_string + "</Filter>";
		} else if (wfsToDisplay[i] == "Rando") {
			if (randos_ids) {
				id_filter = " = rando_poi.poi_id AND rando_poi.rando_id in ("+ randos_ids + ")";
			}
			filter_string = "<Filter><PropertyIsEqualTo><PropertyName>rando</PropertyName><Literal>t</Literal></PropertyIsEqualTo></Filter>";
		}
		else {
			var filter_string = "<Filter><PropertyIsEqualTo><PropertyName>categorie</PropertyName><Literal>"+wfsToDisplay+"</Literal></PropertyIsEqualTo></Filter>";
		}
		var filter = {filter: filter_string, ID_FILTER: id_filter};
		layer.mergeNewParams(filter);
		layer.setVisibility(true);	
	}
	else {
		layer.setVisibility(false);
	}
}

/*
 * Hide or show the layer
 */
function change_visibility(name) {
	if (!is_in_array(wfs_categories,name))
	{
		var layer = map.getLayersByName(name)[0];
		if (layer.visibility == false)
			layer.setVisibility(true);
		else
			layer.setVisibility(false);
	}
	else
	{
		var wfsToDisplay = [];
		for (var i=0; i < wfs_categories.length; i++)
		{
			if (document.getElementById(wfs_categories[i]) && document.getElementById(wfs_categories[i]).checked) 
				wfsToDisplay.push(wfs_categories[i]);
		}
		if (name == "Rando")
		{
			if (map.getLayersByName(name)[0].visibility == false) 
				map.getLayersByName(name)[0].setVisibility(true);
			else 
				map.getLayersByName(name)[0].setVisibility(false);
		}
		display_poi(wfsToDisplay);
	}
}

function getByFid(array, match) {
  var found = OpenLayers.Array.filter(array, function(item) {
    return item.fid == match;
  });
  return found;
}

