/*
 * Copyright © 2008  Neogeo Technologies, Toulouse, France

 * This file is part of Opencarto web map publishing system project
 *
 * Opencarto is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Opencarto is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Opencarto.  If not, see <http://www.gnu.org/licenses/>.
 */

var panel;
var oLayer; 

opencarto.tm = null;
opencarto.overFeature = null;
opencarto.overAttr = null;
opencarto.autozoom = false;
opencarto.autocenter = false;
opencarto.mode_click = null;

opencarto.resultWindow = null;
opencarto.legend_html = null;

opencarto.resizeMap = function(p){
opencarto.refreshTimeout = null;
   opencarto.map.updateSize();
  // opencarto.map.panTo(opencarto.map.getCenter());
   
   
}

opencarto.setGoogleStyle = function(obj){
	
 myLayerName = obj.id;
   myLayers = opencarto.map.getLayersByName(myLayerName);
   opencarto.map.setBaseLayer(myLayers[0]);
   if (myLayerName == "ortho")
   {
	opencarto.batlayer.setVisibility(true);
 //      opencarto.batlayerlab.setVisibility(true);

   }
   else
   {
       opencarto.batlayer.setVisibility(false);
   //     opencarto.batlayerlab.setVisibility(false);
  }
}

opencarto.checkZoomLevel = function(m){
	
	var myOldLayer = opencarto.map.getLayersByName('Google Layer');
	gl = myOldLayer[0];
	if (opencarto.map.getZoom() > 17 && gl.type == G_NORMAL_MAP)	{
		opencarto.map.zoomTo(17);
		Ext.Msg.show({
                title: "Attention",
                msg: "Le zoom maximal est atteint pour ce fond de plan.",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
               });
          
            return;
		
	}
	

}

opencarto.toolbarHandler = function(btn,e) {
   
   
   lastBtn = null;
  
   for (j=0;j<opencarto.toolbar.items.length;j++)
   {
      theBtn = opencarto.toolbar.items.get(j);
      
      
      if(theBtn.pressed){
         
         
         if (theBtn != btn)
            lastBtn = theBtn;
      }
      theBtn.toggle(false);
      
   }
   btn.toggle(true);
   switch(btn.id){
      case 10:
         opencarto.map.zoomToMaxExtent();
         btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
      case 11:
         ctlClassName = 'olControlZoomBox';
         break;
      case 12:
         opencarto.map.zoomOut();
         btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
      case 13:
         ctlClassName = 'olControlNavigation';
         break;
      case 14:
         opencarto.addPoi();
         btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
      case 15:
         ctlClassName = 'olControlCalculateArea';
         break;
      case 16:
         ctlClassName = 'olInfoCtrl';
         break;
      
      case 17:
         //opencarto.vectorLayer.destroyFeatures(opencarto.vectorLayer.features);
         
         btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         opencarto.addGPSFile();
         return;
         break;
      
	case 20:
		var w = 800;
        var h = 800;
        var url = 'print/';
        var win = window.open(url,'printWindow','menubar=yes ,status=no, scrollbars=yes, width=' + w + ', height='+h);
        btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
        return;
        break;
     case 21:
         opencarto.showLegend();
        btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
     
     case 22:
        opencarto.saisie.activate();
         ctlClassName = 'olSketchControl';
       
         break
     case 23:
       // opencarto.saisie.activate();
         ctlClassName = 'olModifyCtrl';
         opencarto.mode_click = 'modify';
         break
     case 24:
       // opencarto.saisie.activate();
         ctlClassName = 'olModifyCtrl';
         opencarto.mode_click = 'delete';
         break
     case 26:
        var w = 800;
        var h = 800;
        var url = '../admin/';
        var win = window.open(url,'adminWindow','menubar=no ,resizable, status=no, scrollbars=yes, width=' + w + ', height='+h);
        btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
        return;
        break;
     case 27:
        opencarto.showPermalink();
        btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
     case 30:
         ctlClassName = 'olControlCalculateLength';
         break; 
     case 95:
         
         btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
      case 99:
         btn.toggle();
         if(lastBtn)
            lastBtn.toggle();
         return;
         break;
     
   }
   opencarto.getMapControl(opencarto.lastControlUsed).deactivate();
   opencarto.getMapControl(ctlClassName).activate();
   opencarto.lastControlUsed = ctlClassName;
   if (opencarto.saisie_layer){
   	opencarto.saisie_layer.destroyFeatures(opencarto.saisie_layer.features);
   }
   
}
opencarto.getMapControl = function(className){
   for (i=0;i<opencarto.map.controls.length;i++)
   {
      theCtl = opencarto.map.controls[i];
      if(theCtl.displayClass == className)
      {
         return theCtl;
      }
   }
   return null;
}

opencarto.addPoi = function(){
  
   var w = window.open('../admin/geo/poi/add/','ajoutpoi','menubar=no, status=no, scrollbars=yes, menubar=no, width=800, height=600');
   
}

opencarto.showPermalink = function(btn){
    var	center = opencarto.map.center;
    var	zoom = opencarto.map.zoom;
    var	layers = opencarto.poilayer.params.LAYERS.replace('fake,num,','').replace(/layer_/g ,'');
    var base = opencarto.map.baseLayer.name;
    
    layers = layers.replace('fake,num','');
	Ext.MessageBox.prompt('Permalien',
	    'Copier le lien ci-dessous pour accéder directement à la vue en cours:', 
	    null,
	    null,
	    true,
	    window.location.href.split('&')[0] + '&base='+ base + '&center='+center.lon+','+center.lat+'&zoom='+zoom+'&layers='+layers);
	
	
	
}
opencarto.centerVector = function(btn){
   if (btn.pressed){
      opencarto.autocenter = true;
      btn.setIconClass("checkedButton");
      btn.setText(btn.text.replace('inactif','actif'));
   }
   else{
      opencarto.autocenter = false;
      btn.setIconClass("noCheckButton");
      btn.setText(btn.text.replace('actif','inactif'));
   }
  
   opencarto.centerRoute();
   
}
function displayLayer(id,status,mode){
  
  if (status == true){
      my_layers = opencarto.poilayer.params.LAYERS + ',layer_' + id;
      if (mode == 'v')
        opencarto.loadVector(id);
  }
   else{
      my_layers = opencarto.poilayer.params.LAYERS.replace(',layer_'+id,'')
      if (mode == 'v')
        opencarto.deleteVector(id);
   }
   opencarto.poilayer.mergeNewParams({'layers':my_layers});
   opencarto.poilayer.redraw();
   opencarto.computeLegend();
  // opencarto.drawLegend();
} 

opencarto.resetSearch = function(){
opencarto.vector_layer.destroyFeatures(opencarto.vector_layer.features);
   opencarto.deleteVector('search');	  
   opencarto.PoiTypesCombo.reset();
   opencarto.radiusSlider.setValue(0);
  
   opencarto.searchPoiForm.getForm().findField('poiname').setValue('');
   if (opencarto.resultWindow != null){
      opencarto.resultWindow.destroy();
      opencarto.resultWindow = null;
      
   }
   
}
opencarto.deleteVector = function(id){
   fToDel = new Array();
   id == 'search' ? myField = 'mode' : myField = 'thm_id';

   for (i=0;i<opencarto.poi_layer.features.length;i++)
   {
      f = opencarto.poi_layer.features[i];

      if (f.attributes[myField] == id)
         fToDel.push(f)


   }
   opencarto.poi_layer.destroyFeatures(fToDel);



}

opencarto.loadVector = function(id){
   
   
   // suppression des marques d'adresse
      //opencarto.deleteVector(99999);
    if (opencarto.vector_layer)
        opencarto.vector_layer.destroyFeatures(opencarto.vector_layer.features);
       
    if (id && typeof(id) == 'object'){
    	
      if (!opencarto.searchPoiForm.getForm().isValid()){
         Ext.Msg.show({
                title: "ERREUR",
                msg: "La saisie n'est pas valide",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
               });
          
            return;
         
      }
      
      var mode = 'search';
      id = opencarto.searchPoiForm.getForm().findField('poitype').value;
      if (!id)
         id = 0;
      if (id == 0 && opencarto.searchPoiForm.getForm().findField('poiname').getValue() == '')
      {
         Ext.Msg.show({
                title: "ERREUR",
                msg: "Un nom ou un type de lieu doit être spécifié.",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
               });
          
            return;
         
         
      }
      if (opencarto.radiusSlider.getValue() == 0 && opencarto.searchPoiForm.getForm().findField('poiname').getValue() == '')
      {
         Ext.Msg.show({
                title: "ERREUR",
                msg: "Un nom ou un rayon doit être spécifié.",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
               });
          
            return;
         
         
      }
     
      var poiname= opencarto.searchPoiForm.getForm().findField('poiname').getValue();
      // effacement des objets déjà affichés dans le type
      opencarto.deleteVector(id);
      //effacement des objets déjà affichés par une recherche
      opencarto.deleteVector('search');
      var radius = opencarto.radiusSlider.getValue();
      
     
      
      var center = opencarto.map.getCenter();
      var x = center.lon;
      var y = center.lat;
   }
   else{
   	
      var mode = 'all';
      var radius = 0;
      var poiname = '';
      var x = 0;
      var y = 0;
     // var bbox = opencarto.map.getExtent().toBBOX();
   }
   if (Ext){
	   Ext.Ajax.request({
	        url: '../pois/',
	        method: 'GET',
	        disableCaching: false,
	        params: {
	            id: id,
	            mode : mode,
	           // bbox : bbox,
	            radius : radius,
	            x:x,
	            y:y,
	            poiname:poiname
	            
	        },
	        success: function(res,opt) {
			   	
	            
	            
	            try {
	                
	                eval('var response = ' + res.responseText);
	            } catch(e) {
	                Ext.Msg.show({
	                title: "ERREUR",
	                msg: "Les lieux n'ont pas pu être chargés",
	                buttons: Ext.Msg.OK,
	                icon: Ext.MessageBox.ERROR
	               });
	               return;
	            }
	            j =  new OpenLayers.Format.GeoJSON();
	              
	            features = j.read(response);
	            if (features.length == 1 && features[0].attributes['result']){
	               cname = features[0].attributes['category'];
	               Ext.Msg.show({
	                title: "Trop d'objets à afficher",
	                msg: "L'affichage de la couche " + cname + " n'est pas pertinent à cette échelle. Veuillez zoomer pour visualiser les éléments ou la désactiver.",
	                buttons: Ext.Msg.OK,
	                icon: Ext.MessageBox.INFO
	               });
		   
	              return;
	               
	            }
	            opencarto.poi_layer.addFeatures(features);
	            if (mode == 'search'){
	               opencarto.showResults(response);  
	            }
	           /*
	            else{
	               opencarto.drawLegend();
	              
	            }
	            */
	               
	        },
	        failure: function(res,opt) {
	            Ext.Msg.show({
	                title: "ERREUR",
	                msg: "Les POIs n'ont pas pu être chargés",
	                buttons: Ext.Msg.OK,
	                icon: Ext.MessageBox.ERROR
	               });
	          
	            return;
	        }
	    });
   }
   
  else{
  	 var request = OpenLayers.Request.GET({
            url: '../pois/',
            params: {
            	id: id,
            	mode:mode,
            	radius : radius,
                x:x,
                y:y,
                poiname:poiname
            },
            callback: opencarto.add_features,
            scope: opencarto
        });
  	
  	
  	
  	
  }
  
   
}

opencarto.drawLegend = function(){
   try{
   opencarto.menuLeg.removeAll(true);
   opencarto.layerStore.each(opencarto.addToLegend);
   }
   catch(e)
   {
   }
}

opencarto.addToLegend = function(r){
    if (r.get('checked') == true && !opencarto.menuLeg.items.get('x' + r.get('id'))){
      opencarto.menuLeg.add({
      	id:'x' + r.get('id'),
        text: r.get('name'),
        icon: globalParams.mediaURL+r.get('icon')
      })  
      
   }
   
}

opencarto.formatDistance = function(dist){
   return dist.toFixed(0) + ' m';


}

opencarto.showResults = function(response){
   opencarto.resultStore = new Ext.data.JsonStore({
         data:response,
         storeId: 'id',
         root: 'features',
         fields: ['properties.id',
                  {name:'properties.thm_name',type:'string'},
                  {name:'properties.name',type:'string'},
                  'properties.adresse',
                  'properties.description',
                  'properties.adresse',
                  'properties.tel',
                  'properties.acces',
                  'properties.fax',
                  'properties.mail',
                  'properties.web',
                  'properties.distance',
                  'geometry.coordinates'],
         sortInfo: {field: 'properties.distance', direction: 'ASC'},
         remoteSort: false
       });
   
   var sm = new Ext.grid.RowSelectionModel({ singleSelect:true});
   
   var cm = new Ext.grid.ColumnModel([
      {id:'id',header: "ID", hidden:true, sortable: false, dataIndex: 'properties.id'},
      {id:'theme',header: "Rubrique", width:150,hidden:false, sortable: true, dataIndex: 'properties.thm_name', resizable:true},
      {id:'name',header: "Nom", hidden:false, sortable: true, dataIndex: 'properties.name', resizable:true},
      {id:'dist',header: "Dist.", renderer:opencarto.formatDistance,hidden:false, sortable: true, dataIndex: 'properties.distance', resizable:true}
      ]);
   opencarto.resultGrid = new Ext.grid.GridPanel({
      store: opencarto.resultStore,
      cm: cm,
      sm:sm,
      viewConfig: {
        forceFit: false
      },
      autoExpandColumn:'name',
       autoExpandMin:150,
      autoScroll:true,
      width:450,
      height:200,
      frame:false,
      border:false,
      collapsible: false,
      title: ''
  });
   opencarto.resultGrid.getSelectionModel().on(
         'rowselect',opencarto.showItem
     );
   if (opencarto.resultWindow != null){
      opencarto.resultWindow.destroy();
      opencarto.resultWindow = null;
   }
   opencarto.resultWindow = new Ext.Window({
   title: 'Résultats de la recherche',
   width: 470,
   height:250,
   minWidth: 200,
   minHeight: 100,
   x:250,
   y:500,
   layout: 'fit',
   closeAction :'close',
   plain:true,
   bodyStyle:'padding:5px;',
   buttonAlign:'center',
   items:opencarto.resultGrid,
   buttons: [{
       text: 'Fermer',
       handler  : function(){
            opencarto.resultWindow.destroy();
            opencarto.resultWindow = null;
         }

      }]
   });    
   opencarto.resultWindow.show();
}
opencarto.showItem = function(sm,idx,r){
   aXY = r.get('geometry.coordinates');
   
   if (aXY[0] != null && aXY[1] != null){
      var lonlat = new OpenLayers.LonLat(aXY[0] , aXY[1]);
      opencarto.map.setCenter(lonlat,opencarto.map.getZoom(),false,false);
      for (i=0;i<opencarto.poi_layer.features.length;i++){
         f = opencarto.poi_layer.features[i];
         
         if (f.attributes["id"] == r.get('properties.id')){
            opencarto.preparePopup(f);
            
            opencarto.tm = setTimeout("opencarto.deletePopup()", 5000);
            return;
         }
         
      }
   }
   else{
      var msg = "<b>Nom</b> : " + r.get('properties.name') + "<br />";
      msg += "<b>Description</b> : " + r.get('properties.description') + "<br />";
      if (r.get('properties.adresse') != '')
      	msg += "<b>Adresse</b> : " + r.get('properties.adresse') + "<br />";
      if (r.get('properties.tel') != '')
       msg += "<b>Téléphone</b> : " + r.get('properties.tel') + "<br />";
	if (r.get('properties.fax') != '')
      msg += "<b>Télécopie</b> : " + r.get('properties.fax') + "<br />";
	if (r.get('properties.mail') != '')
      msg += "<b>E-Mail</b> : " + r.get('properties.mail') + "<br />";
	if (r.get('properties.acces') != '')
      msg += "<b>Accès</b> : " + r.get('properties.acces') + "<br />";
	if (r.get('properties.web') != '')
      msg += "<b>Site web</b> : " + r.get('properties.web') + "<br />";
       
      Ext.MessageBox.show({
           title: 'Lieu non localisé sur la carte',
           msg: msg,
           width:400,
           buttons: Ext.MessageBox.OK
       });

      
      
   }
   
   
}
opencarto.preparePopup = function(feature) {
    if (opencarto.tm) {
        clearTimeout(opencarto.tm);
    }
   opencarto.overFeature = feature;
   opencarto.tm = setTimeout("opencarto.createPopup()", 100);
}
opencarto.preparePopupXML = function(att) {
    if (opencarto.tm) {
        clearTimeout(opencarto.tm);
    }
    opencarto.overAttr = att;
   opencarto.tm = setTimeout("opencarto.createPopupXML()", 100);
}

opencarto.createPopup = function() {
    if (opencarto.popup) {
        opencarto.deletePopup();
    }
    var lonlat = new OpenLayers.LonLat(opencarto.overFeature.geometry.getCentroid().x , opencarto.overFeature.geometry.getCentroid().y );
    if (opencarto.overFeature.attributes["thm_id"] != 99999){
    var html = '<div style="text-align:left;"><span style="font-size:medium"><b>' + opencarto.overFeature.attributes["thm_name"] + ' </b></span>';
    html += '<br /><span style="font-size:small"><b>' + opencarto.overFeature.attributes["name"] + '</b></span>';
    html += '<br /><span style="font-size:small">' + opencarto.overFeature.attributes["description"] + '</span>';
    if (opencarto.overFeature.attributes["adresse"] != "")
    html += '<br /><span style="font-size:small">Adresse : ' + opencarto.overFeature.attributes["adresse"] + '</span>';
    if (opencarto.overFeature.attributes["tel"] != "")
    html += '<br /><span style="font-size:small">Téléphone : ' + opencarto.overFeature.attributes["tel"] + '</span>';
    if (opencarto.overFeature.attributes["fax"] != "")
    html += '<br /><span style="font-size:small">Télécopie : ' + opencarto.overFeature.attributes["fax"] + '</span>';
    if (opencarto.overFeature.attributes["mail"] != "")
    html += '<br /><span style="font-size:small">Mél : : <a href="mailto:' + opencarto.overFeature.attributes["mail"] + '">' + opencarto.overFeature.attributes["mail"] + '</a></span>';
    if (opencarto.overFeature.attributes["acces"] != "")
    html += '<br /><span style="font-size:small">Accès : ' + opencarto.overFeature.attributes["acces"] + '</span>';
    if (opencarto.overFeature.attributes["url"] != "")
    html += '<br /><span style="font-size:small">Téléchargement : <a href="' + opencarto.overFeature.attributes["url"] + '" target="_blank">Télécharger la donnée</a></span>';
    
    if (opencarto.overFeature.attributes["web"] != "")
    html += '<br /><span style="font-size:small">Site internet : <a href="' + opencarto.overFeature.attributes["web"] + '" target="_blank"> ' + opencarto.overFeature.attributes["web"] + '</a></span>';
    if(opencarto.overFeature.attributes["image"] != ""){
        html += '<br /><img src="'+globalParams.mediaURL+opencarto.overFeature.attributes["image"]+'" border="0"/>'
     }
    }
    else{
      // localisation d'une adresse
      var html = '<div style="text-align:center;"><span style="font-size:medium"><b>' + opencarto.overFeature.attributes["adresse"] + ' </b></span>';
   
   
      
    }
    html += "</div>";
    var anchor = {'size': new OpenLayers.Size(20,20), 'offset': new OpenLayers.Pixel(-10,-10) };
    opencarto.popup = new OpenLayers.Popup.AutoSizedFramedCloud("popup", lonlat, null, html, anchor, false);
    opencarto.popup.fixedRelativePosition = true;
    opencarto.map.addPopup(opencarto.popup, true);
}
opencarto.createPopupXML = function() {
    if (opencarto.popup) {
        opencarto.deletePopup();
    }
    var lonlat = new OpenLayers.Pixel(opencarto.overAttr["x"] , opencarto.overAttr["y"] );
    var html = '<div style="text-align:left;">'; //<span style="font-size:medium"><b>' + opencarto.overAttr["cl_name"] + ' </b></span>';
    html += '<br /><span style="font-size:small"><b>' + opencarto.overAttr["poi_name"] + '</b></span>';
    html += '<br /><span style="font-size:small">' + opencarto.overAttr["poi_description"] + '</span>';
    if (opencarto.overAttr["poi_adresse"] && opencarto.overAttr["poi_adresse"] != "")
        html += '<br /><span style="font-size:small">Adresse : ' + opencarto.overAttr["poi_adresse"] + '</span>';
    if (opencarto.overAttr["poi_tel"] && opencarto.overAttr["poi_tel"] != "")
        html += '<br /><span style="font-size:small">Téléphone : ' + opencarto.overAttr["poi_tel"] + '</span>';
    if (opencarto.overAttr["poi_fax"] && opencarto.overAttr["poi_fax"] != "")
        html += '<br /><span style="font-size:small">Télécopie : ' +opencarto.overAttr["poi_fax"] + '</span>';
    if (opencarto.overAttr["poi_mail"] && opencarto.overAttr["poi_mail"] != "")
        html += '<br /><span style="font-size:small">Mél : <a href="mailto:' + opencarto.overAttr["poi_mail"] + '">' + opencarto.overAttr["poi_mail"] + '</a></span>';
   
      
    if (opencarto.overAttr["poi_web"] && opencarto.overAttr["poi_web"] != "")
        html += '<br /><span style="font-size:small">Site internet : <a href="' +opencarto.overAttr["poi_web"] + '" target="_blank"> ' + opencarto.overAttr["poi_web"] + '</a></span>';
    if (opencarto.overAttr["poi_url"] && opencarto.overAttr["poi_url"] != "")
        html += '<br /><span style="font-size:small">Téléchargement : <a href="' +opencarto.overAttr["poi_url"] + '" target="_blank">Télécharger la donnée</a></span>';
    
    if (opencarto.overAttr["poi_acces"] && opencarto.overAttr["poi_acces"] != "")
        html += '<br /><span style="font-size:small">Accès : ' + opencarto.overAttr["poi_acces"] + '</span>';
    if (opencarto.overAttr["image"] && opencarto.overAttr["image"] != "")
	   html += '<br /><img src="'+globalParams.mediaURL+opencarto.overFeature.attributes["image"]+'" border="0"/>'
    
     html += "</div>";
    //var anchor = {'size': new OpenLayers.Size(20,20), 'offset': new OpenLayers.Pixel(-10,-10) };
    opencarto.popup = new OpenLayers.Popup.AutoSizedFramedCloud("popup", opencarto.map.getLonLatFromPixel(lonlat), null, html, null, true);
    opencarto.popup.fixedRelativePosition = true;
    opencarto.map.addPopup(opencarto.popup, true);
   /* opencarto.map.addPopup(new OpenLayers.Popup.FramedCloud(
                        "chicken", 
                        opencarto.map.getLonLatFromPixel(lonlat),
                        null,
                        html,
                        null,
                        true
                    ));
*/
}


opencarto.deletePopup = function(){
   if (opencarto.popup){
      opencarto.map.removePopup(opencarto.popup);

   opencarto.popup = null;
   }
}

opencarto.getLocation = function(){
//opencarto.deleteVector(99999);	  
    opencarto.resultLayer.destroyFeatures(opencarto.resultLayer.features);
        adr = opencarto.searchForm.getForm().findField('adresse').getValue();
        adr = adr.replace(/&/g,'');
        city = opencarto.gtCities.getValue();
        if (adr == '') return;
    
    if(adr.length < 3)
    {
    	Ext.Msg.show({
                title: "Attention",
                msg: "Vous devez saisir au moins 3 caractères pour la recherche.",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.INFO
                });
        return;
    }
    
    
    if(parseInt(adr) == adr)
    {
        Ext.Msg.show({
                title: "Attention",
                msg: "Vous devez saisir une adresse contenant un nom de rue.",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.INFO
                });
        return;
    }
    
    
	Ext.Ajax.request({
            url:'../proxy/',
            params: {'url':'getlocation?cty='+city+'&adr='+adr+'&proj=3943' },
            
             success:function(res,opt) {
                  //eval('var adresses = ' + res.responseText);
                  geojson = new OpenLayers.Format.GeoJSON();
                  opencarto.features = geojson.read(res.responseText);
                  if (opencarto.features && opencarto.features.length == 0){
                  	Ext.Msg.show({
                            title: "Adresse inconnue",
                            msg: "L'adresse n'a pas été trouvée",
                            buttons: Ext.Msg.OK,
                            icon: Ext.MessageBox.INFO
                            });
                    return;
                  	
                  }
                  if (opencarto.features.length == 1) {
                  	 opencarto.resultLayer.addFeatures(opencarto.features);
                  	 bounds = opencarto.features[0].geometry.getBounds();
                  	 quality_message = '';
                  	 if (opencarto.features[0].attributes['score'] != 1){
                  	 	quality_message = "Votre saisie a été corrigée en <br />\"" + opencarto.features[0].attributes['adr'] + "\"<br>";
                  	 }
                  	 if (opencarto.features[0].attributes['quality'] == 7 )
                  	 	quality_message += "Numéro exact non trouvé, <br />vous allez être positionné au numéro le plus proche, le "+ opencarto.features[0].attributes['no'];
                  	 else if (opencarto.features[0].attributes['quality'] == 6.5)
                  	    quality_message += "Numéro exact non trouvé, vous allez être positionné sur la voie.";
					 if (quality_message != ''){
					 	Ext.Msg.show({
                            title: "Information",
                            msg: quality_message,
                            buttons: Ext.Msg.OK,
                            icon: Ext.MessageBox.INFO
                            });
					 }
					 if (opencarto.features[0].attributes['quality'] == 6 || opencarto.features[0].attributes['quality'] == 6.5)
					 	opencarto.map.zoomToExtent(bounds);
					 else
					 	opencarto.map.setCenter(new OpenLayers.LonLat(opencarto.features[0].geometry.x - 50,opencarto.features[0].geometry.y),5,false,false);
					 
                  	 return;
                  }
                  else{
                  	eval('var response = ' + res.responseText);
                  	opencarto.showResultsAdr(response)
                  	
                  	
                  }
                 
                }
            });


}
    
opencarto.syncMapToSlider = function(slider,e){
   opencarto.drawRadius(slider.getValue());
}
opencarto.refreshRadius = function(){
   
   if (opencarto.vector_layer.features.length == 1){

      opencarto.drawRadius(opencarto.radiusSlider.getValue());
   }
   
   
}
opencarto.drawRadius = function(val){
   val = parseInt(val/opencarto.map.resolution*1.35);
   opencarto.vector_layer.destroyFeatures(opencarto.vector_layer.features);
   f = new OpenLayers.Feature.Vector(
						new OpenLayers.Geometry.Point(
							opencarto.map.getCenter().lon, 
							opencarto.map.getCenter().lat
						),
						{"id":"radius","radius":val}
					);
   
  // alert(val);
   opencarto.vector_layer.addFeatures([f]);
   
}


OpenLayers.Control.Hover = OpenLayers.Class(OpenLayers.Control, {
    layer: null,
    selectStyle: "select",
    selectedFeature: null,
    overFeature: function(feature) {},
    outFeature: function(feature) {},
    clickFeature: function(feature) {},
    clickoutFeature: function(feature) {},
    
    initialize: function(layer, options) {
        OpenLayers.Control.prototype.initialize.apply(this, [options]);
        this.layer = layer;
        var callbacks = {
            over : this.overFeature,
            out: this.outFeature,
            click: this.onFeatureClick,
            clickout: this.onFeatureClickOut
        };
        
        this.handler = new OpenLayers.Handler.Feature(
            this, layer, callbacks, {geometryTypes: this.geometryTypes} // FIXME : geometryTypes not defined ?
        );
    },
    
    onFeatureClick: function(feature) {
        if (this.selectedFeature) {
            this.layer.drawFeature(this.selectedFeature, "default");
        }
        this.layer.drawFeature(feature, this.selectStyle);
        this.selectedFeature = feature;
        this.clickFeature(feature);
    },
    
    onFeatureClickOut: function(feature) {
        this.clickoutFeature(feature);
        this.selectedFeature = null;
    },

    /**
     * APIMethod: destroy
     * Take care of things that are not handled in superclass
     */
    destroy: function() {
        this.layer = null;
        this.selectedFeature = null;
        OpenLayers.Control.prototype.destroy.apply(this, []);
    }
});
OpenLayers.Popup.AutoSizedFramedCloud = OpenLayers.Class(
    OpenLayers.Popup.FramedCloud, {
        'autoSize': true,
        'fixedRelativePosition': true, // in order to be able to clic on the icons ...
        'relativePosition': 'tr', // idem
        'minSize': new OpenLayers.Size(150, 75),
        'maxSize': new OpenLayers.Size(600, 660)
});

opencarto.showResultsAdr = function(response){
   opencarto.resultStore = new Ext.data.JsonStore({
         data:response,
         storeId: 'id',
         root: 'features',
         fields: ['properties.adr',
                  
                  'properties.score'],
         sortInfo: {field: 'properties.score', direction: 'DESC'},
         remoteSort: false
       });
   
   var sm = new Ext.grid.RowSelectionModel({ singleSelect:true});
   
   var cm = new Ext.grid.ColumnModel([
      
      {id:'adr',header: "Adresse", width:150,hidden:false, sortable: true, dataIndex: 'properties.adr', resizable:true}
      //{id:'qual',header: "Qualité", width:150,hidden:false, sortable: true, dataIndex: 'properties.score', resizable:true},
      ]);
   opencarto.resultGrid = new Ext.grid.GridPanel({
      store: opencarto.resultStore,
      cm: cm,
      sm:sm,
      viewConfig: {
        forceFit: false
      },
      autoExpandColumn:'adr',
       autoExpandMin:150,
      autoScroll:true,
      width:450,
      height:200,
      frame:false,
      border:false,
      collapsible: false,
      title: ''
  });
   opencarto.resultGrid.getSelectionModel().on(
         'rowselect',opencarto.showItemAdr
     );
   if (opencarto.resultWindow != null){
      opencarto.resultWindow.destroy();
      opencarto.resultWindow = null;
   }
   opencarto.resultWindow = new Ext.Window({
   title: 'Résultats de la recherche',
   width: 470,
   height:250,
   minWidth: 200,
   minHeight: 100,
   x:250,
   y:200,
   //layout: 'fit',
   closeAction :'close',
   plain:true,
   bodyStyle:'padding:5px;',
   buttonAlign:'center',
   items:opencarto.resultGrid,
   buttons: [{
       text: 'Fermer',
       handler  : function(){
            opencarto.resultWindow.destroy();
            opencarto.resultWindow = null;
         }

      }]
   });    
   opencarto.resultWindow.show();
}
opencarto.showItemAdr = function(sm,idx,r){
  adr = r.get('properties.adr');
opencarto.resultLayer.destroyFeatures(opencarto.resultLayer.features); 
  for (i=0;i<opencarto.features.length;i++){
  	if (adr == opencarto.features[i].attributes['adr']){
  		opencarto.resultLayer.addFeatures([opencarto.features[i]]);
  		bounds = opencarto.features[i].geometry.getBounds();
  		
  		 if (opencarto.features[i].attributes['quality'] == 6)
				opencarto.map.zoomToExtent(bounds);
		else
			opencarto.map.setCenter(new OpenLayers.LonLat(opencarto.features[i].geometry.x - 50,opencarto.features[i].geometry.y),5,false,false);
						 	
  		
  	}
  	
  }
}
opencarto.resetAdrSearch = function(){
	opencarto.resultLayer.destroyFeatures(opencarto.resultLayer.features);
	opencarto.searchForm.getForm().findField('adresse').setValue('');
	opencarto.gtCities.value = '31555';	
	
}
opencarto.computeLegend = function(){
	
   
	
}
opencarto.showLegend = function(){
    html = '';
    my_layers = opencarto.poilayer.params.LAYERS.replace('fake,num','').split(',');

    the_url = globalParams.mapserver.replace('__MAPNAME__', globalParams.map_file) + 'SLD_VERSION=1.1.0&SERVICE=WMS&REQUEST=GetLegendGraphic&FORMAT=image/png&VERSION=1.3.0&LAYER=';
    
    for (i=0;i<my_layers.length;i++){
        if (my_layers[i].indexOf('layer_') != -1){
            id = my_layers[i].replace('layer_','');
            the_rec = opencarto.layerStore.getAt(opencarto.layerStore.find('id',id));
            if (the_rec.get('has_point'))
                html += "<img src='"+the_url+my_layers[i]+"_poi' border='0' /><br />";
            if (the_rec.get('has_line'))
                html += "<img src='"+the_url+my_layers[i]+"_loi' border='0' /><br />";
            if (the_rec.get('has_polygon'))
                html += "<img src='"+the_url+my_layers[i]+"_zoi' border='0' /><br />";
        }
    }
    
    my_width = 260;
    my_height = 400;
    
    if (opencarto.chantier_layer){
    	
    	   the_url = globalParams.mapserver.replace('__MAPNAME__', 'chantiers') + 'SLD_VERSION=1.1.0&SERVICE=WMS&REQUEST=GetLegendGraphic&FORMAT=image/png&VERSION=1.3.0&LAYER=';
    
    	    html += "<table><tr><th colspan=2>Chantiers</th></tr>";
           html += "<tr><td><img src='"+the_url+"coord_line' border='0' /><td/>";
           html += "<td><img src='"+the_url+"coord_point' border='0' /><td/></tr></table>";
           html += "<td><img src='"+the_url+"deviation' border='0' /><td/></tr></table>";
           my_width += 50;
           my_height += 50;
    	
    }
    opencarto.legend_html = html;
    if (opencarto.legendWindow)
    {
    	opencarto.legendWindow.destroy();
        opencarto.legendWindow = null;
    	
    }
    ;
    opencarto.legendWindow = new Ext.Window({
    title: 'Légende',
    width: my_width,
    height:my_height,
    minWidth: 200,
    minHeight: 100,
    x:700,
    y:115,
    autoScroll:true,
    constrain:true,
    collapsible:true,
    expandOnShow:true,
    layout: 'fit',
    closeAction :'close',
    plain:true,
    bodyStyle:'padding:5px;',
    buttonAlign:'center',
    html:opencarto.legend_html,
    buttons: [{
       text: 'Fermer',
       handler  : function(){
            opencarto.legendWindow.destroy();
            opencarto.legendWindow = null;
         }

      }]
    });
    opencarto.legendWindow.show();
}


opencarto.changeDate = function(df, nv, ol){
    if(opencarto.chantier_layer){
	opencarto.chantier_layer.mergeNewParams({'fdate':opencarto.date_debut.value,'tdate':opencarto.date_fin.value});
    opencarto.chantier_layer.redraw();
    }
}



opencarto.calculate_length = function(e){
if (opencarto.popup) {
    opencarto.popup.destroy();
    opencarto.popup = null;
}
    var geometry = e.feature.geometry;
    var lng = Math.round(geometry.getLength());
    if (lng > 1000)
        lng = Math.round(lng / 100) / 10 + ' km';
    else
        lng = Math.round(lng) + ' m';
    var point = geometry.components[geometry.components.length - 1];
    opencarto.show_measure(point, lng);
}
opencarto.show_measure = function (point, value) {
    var lonlat = new OpenLayers.LonLat(point.x, point.y);
    var html = '<span style="font-size:small;overflow:scroll">' + value + '</span>';
    nbLignes = html.split('\n').length
    opencarto.popup = new OpenLayers.Popup.FramedCloud("popup",
       lonlat,
       new OpenLayers.Size(250,nbLignes * 12),
       html,
       null,
       true,close_popup_callback);
    opencarto.map.addPopup(opencarto.popup);
}
var close_popup_callback = function(e) {
   opencarto.resultLayer.setZIndex(opencarto.map.Z_INDEX_BASE['Popup'] - 1);
  opencarto.measureLayer.destroyFeatures(opencarto.measureLayer.features);
  if (opencarto.popup) {
      opencarto.popup.destroy();
      opencarto.popup = null;
  }
  OpenLayers.Event.stop(e);
};


