/*
 * 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; 
var timeOutInit = window.setTimeout("",100);
var timerInfoPanneau ;
var close_popup_callback = function(e) {
opencarto.vectorLayer.setZIndex(opencarto.map.Z_INDEX_BASE['Popup'] - 1);
if (opencarto.vector) {
   opencarto.vector.destroy();
   opencarto.vector = null;
}
if (opencarto.popup) {
opencarto.popup.destroy();
opencarto.popup = null;
}
OpenLayers.Event.stop(e);
};
opencarto.features = null;
function create_popup(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);
}
function getFeatureInfo(feature) {
    
    if (opencarto.vector) {
        opencarto.vector.destroy();
        opencarto.vector = null;
   }

    opencarto.vector = feature;
    if (opencarto.popup) {
        opencarto.popup.destroy();
        opencarto.popup = null;
        
    }
    for (i=0;i<opencarto.map.popups.length;i++)
         opencarto.map.removePopup(opencarto.map.popups[i]);
    opencarto.vectorLayer.setZIndex(opencarto.map.Z_INDEX_BASE['Popup'] - 1);
    var geometry = feature.geometry;
    opencarto.actualGeometry = geometry;

    var bounds = opencarto.map.getExtent();
    BBOX = bounds.left + "," + bounds.bottom + "," + bounds.right + "," + bounds.top;
    WIDTH = opencarto.map.size.w;
    HEIGHT = opencarto.map.size.h;  
    X = (feature.geometry.x - bounds.left)/opencarto.map.resolution;
    Y = -(feature.geometry.y - bounds.top)/opencarto.map.resolution;
    var url = 'info/?X='+X+'&Y='+Y+'&BBOX='+BBOX+'&WIDTH='+WIDTH+'&HEIGHT='+HEIGHT+'&layers='
    visibleLayers = opencarto.map.getLayersBy('visibility',true);
    layersToQuery = new Array();       
    for (i=0;i<visibleLayers.length;i++)
    {
        for (j=0;j<opencarto.gisobjects.layers.length;j++)
        {
            myLayer = opencarto.gisobjects.layers[j];
            
            if (visibleLayers[i].name == myLayer.name && visibleLayers[i].calculateInRange() && myLayer.name != 'Google Layer')
                layersToQuery.push(myLayer.options.layerid);

        }
    }
    if (layersToQuery.length > 0){
     url += layersToQuery.join(',');
     OpenLayers.loadURL(url, '', this, displayInfo);
    }
    else{
     Ext.Msg.show({
            title: "ATTENTION",
            msg: "Aucune couche interrogeable n'est visible sur la carte.",
            buttons: Ext.Msg.OK,
            icon: Ext.MessageBox.ERROR
        });
      if (opencarto.vector) {
        opencarto.vector.destroy();
        opencarto.vector = null;
     }
    }
    
}


function displayInfo(request){
  
   var lonlat = new OpenLayers.LonLat(opencarto.actualGeometry.x, opencarto.actualGeometry.y); 
    var html = '<span style="font-size:small;overflow:scroll">' + request.responseText + '</span>';
   nbLignes = request.responseText.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);
}

function calculate_length(feature) {
   if (opencarto.vector) {
      opencarto.vector.destroy();
      opencarto.vector = null;
   }
opencarto.vector = feature;
    if (opencarto.popup) {
       opencarto.popup.destroy();
       opencarto.popup = null;
    }
    var geometry = feature.geometry;
    var lng = Math.round(geometry.getLength());
 /* 	var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT['meter']; 
	    if(inPerDisplayUnit) { 
        var inPerMapUnit = OpenLayers.INCHES_PER_UNIT[opencarto.map.getUnits()]; 
        lng *= (inPerMapUnit / inPerDisplayUnit); 
   }  
   lng = geometry.getLength(opencarto.map.getProjectionObject()); 
   */  
   if (lng > 1000)
       lng = Math.round(lng / 100) / 10 + ' km';
    else
       lng = Math.round(lng) + ' m';
    var point = geometry.components[geometry.components.length - 1];
    create_popup(point, lng);

 
}

function calculate_area(feature) {
  
   if (opencarto.vector) {
      opencarto.vector.destroy();
      opencarto.vector = null;
   }

   opencarto.vector = feature;
   if (opencarto.popup) {
      opencarto.popup.destroy();
      opencarto.popup = null;
   }
   var geometry = feature.geometry;
   area = Math.round(geometry.getArea()); 
   if (area > 1000000)
      area = Math.ceil(area / 10000) / 100 + ' km²';
   else
      area = area + ' m²';
   var perim = Math.ceil(geometry.getLength());
   if (perim > 1000)
      perim = Math.ceil(perim / 10) /100+ ' km';
   else
      perim = perim + ' m';
   var line = geometry.components[geometry.components.length - 1];
   var point = line.components[line.components.length - 1];
   var info = 'Périmètre : ' + perim + '<br />\nSurface : ' + area;
   create_popup(point, info);
}
 
function displayLayer(layerName,v){
   
   ls = opencarto.map.getLayersByName(layerName);
   for (j=0;j<ls.length;j++)
   {           
       
       if (ls[j].name == layerName) {
           ls[j].setVisibility(v); 
      }
   }
}



function loadCapabilities(request) {
      
   var format = new OpenLayers.Format.XML();
   var capa = format.read(request.responseText);
   var result = new Array();
   var parurl = document.getElementById('wmsurlcur').value ;
    
   if (capa.getElementsByTagName('Layer').length > 0) {
      layers = capa.getElementsByTagName('Layer').item(0).getElementsByTagName('Layer');
      for(i=0;i<layers.length;i++){
         result[i] = new Array();
         layer = layers.item(i);
         for(var k=0;k<layer.childNodes.length;k++){
            attr = 	layer.childNodes[k];
            if(attr.tagName && attr.firstChild){
               if(attr.tagName == 'Name' || attr.tagName == 'Title' || attr.tagName == 'SRS'){     					
                  //alert(i + " : "+attr.tagName +" ==>"+attr.firstChild.nodeValue);
                  result[i][attr.tagName]=attr.firstChild.nodeValue;
               }
            }
         } 
      }
   }
   var content = "<table>";
   content += '<tr class="infotbhd">';
   content += '<td>&nbsp;</td>';
   content += '<td>Nom </td>';
   content += '<td>Resumé </td>';
   content += '</tr>';
   nb_ligne = result.length;
   for(b=0;b<result.length;b++){   
      if(result[b]['SRS'] == result[b]['SRS']){
         content += '<tr id="element'+b+'">';
         content += '<td><img src="images/addcat.png" alt="Ajouter la couche" title="Ajouter la couche" onClick="addLayerWms(\''+result[b]['Name']+'\',\''+parurl+'\');"></td>';
         content += '<td>'+result[b]['Name']+'</td>';
         content += '<td>'+result[b]['Title']+'</td>';
         content += '</tr>';
      }
   }
   content += '</table>';				 	
   document.getElementById('liste_couche').innerHTML = content;				
   CapaTransfert = null;     
}


opencarto.layerSelect = function(sm, rIdx, r) {
 
   if (opencarto.selection && opencarto.selection.toolbar.disabled && r.get('options.typegeo') != 'RASTER'){
      opencarto.selection.toolbar.enable();
      
   }
   if (opencarto.selection &&  r.get('options.typegeo') == 'RASTER'){
   		opencarto.selection.toolbar.disable();
   		if (opencarto.selection.addFeatureControl){
   			opencarto.selection.addFeatureControl.deactivate();
   		}
   }
   ls = opencarto.map.getLayersByName(r.get('name'));
   // vidange de la sélection
   
   if (opencarto.selection){
   	opencarto.selection.unSelectAll();
   }
   
}
opencarto.setLayerOpacity = function(item){
   // récupération de la couche sélection

   if (item.checked){
      toks = item.id.split('&');
      alphaValue = toks[1].replace('alpha','');
      layerName = toks[0];
      ls = opencarto.map.getLayersByName(layerName);
      ls[0].setOpacity(alphaValue/100);
   } 
   
}

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




opencarto.onContextClick = function(grid, rowindex,e){
   if(!opencarto.sm.isSelected(rowindex)){
        opencarto.sm.selectRow(rowindex);
   }
   
   this.menu = new Ext.menu.Menu({
       id:'grid-ctx',
       items: []
   });
   //this.menu.on('hide', this.onContextHide, this);
   
   myRec = grid.store.getAt(rowindex);
   
   myOlLayers = opencarto.map.getLayersByName(myRec.get('name'));
   sldItems = null;
   if(opencarto.sld && opencarto.sld && myRec.get('options.sldFiles') && myRec.get('options.sldFiles').length > 0){
      sldItems = new Array();
      
      for (i=0;i<myRec.get('options.sldFiles').length;i++)
      {
         mySldFile = myRec.get('options.sldFiles')[i];
        
         var myItem = new Ext.menu.CheckItem({
            id:'sld'+i,
            text: mySldFile.name,
            group:'sld',
            layer:myOlLayers[0].name,
            sld:mySldFile.sldurl,
            checked: myOlLayers[0].params.SLD== mySldFile.sldurl?true:false,
            checkHandler: opencarto.onSldChange
         });
         sldItems.push(myItem);
      }
      sldItems.push('<b class="menu-title">Edition</b>');
      editItem = new Ext.menu.Item({
            id:'sldEdit',
            text: "Modifier la représentation",
            layer:myOlLayers[0].name,
            sld:myOlLayers[0].params.SLD,
            listeners:{
               click:opencarto.sld.editSLD
            }
            });
      sldItems.push(editItem);
      addItem = new Ext.menu.Item({
            id:'sldAdd',
            text: "Nouvelle représentation",
            layer:myOlLayers[0].name,
            listeners:{
               click:opencarto.sld.editSLD
            }
            });
      sldItems.push(addItem);
      if (globalParams.userAdmin){
         delItem = new Ext.menu.Item({
               id:'sldDel',
               text: "Supprimer la représentation",
               layer:myOlLayers[0].name,
               sld:myOlLayers[0].params.SLD,
               listeners:{
                  click:opencarto.sld.delSLD
               }
               });
         sldItems.push(delItem);
      }
      
   }
   else if(opencarto.sld && myRec.get('options.typegeo') != 'RASTER'){
      sldItems = new Array();
      addItem = new Ext.menu.Item({
            id:'sldAdd',
            text: "Nouvelle représentation",
            layer:myOlLayers[0].name,
            listeners:{
               click:opencarto.sld.editSLD
            }
            });
      sldItems.push(addItem); 
   }
   if (sldItems){
   sldMenu = new Ext.menu.Item({
         text : 'Représentations',
         menu :{
            items:sldItems  
         } 
      })
   }
   if(myRec.get('name') != 'Google Layer'){
      var exportItem1 = new Ext.menu.Item({
           text: 'Zoom sur la couche',
           iconCls: 'zoomToLayer',
           scope:this,
           handler: function(){
               opencarto.zoomToLayer(this.ctxRecord.get('options.layerid'));
           }
      });
      this.menu.add(exportItem1); 
   }
   else{
      var ggItem = new Ext.menu.Item({
        text: 'Choix de la couche Google',
        menu: {  
            items: [
                {
                    id:'G_SATELLITE_MAP',
                    text: 'Satellite',
                    group: 'gmap',
                    checked: globalParams.googlelayer == G_SATELLITE_MAP?true:false,
                    checkHandler: opencarto.setGoogleStyle
                }, {
                   id:'G_NORMAL_MAP',
                    text: 'Fond de Plan',
                    group: 'gmap',
                    checked: globalParams.googlelayer == G_NORMAL_MAP?true:false,
                    checkHandler: opencarto.setGoogleStyle
                }, {
                   id:'G_HYBRID_MAP',
                    text: 'Mixte',
                    group: 'gmap',
                    checked: globalParams.googlelayer == G_HYBRID_MAP?true:false,
                    checkHandler: opencarto.setGoogleStyle
                }, {
                   id:'G_PHYSICAL_MAP',
                    text: 'Relief',
                    group: 'gmap',
                    checked: globalParams.googlelayer == G_PHYSICAL_MAP?true:false,
                    checkHandler: opencarto.setGoogleStyle
                }
            ]
        }
      });
      this.menu.add(ggItem);
   }
   alphaValue = myOlLayers[0].opacity *100;
   opacItems = new Array();
   for (i=10;i<=100;i=i+10){
      var newItem = new Ext.menu.CheckItem({
            id:myRec.get('name') +'&alpha' + i.toString(),
            text: i  + ' %',
            group: 'alpha',
            checked: alphaValue==i?true:false,
            checkHandler: opencarto.setLayerOpacity
        })
      opacItems.push(newItem);
      
   }
   
   var alphaItem = new Ext.menu.Item({
      text: 'Opacité',
             menu: {  
                 items: opacItems
             }

   });
   this.menu.add(alphaItem);
   if(opencarto.dataview && myRec.get('options.typegeo') != 'RASTER'){
      var exportItem1 = new Ext.menu.Item({
         iconCls: 'openTable',
                  text:'Voir les données',
                  scope:this,
                  handler: function(){
                      grid.getSelectionModel().selectRow(rowindex);
                      if (opencarto.selection)
                      	opencarto.selection.unSelectAll();
                      opencarto.datagrid.displayData(this.ctxRecord.get('options.layerid'));
                  }
      });
      this.menu.add(exportItem1); 
   }
   
   if(opencarto.search && opencarto.search.geom != null && myRec.get('options.search') != false){
      var searchItem = new Ext.menu.Item({
         iconCls: 'search',
         text:'Rechercher...',
         scope:this,
         handler: function(){
            opencarto.search.showSearchWindow(this.ctxRecord);
         }
      });
      this.menu.add(searchItem); 
   }
   
   
   if(myRec.get('options.exporter') && myRec.get('options.typegeo') != 'RASTER'){
      var exportItem2 = new Ext.menu.Item({
         iconCls: 'exportData',
                  text:'Exporter...',
                  scope:this,
                  handler: function(){
                      grid.getSelectionModel().selectRow(rowindex);
                      opencarto.showExportWindow(this.ctxRecord);
                  }
      });
      this.menu.add(exportItem2);
   }
   if (opencarto.sld && sldItems)
      this.menu.add(sldMenu);
   if(myRec.get('name') != 'Google Layer'){ 
   var mdItem = new Ext.menu.Item({
         text:'Métadonnées',
         scope:this,
         handler: function(){
            opencarto.showMDWindow(this.ctxRecord);
         }
      });
    // this.menu.add(mdItem);   
   }
   e.stopEvent();
   if(this.ctxRow){
       Ext.fly(this.ctxRow).removeClass('x-node-ctx');
       this.ctxRow = null;
   }
   this.ctxRow = this.view.getRow(rowindex);
   this.ctxRecord = this.store.getAt(rowindex);
   Ext.fly(this.ctxRow).addClass('x-node-ctx');
   this.menu.showAt(e.getXY());
}
opencarto.setGoogleStyle = function(obj){
   myLayerName = obj.id;
   /*myLayers = opencarto.map.getLayersByName('planville');
   myLayers[0].setVisibility(false);
   myLayers = opencarto.map.getLayersByName('ortho');
   myLayers[0].setVisibility(false);
   myLayers = opencarto.map.getLayersByName('mixte');
   myLayers[0].setVisibility(false);
   
   myLayers = opencarto.map.getLayersByName(myLayerName);
   myLayers[0].setVisibility(true);
   */
   myLayers = opencarto.map.getLayersByName(myLayerName);
      opencarto.map.setBaseLayer(myLayers[0]);
}


function renderURL(value, p, record){
   layerID = opencarto.layerGrid.getSelectionModel().getSelected().get('name');
      return String.format(
         '<b><a href="/media/DOCS/{0}/{1}" class="pdflink" target="_blank" title="Cliquer pour télécharger le document"><img src="/media/images/export.png" border="0" />&nbsp;&nbsp;{1}</a></b>',layerID,value);
   }




opencarto.zoomToLayer = function(layerID){

   Ext.Ajax.request({
		url:'../layer/'+layerID+'/extent/?proj=' + globalParams.projection.replace('epsg:',''),
		success:function(res,opt) {
            try{
            eval('geoextent = new OpenLayers.Bounds(' + res.responseText+')');
            opencarto.map.zoomToExtent(geoextent);
            }
            catch(e){
               Ext.Msg.show({
                title: "ERREUR",
                msg: "Le zoom sur la couche a échoué !",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            }); 
            }
        },
         failure: function(res,opt){
		   	Ext.Msg.show({
                title: "ERREUR",
                msg: "Le zoom sur la couche a échoué !",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
		   	return;
		}   
	});
   
   
}
opencarto.onGridCollapse = function(p){
   if (opencarto.map)
      opencarto.map.updateSize(); 
}

opencarto.adminHandler = function() {
   
   f = window.open('/opencarto/admin/','admin');
}

opencarto.showExportWindow = function(rec){
   opencarto.projStore = new Ext.data.JsonStore({
      id: 'ps',
      autoLoad:true,
      url: '../../projections/',
      root: 'projs',
      fields: ['name', 'code']
   });

   var form = new Ext.form.FormPanel({
      baseCls: 'x-plain',
      url:'export',
      items: [{
         id:'cbformat',
         hiddenName:'format',
         xtype: 'combo',
         editable: false,
         fieldLabel: 'Format',
         displayField: 'name',
         valueField: 'code',
         forceSelection:true,
         labelWidth:150,
         emptyText:'Choisir un format...',
         store: new Ext.data.Store({
             reader: new Ext.data.ArrayReader(
                 {}, [
                     {name: 'code'},
                     {name: 'name'},
                 ]
             ),
             data: [
                 ['SHP','ESRI Shapefile'],
                 ['TAB','MapInfo TAB'],
                 ['MIF','MapInfo MIF/MID'],
                 ['GML','GML'],
                 ['KML','KML']
             ]
         }),
         mode: 'local'
         },
        {
         id:'cbprojection',
         hiddenName:'projection',
         triggerAction: 'all',
         labelWidth:150,
         xtype: 'combo',
         lazyInit: true,
         editable: false,
         fieldLabel: 'Projection',
         displayField: 'name',
         valueField: 'code',
         forceSelection:true,
         emptyText:'Choisir une projection...',
         store: opencarto.projStore,
         mode:'local'},
         {
            xtype:'fieldset',
            title: 'Etendue géographique de l\'export',
            autoHeight: true,
            items: [{
                xtype: 'radiogroup',
                fieldLabel: 'Choix de l\'étendue',
                id:'rdextent',
                items: [
                    {boxLabel: 'Tout', name: 'extent', inputValue: 1, checked: true},
                    {boxLabel: 'Fenêtre', name: 'extent', inputValue: 2},
                    {boxLabel: 'Sélection', name: 'extent', inputValue: 3}
                   
                ]
            }
         ]
      }
   ]
  });
         
   opencarto.exportWindow = new Ext.Window({
      title: 'Téléchargement des données SIG',
      width: 400,
      height:220,
      minWidth: 400,
      minHeight: 220,
      layout: 'fit',
      closeAction :'close',
      plain:true,
      bodyStyle:'padding:5px;',
      buttonAlign:'center',
      items:form,
      buttons: [{
          text: 'Télécharger',
          handler : function() {
            vals = form.getForm().getValues(false);
            opencarto.downloadLayer(rec.get('options.layerid'),vals)
          }
      },{
          text: 'Annuler',
          handler  : function(){
               opencarto.exportWindow.destroy();
               opencarto.exportWindow = null;
           }

      }]
   });
        opencarto.exportWindow.show();
 
}
opencarto.downloadLayer = function(idLayer,vals){
   if (idLayer && vals.format && vals.projection)
   {
      var myMask = new Ext.LoadMask(opencarto.exportWindow.getEl(), {
          removeMask:true,
            msg:"Préparation des données en cours..."});
            myMask.show();
   }
   extraOption = ''
   if (vals.extent == 2)
      extraOption = '&extent='+opencarto.map.getExtent().toArray().join(',')+'&projExtent='+globalParams.projection;
   else if(vals.extent == 3)
   {
      if (opencarto.datagrid.grid.getSelectionModel().hasSelection() == false)
      {
         Ext.Msg.show({
                title: "Exportation impossible",
                msg: "Il n'y a pas de sélection dans la grille",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
         myMask.hide();
         return;
      }
      aIds = new Array();
      rows =opencarto.datagrid.grid.getSelectionModel().getSelections();
      for (i=0;i<rows.length;i++)
      {
         aIds.push(rows[i].get('id'));
      }
      extraOption = '&ids=' + aIds.join(',');
   }
   Ext.Ajax.request({
       timeout:120000,
        url:'../export/?objid=' + idLayer + '&f='+vals.format+'&proj=' +vals.projection+extraOption,
		success:function(res,opt) {
         opencarto.exportWindow.destroy();
         opencarto.exportWindow = null;
         this.location = '../getZipFile/?file='+res.responseText
        },
        failure: function(res,opt){
		   opencarto.exportWindow.destroy()
         opencarto.exportWindow = null;
            Ext.Msg.show({
                title: "ERREUR",
                msg: "La donnée n'a pas pu être téléchargée",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
		   	return;
		}
   });
}
opencarto.zoomVector = function(){
   bb = opencarto.getVectorExtent();
   if (bb)
      opencarto.map.zoomToExtent(bb);
   opencarto.datagrid.prepareGeom();
}
opencarto.centerVector = function(){
   bb = opencarto.getVectorExtent();
   if (bb)
   {
      var p = bb.getCenterLonLat();
      opencarto.map.panTo(p);
   }
   
}
opencarto.getVectorExtent = function(){
   var bb = null;
   for (i=0;i<opencarto.vectorLayer.features.length;i++)
   {
      f = opencarto.vectorLayer.features[i];
      if (!bb)
         bb = f.geometry.getBounds();
      else{
         var newBounds = f.geometry.getBounds();
         
         if (newBounds.left < bb.left)
            bb.left = newBounds.left;
         if (newBounds.top > bb.top)
            bb.top = newBounds.top;
         if (newBounds.right > bb.right)
            bb.right = newBounds.right;
         if (newBounds.bottom < bb.bottom)
            bb.bottom = newBounds.bottom;      
      }
      
   }
   return bb;
   
   
}



opencarto.onSldChange = function(item){
    if (item.checked){
      myLayers = opencarto.map.getLayersByName(item.layer);
      myLayers[0].mergeNewParams({sld: item.sld});
      if (opencarto.legend)
      	opencarto.legend.show();
    } 
}

opencarto.ZoomToPosition = function(cb,rec,idx){
   
   x = rec.get('x');
   y = rec.get('y');
   z = rec.get('z');
   if (z != opencarto.map.getZoom()){
      opencarto.map.setCenter(new OpenLayers.LonLat(x,y),z);
   }
   else{
      
      opencarto.map.panTo(new OpenLayers.LonLat(x,y));
   }
   cb.reset();
   
}

opencarto.addPosition = function(){
   Ext.MessageBox.prompt('Nouvelle position', 'Nom de la nouvelle position :', opencarto.savePosition);
   
}
opencarto.savePosition = function(btn,name){
   if (btn == 'ok' && name != ''){
      xy = opencarto.map.getCenter();
      z = opencarto.map.getZoom();
      x = xy.lon;
      y = xy.lat;
      Ext.Ajax.request({
         url:'addposition/',
         params: { 
             name: name,
             x:x,
             y:y,
             z:z
         },
        method: 'GET',
         success:function(res,opt) {
            if (res.responseText == '1'){
               Ext.MessageBox.alert('Succès', 'La position a bien été ajoutée.');
               opencarto.position.positionStore.reload();
            }
            else
               Ext.MessageBox.alert('Erreur', "La position n'a pas pu être ajoutée");
         },
         failure:function(res,opt){
            Ext.MessageBox.alert('Erreur', "La position n'a pas pu être ajoutée");
            
         }
      });
   }
   else if(btn=='ok' && name == '')
       Ext.MessageBox.alert('Erreur', 'Vous devez renseignez le nom de la position', opencarto.addPosition);

   
}

opencarto.getLayerType = function(layerName){
   
   for (i=0;i<opencarto.gisobjects.layers.length;i++)
   {
      myLayer = opencarto.gisobjects.layers[i];
      
      if (myLayer.name == layerName)
         return myLayer.options.typegeo;
      
   }
   return null;
   
   
}
opencarto.getLayerId = function(layerName){
   
   for (i=0;i<opencarto.gisobjects.layers.length;i++)
   {
      myLayer = opencarto.gisobjects.layers[i];
      
      if (myLayer.name == layerName)
         return myLayer.options.layerid;
      
   }
   return null; 
}
opencarto.getLayerName = function(layerId){
   
   for (i=0;i<opencarto.gisobjects.layers.length;i++)
   {
      myLayer = opencarto.gisobjects.layers[i];
      
      if (myLayer.options.layerid == layerId)
         return myLayer.name;
      
   }
   return null; 
}




opencarto.showMDWindow = function(rec){
   
   opencarto.MDWindow = new Ext.Window({
      title: 'Métadonnées',
      width: 400,
      height:220,
      minWidth: 400,
      minHeight: 220,
      layout: 'fit',
      closeAction :'close',
      plain:true,
      bodyStyle:'padding:5px;',
      buttonAlign:'center',
      buttons: [{
          text: 'Fermer',
          handler  : function(){
               opencarto.MDWindow.destroy();
               opencarto.MDWindow = null;
           }

      }]
   });
   opencarto.MDWindow.show();
   
   layer_id = rec.get('options.layerid');
   opencarto.MDtpl = new Ext.Template(
   '<p><b>Format :</b> {format}</p>',
   '<p><b>Type :</b> {type}</p>',
   '<p><b>Projection :</b> {projection}</p>',
   '<p><b>Description :</b> {description}</p>',
   '<p><b>Auteur :</b> {auteur}</p>',
   '<p><b>Source :</b> {source}</p>',
   '<p><b>Date de mise à jour :</b> {dmaj}</p>',
   '<p><b>Echelle :</b> {echelle}</p>',
   '<p><b>Précision :</b> {precision}</p>'
   
   );
   Ext.Ajax.request({
        url: '../metadata/',
        method: 'GET',
        params: {
            layer_id: layer_id 
        },
        success: function(res,opt) {
		   	// affectation de la réponse à un objet global
            try {
                eval('var response = ' + res.responseText);
            } catch(e) {
               
            }
            
           
            if (response) {
               opencarto.MDtpl.overwrite(opencarto.MDWindow.body, response);
               opencarto.MDWindow.body.highlight('#c3daf9', {block:true});
            }
        },
        failure: function(res,opt){
          Ext.MessageBox.alert('Erreur', "Les données n'ont pas pu être récupérées");
         
         
        }
   });  
}
opencarto.getLocation = function(){
	
	opencarto.vectorLayer.destroyFeatures(opencarto.vectorLayer.features);
        adr = opencarto.searchForm.getForm().findField('adresse').getValue();
        city = opencarto.gtCities.getValue();
        if (adr == '') return;
    if(adr.length < 4)
    {
    	Ext.Msg.show({
                title: "Attention",
                msg: "Vous devez saisir au moins 4 caractères pour la recherche.",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.INFO
                });
        return;
    }
	Ext.Ajax.request({
            url:'../../../locadresse/getlocation/?cty='+city+'&adr='+adr+'&proj=3943', // FXP removed 20100322 27563',
                 success:function(res,opt) {
                      //eval('var adresses = ' + res.responseText);
                      geojson = new OpenLayers.Format.GeoJSON();
                      opencarto.features = geojson.read(res.responseText);
                      if (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.vectorLayer.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),8,false,false);
						 	
						 
						 
                      	 //opencarto.map.setCenter(new OpenLayers.LonLat(x-50,y),17,false,false);
                      	 return;
                      }
                      else{
                      	eval('var response = ' + res.responseText);
                      	opencarto.showResults(response)
                      	
                      	
                      }
                     
                    }
                });
        }

opencarto.showResults = 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.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: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.showItem = function(sm,idx,r){
  adr = r.get('properties.adr');
 
  for (i=0;i<opencarto.features.length;i++){
  	if (adr == opencarto.features[i].attributes['adr']){
  		opencarto.vectorLayer.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),17,false,false);
	   return;			 	
  		
  	}
  	
  }
}
opencarto.resetSearch = function(){
	opencarto.vectorLayer.destroyFeatures(opencarto.vectorLayer.features);
	opencarto.searchForm.getForm().findField('adresse').setValue('');
	opencarto.gtCities.value = '31555';	
	
}

opencarto.loadVector = function(){
   
  //opencarto.poi_layer.destroyFeatures(opencarto.poi_layer.features);
     
   Ext.Ajax.request({
        url: '../../getPOIS/',
        method: 'GET',
        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);
           
            opencarto.poi_layer.addFeatures(features);
            
               
        },
        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;
        }
    });
   
   
   
}



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(20, 20),
        'maxSize': new OpenLayers.Size(600, 660)
});

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

opencarto.createPopup = function() {
    if (opencarto.popup) {
        opencarto.deletePopup();
    }
    var lonlat = new OpenLayers.LonLat(opencarto.overFeature.geometry.x , opencarto.overFeature.geometry.y );
   
    var html = '<div style="text-align:left;"><span style="font-size:medium"><b>Point de Contact</b></span>';
    html += '<br /><span style="font-size:small"><b>Pôle n° ' + opencarto.overFeature.attributes["name"] + '</b></span>';
    html += '<br /><span style="font-size:small"><b>Adresse : ' + opencarto.overFeature.attributes["description"] + '</b></span>';
    html += '<br /><span style="font-size:small"><b>Etat : ' + opencarto.overFeature.attributes["etat"] + '</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.deletePopup = function(){
   if (opencarto.popup){
      opencarto.map.removePopup(opencarto.popup);

   opencarto.popup = null;
   }
}

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, []);
    }
});
