/*
 * 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/>.
 */

Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i].id === this[j].id)
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

Ext.namespace('opencarto');
Ext.namespace('opencarto.datagrid');
Ext.namespace('opencarto.selection');

opencarto.tm = null; // timeout
opencarto.gisobjects = {};
opencarto.layercounter = 0;
opencarto.lastControlUsed = 'olControlNavigation';


function init(){
    
    opencarto.menuLeg = new Ext.menu.Menu({
    	id:95,
    	items:[
         ]
    });		
   
   

    
    Ext.Ajax.request({
      
		url:'../rubriques/?t='+globalParams.thematique+'&l='+globalParams.layers,
		disableCaching: false,
		success:function(res,opt) {
                   
            eval('opencarto.rubriques = ' + res.responseText);
	          
	          var reader = new Ext.data.JsonReader({
	          	id:"my_id"
	          }, [
                {name: 'id'},
                {name: 'name'},
                {name: 'groupname'},
				{name: 'checked'},
				{name: 'rang'},
				{name: 'icon'},
				{name: 'mode'},
				{name: 'has_point'},
				{name: 'has_line'},
				{name: 'has_polygon'}
             ]);
			opencarto.layerStore = new Ext.data.GroupingStore({
                reader: reader,
                data: opencarto.rubriques.ssrubriques,
                sortInfo:{field: 'rang', direction: "ASC"},
                groupField:'groupname',
				groupOnSort:true
                
            });
			
			var visibilityColumn = new Ext.grid.CheckColumn({
                header: "Aff.",
                dataIndex: 'checked',
                menuDisabled:true,
                width: 2,
                hidden:false,
                sortable: false,
                resizable:true
             });
            opencarto.layercm = new Ext.grid.ColumnModel([
                visibilityColumn,
                {id:'id',header: "ID", width: 10, hidden:true, sortable: false, dataIndex: 'options.layerid'},
                {id:'name',header: "Rubrique",  width: 120,menuDisabled:true,sortable: false, dataIndex: 'name', renderer: Ext.util.Format.capitalize},
                {header: "Groupe", width: 20, hidden:true, sortable: false,  dataIndex: 'groupname'},
				{header: "rang", width: 20, hidden:true, sortable: true,  dataIndex: 'rang'},
				{header: "mode", width: 20, hidden:true, sortable: true,  dataIndex: 'mode'}
                
                ]);
			opencarto.layerGrid = new Ext.grid.EditorGridPanel({
                store: opencarto.layerStore,
                cm: opencarto.layercm,
				
                //sm:opencarto.sm,
                plugins:visibilityColumn,
                view: new Ext.grid.GroupingView({
                    forceFit:true,
		              startCollapsed:true,
                    // version avec nb de couches : groupTextTpl: '{[values.rs[0].data["options.groupname"]]} ({[values.rs.length]} {[values.rs.length > 1 ? "Couches" : "Couche"]})'
                    groupTextTpl: '{[Ext.util.Format.capitalize(values.rs[0].data["groupname"])]}'
                }),
                autoHeight:false,
				autoScroll:true,
                autoExpandColumn:'name',
               // width:270,

	            height:globalParams.thematique == 'COORDONNE' && globalParams.operators && globalParams.operators.length > 1 ? 200 : 300,

                frame:false,
                border:true,
                hideGroupedColumn:true,
                collapsible: true,
                title: 'Affichage',
                animCollapse: true,
                enableColLock: false,
                //iconCls: 'layerList',
                loadMask: true,
				 stripeRows:true
            });
            
            /*opencarto.layerGrid.getSelectionModel().on(
                'rowselect',opencarto.layerSelect
            );
            opencarto.layerGrid.getSelectionModel().on(
                'rowdeselect',opencarto.layerSelect
            );*/

            target = Ext.getCmp('west-panel');
            
            target.insert(0,opencarto.layerGrid);
			target.doLayout();
			// ajout de la liste des types de poi
			opencarto.searchRubriques = opencarto.rubriques;
			opencarto.searchRubriques.ssrubriques.push({"id":0,"name":" Tous les types "});
			opencarto.searchRubriques.ssrubriques = opencarto.searchRubriques.ssrubriques.unique();
            opencarto.PoiTypesCombo = new Ext.form.ComboBox({
				id: 'cbpoitype',
				fieldLabel: "Type",
				displayField: 'name',
				hiddenName:'poitype',
				allowBlank:true,
				valueField: 'id',
				width: 160, 
				height: 30,
				editable: false,
				typeAhead: true,
				mode: 'local',
				triggerAction: 'all',
	 
				emptyText: "Choisir un type de lieu",
				selectOnFocus: true,
				store: new Ext.data.JsonStore({
					data: opencarto.searchRubriques,
					root: 'ssrubriques',
					sortInfo: {field: "name", direction: "ASC"},
					fields: ['id', 'name']
			})
	    });
			target = opencarto.searchPoiForm;
            target.insert(0,opencarto.PoiTypesCombo);
            target.doLayout();
			
            opencarto.map.events.register('zoomend',this,function(){
                opencarto.checkZoomLevel();
                opencarto.refreshRadius();
            });
			opencarto.map.events.register('moveend',this,function(){
                opencarto.refreshRadius();
            });
           // opencarto.computeLegend();
			
/*		
	opencarto.toolbar.add({
   		text:'Légende',
   		iconCls: 'bmenu',
   		menu:opencarto.menuLeg
   }) 
	opencarto.LegendToolbar = new Ext.Toolbar.MenuButton({
			id: 95,
			tooltip: 'Légende',
			tooltipType:'title',
			text: 'Légende',
			enableToggle: false,
			pressed: false,
			disabled:false,
			menu:{
				
			}
		});
  */  
		//opencarto.toolbar.add(opencarto.LegendToolbar);
		
	    // ajout des sous-rubriques cochées au chargement
	   for (i=0;i<opencarto.rubriques.ssrubriques.length;i++){
		r = opencarto.rubriques.ssrubriques[i];
		if (r.checked){
		
			displayLayer(r.id,true,r.mode);
			
		}

	   }
		},
		failure: function(res,opt){
		   	Ext.Msg.show({
                title: "ERREUR",
                msg: "Le flux de description des couches n'a pas pu être chargé",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
		   	return;
		}   
	});
	/*
	 Ext.Ajax.request({
      
        url:'../cities/',
        disableCaching: false,
        success:function(res,opt) {
            
            eval('gtCities = ' + res.responseText);
        },
        failure:function(res,opt){
        	alert("La liste des communes n'a pas pu être chargée");
        }
	 })
	 */
var zoomToMaxExtentControl = new OpenLayers.Control.ZoomToMaxExtent();
var zoomBoxControl = new OpenLayers.Control.ZoomBox();
var navigationControl = new OpenLayers.Control.Navigation();
mapOptions = {
    projection: new OpenLayers.Projection("EPSG:3943"),
    displayProjection: new OpenLayers.Projection("EPSG:3943"),
    animate:false,
    resolutions: globalParams.resolutions,
    maxExtent: globalParams.maxExtent,
    controls:[
                new OpenLayers.Control.PanZoomBar(),
                zoomToMaxExtentControl, zoomBoxControl, navigationControl
                ]
    };
    

opencarto.mapPanel = new Ext.ol.OLPanel(mapOptions);
opencarto.toolbar = new Ext.Toolbar();
opencarto.Mask = new Ext.LoadMask(Ext.getBody(), {msg:"Merci de patienter..."});
   
   
gtCities = { cities:[
    {id:'31555', name:'Toulouse'},
    {id:'31205', name:'Gagnac-sur-Garonne'},
    {id:'31541', name:'Seilh'},
    {id:'31116', name:'Castelginest'},
    {id:'31467', name:'Saint-Alban'},
    {id:'31182', name:'Fenouillet'},
    {id:'31032', name:'Aussonne'},
    {id:'31351', name:'Mondonville'},
    {id:'31186', name:'Fonbeauzard'},
    {id:'31022', name:'Aucamville'},
    {id:'31282', name:'Launaguet'},
    {id:'31056', name:'Beauzelle'},
    {id:'31150', name:'Cornebarrieu'},
    {id:'31069', name:'Blagnac'},
    {id:'31417', name:'Pibrac'},
    {id:'31088', name:'Brax'},
    {id:'31149', name:'Colomiers'},
    {id:'31557', name:'Tournefeuille'},
    {id:'31157', name:'Cugnaux'},
    {id:'31588', name:'Villeneuve Tolosane'},
    {id:'31561', name:'L\'Union'},
    {id:'31044', name:'Balma'},
    {id:'31418', name:'Pin Balma'},
    {id:'31445', name:'Quint-Fonsegrives'},
    {id:'31003', name:'Aigrefeuille'},
    {id:'31053', name:'Beaupuy'},
    {id:'31091', name:'Bruguières'},
    {id:'31163', name:'Drémil-Lafage'},
    {id:'31184', name:'Flourens'},
    {id:'31230', name:'Gratentour'},
    {id:'31293', name:'Lespinasse'},
    {id:'31352', name:'Mondouzil'},
    {id:'31355', name:'Mons'},
    {id:'31389', name:'Montrabé'},
    {id:'31488', name:'Saint-Jean'},
    {id:'31490', name:'Saint-Jory'},
    {id:'31506', name:'Saint-Orens-de-Gameville'}
    ]
}
opencarto.gtCities = new Ext.form.ComboBox({
   id: 'cbcity',
   fieldLabel: "Commune",
   displayField: 'name',
   hiddenName:'city',
   allowBlank:false,
   valueField: 'id',
   width: 170,
   height: 30,
   editable: false,
   typeAhead: true,
   mode: 'local',
   triggerAction: 'all',
   forceSelection:true,
   value:'31555',
   lazyInit:false,
   selectOnFocus: true,
   store: new Ext.data.JsonStore({
        data: gtCities,
        root: 'cities',
        sortInfo: {field: "name", direction: "ASC"},
        fields: ['id', 'name']
   })
});

// ajout formulaire de recherche d'adresse
opencarto.searchForm  =new Ext.form.FormPanel({
    labelWidth:60,
collapsible:true,
collapsed:false,
    frame:true,
            title:"Trouver une adresse...",
    items:[
                    {
                    xtype:'textfield',
                    fieldLabel: 'Adresse',
                    name: 'adresse',
                    id:'find_adresse',
                    width: 170,
                    minLength:2
                    },
	opencarto.gtCities
    ]
});

opencarto.searchForm.addButton('Afficher', opencarto.getLocation);
opencarto.searchForm.addButton('Effacer', opencarto.resetAdrSearch);
// Slider de recherche
opencarto.radiusSlider = new Ext.Slider({
	width: 190,
	minValue: 0,
	maxValue: 5000,
	 increment: 50,
	plugins: new Ext.ux.SliderTip(),
	listeners:{
                    drag:opencarto.syncMapToSlider
                    
                }
	});
   
opencarto.searchPoiForm  =new Ext.form.FormPanel({
    labelWidth:50,
    frame:true,
	title:"Trouver un lieu...",
    items:[
		
		{
		xtype:'textfield',
		fieldLabel: 'Nom',
		name: 'poiname',
		id:'poiname',
		width: 160,
		minLength:3,
		minLengthText:"Veuillez saisir un minimum de 3 lettres. Merci."
		},
		{
        xtype:'fieldset',
		width: 215,
        checkboxToggle:false,
        title: 'Distance au centre de la carte :',
        autoHeight:true,
        defaultType: 'textfield',
        collapsed: false,
		collapsible: false,
        items :[opencarto.radiusSlider]
		}
		
    ]
})
	
// Préparation des items de recherche de chantier
opencarto.filterFormItems = new Array();

if (globalParams.thematique == 'COORDONNE' && globalParams.operators && globalParams.operators.length > 1){
 
 opencarto.cb_operator = new Ext.form.CheckboxGroup({
 	hideLabel:true,      
	//   fieldLabel: 'Opérateurs',
            // Specify exact column widths (could also include float values for %)
              width:240,
            
              columns: 2,//[150,150],
              vertical: true,
              items: globalParams.operators

	 });
	// opencarto.filterFormItems.push(opencarto.cb_operator);
 
}
 if (globalParams.thematique == 'COORDONNE' && globalParams.operators){
 	
 	cb1 = true;
 	cb2 = true;
 	cb3 = false;
 
 opencarto.cb_status = new Ext.form.CheckboxGroup({
 	         id:'cbg_status',
         fieldLabel: 'Statut',
        // Specify exact column widths (could also include float values for %)
        columns:[300],
        defaultType: 'checkbox',

        vertical: true,
        items: [
            {   
            	fieldLabel:'',
            	boxLabel: 'Demande',
            	name: 'cb-custwidth1',
            	inputValue: 0,
            	checked: cb1,
            	listeners:{
                    check:opencarto.changeStatus
                }
            },
            {
            	fieldLabel:'',
            	boxLabel: 'Faisabilité acceptée',
            	name: 'cb-custwidth2',
            	inputValue: 1,
            	checked: cb2,
                listeners:{
                    check:opencarto.changeStatus
                }
            	
            	},
            {
                fieldLabel:'',
                boxLabel: 'Terminé',
                name: 'cb-custwidth3',
                inputValue: 2,
                checked: cb3,
                listeners:{
                    check:opencarto.changeStatus
                }
                    
                 }
                
                
            ]
 })
 

    opencarto.filterFormItems.push(opencarto.cb_status);
    opencarto.cb_label = new Ext.form.Checkbox({
	    fieldLabel:'Afficher labels',
	    name: 'cb-lab',
	    inputValue: 0,
	    checked: false,
	    listeners:{
	        check:opencarto.displayLabels
	    }
    });
    opencarto.filterFormItems.push(opencarto.cb_label);
    opencarto.cb_dev = new Ext.form.Checkbox({
        fieldLabel:'Afficher déviations',
        name: 'cb-lab',
        inputValue: 0,
        checked: true,
        listeners:{
            check:opencarto.displayDevs
        }
    });
    opencarto.filterFormItems.push(opencarto.cb_dev);

}



opencarto.aForms = new Array();


 if (globalParams.thematique == 'COORDONNE' && globalParams.operators && globalParams.operators.length == 1){
     opencarto.cb_all = new Ext.form.Checkbox({
        fieldLabel:'Autres chantiers',
        name: 'cb-all',
        inputValue: 0,
        
        checked: false,
        listeners:{
            check:opencarto.displayAll
        }     
     });
     opencarto.filterFormItems.push(opencarto.cb_all);
     opencarto.cb_status.fieldLabel = 'Mes chantiers';
 }
 
 if (globalParams.thematique == 'COORDONNE' && globalParams.operators) {
	opencarto.date_debut = new Ext.form.DateField({
	 	fieldLabel: 'Entre le',
	    name:'date_debut',
	    id:'date_debut',
	    //value:new Date(),
	   // vtype: 'daterange',
	   // endDateField: 'date_fin', // id of the start date field
	    listeners:{
	        valid:opencarto.changeDate
	        
	    }
	 });
	opencarto.filterFormItems.push(opencarto.date_debut);
	 
	opencarto.date_fin = new Ext.form.DateField({
	    fieldLabel: 'Et le',
	    name:'date_fin',
	    id:'date_fin',
	 // value:date2,
	 //   vtype: 'daterange',
	  //  startDateField: 'date_debut',
	    listeners:{
	        valid:opencarto.changeDate
	    }
	});
	opencarto.filterFormItems.push(opencarto.date_fin);
	
	opencarto.filterForm=new Ext.form.FormPanel({
	    title:"Chantiers...",
	    frame:true,
	    labelWidth:50,
	   // height:Ext.lib.Dom.getDocumentHeight() - 400,
	   height:260,
	    autoScroll:true,
	   collapsible:true,
	    iconCls:'icon_chantier',
	    items:opencarto.filterFormItems    
	});
	opencarto.aForms.push(opencarto.filterForm);
	if (opencarto.cb_operator){
		
		
		opencarto.filterForm2  =new Ext.form.FormPanel({
		    title:"Opérateurs...",
		    frame:true,
		    labelWidth:10,
		    //height:Ext.lib.Dom.getDocumentHeight() - 400,
		   // height:Ext.lib.Dom.getDocumentHeight() - 620,
		   
		    autoScroll:true,
		    collapsible:true,
		    collapsed:true,
		    iconCls:'icon_chantier',
		    items:[opencarto.cb_operator]  ,
		    buttons: [{
	            text: 'Tout décocher',
	            handler: function(){
	                
	                for (y=0;y<opencarto.cb_operator.items.length;y++){
	                	opencarto.cb_operator.items.items[y].setValue(false);
	                }
	            
	            }
	        },{
	            text: 'Tout cocher',
	            handler: function(){
	                
	                for (y=0;y<opencarto.cb_operator.items.length;y++){
	                    opencarto.cb_operator.items.items[y].setValue(true);
	                }
	            
	            }
	        }]
		      
		});
	   opencarto.aForms.push(opencarto.filterForm,opencarto.filterForm2);
	} 
 }
opencarto.aForms.push(opencarto.searchForm);
   // opencarto.searchPoiForm.add(opencarto.radiusSlider);
opencarto.searchPoiForm.addButton('Afficher', opencarto.loadVector);
opencarto.searchPoiForm.addButton('Effacer', opencarto.resetSearch);
if (globalParams.thematique != 'COORDONNE' && globalParams.thematique != 'DEVIATION'){
	searchItems = Array(opencarto.searchForm,opencarto.searchPoiForm);
}
else if(globalParams.thematique == 'COORDONNE' && globalParams.op_layer != 'generic'){
	searchItems = opencarto.aForms;
}
else{
	searchItems = Array(opencarto.searchForm);
}

opencarto.searchPanel = new Ext.Panel({
    id: 'positionPanel',
    title: globalParams.thematique == 'COORDONNE' ? '' : 'Recherche',
    //iconCls: 'positions',
    collapsible:true,
    border:true,
    frame:false,
    autoScroll:true,
    titleCollapse: true,
    items :searchItems
});

opencarto.viewport = new Ext.Viewport({
    layout:'border',
    items:[
      {
	    region:'north',
        contentEl:"title",
        heigth:90
      },{
        region:'west',
        id:'west-panel',
		border:false,
        frame:false,
        //title:'OUTILS',
        split:true,
        width: 290,
        height:700,
        minSize: 175,
        maxSize: 400,
        animate:true,
        collapsible: false,
        collapseMode: 'mini',
        collapsed:false,
        margins:'0 0 0 0',
        autoScroll:true,
        items: [opencarto.searchPanel],
        listeners:{
            collapse:opencarto.resizeMap,
            expand:opencarto.resizeMap
        }
      }, 
      {
        region:'center',
        layout: 'border',
        border: false,
        frame:false,
        bbar:opencarto.bbar,
        items:[{
            region: 'center',
            tbar:opencarto.toolbar,
          //  title: globalParams.thm,
            layout: 'fit',
            collapsible: false,
            collapsed: false,
            split: true,
            
            minSize: 100,

            items: [opencarto.mapPanel]
        }]
       }
   ]
});
    
   
opencarto.toolbar.add(
        new Ext.Toolbar.Button({
            id: 10,
            autoHeight:true,
            iconCls: 'fullextent',
    overCls:'fullextent',
    tooltip: 'Vue générale',
    
    tooltipType:'title',
    //text: 'Vue générale',
            enableToggle: false,
            pressed: false,
            handler: opencarto.toolbarHandler
        })
);
opencarto.toolbar.add(
    new Ext.Toolbar.Button({
	    id: 11,
	    iconCls: 'zoomIn',
	    overCls:'zoomIn',
	    tooltip: 'Zoom avant ou par tracé de rectangle',
	    tooltipType:'title',
	    enableToggle: false,
	    pressed: false,
	    handler: opencarto.toolbarHandler
    })
);
opencarto.toolbar.add(
    new Ext.Toolbar.Button({
	    id: 12,
	    iconCls: 'zoomOut',
	    tooltip: 'Zoom arrière',
	    tooltipType:'title',
	    //text: 'Zoom -',
	    enableToggle: false,
	    pressed: false,
	    handler: opencarto.toolbarHandler
    })
);
opencarto.toolbar.add(
    new Ext.Toolbar.Button({
        id: 13,
        iconCls: 'pan',
        tooltip: 'Déplacement, et zoom avec la molette',
        tooltipType:'title',
        //text: 'Déplacement',
        enableToggle: false,
        pressed: true,
        handler: opencarto.toolbarHandler
    })
);
opencarto.toolbar.add(
    new Ext.Toolbar.Button({
        id: 16,
        iconCls: 'info',
        tooltip: 'Informations',
        tooltipType:'title',
        //text: 'Déplacement',
        enableToggle: false,
        pressed: false,
        handler: opencarto.toolbarHandler
    })
);

opencarto.toolbar.add(
    new Ext.Toolbar.Button({
        id: 20,
        iconCls: 'print',
        tooltip: 'Imprimer',
        tooltipType:'title',
        //text: 'Déplacement',
        enableToggle: false,
        pressed: false,
        handler: opencarto.toolbarHandler
    })
);
opencarto.toolbar.add(
    new Ext.Toolbar.Button({
        id: 21,
        iconCls: 'legend',
        tooltip: 'Afficher la légende',
        tooltipType:'title',
        //text: 'Déplacement',
        enableToggle: false,
        pressed: false,
        handler: opencarto.toolbarHandler
    })
);

opencarto.toolbar.add(
    new Ext.Toolbar.Button({
        id: 27,
        iconCls: 'permalink',
        tooltip: 'Permalien vers cette vue',
        tooltipType:'title',
        //text: 'Déplacement',
        enableToggle: false,
        pressed: false,
        handler: opencarto.toolbarHandler
    })
);
if (globalParams.add_measure){
	opencarto.toolbar.add(
	    new Ext.Toolbar.Button({
		id:30,
		iconCls:'measure',
		tooltip:'Mesurer une longueur',
		tooltipType:'title',
		enableToggle:true,
		pressed:false,
		handler:opencarto.toolbarHandler
	   })
       );

}


    

raster_items = new Array();
for (i=0;i<globalParams.rasters.length;i++){
    obj = globalParams.rasters[i];
    var item = new Ext.menu.CheckItem({
    	id:obj.layer_name,
    	text:obj.name,
    	group:'gmap',
    	checked:i==0?true:false      	
    });
   
    raster_items.push(item);
}
var menu = new Ext.menu.Menu({
	id:99,
	items:raster_items,
	listeners:{
        itemclick:opencarto.setGoogleStyle
    }
});


// réglage final de la date max
if (opencarto.date_debut){
	dated = new Date();
	opencarto.date_debut.setValue(dated);
	    
	dated.setFullYear(dated.getFullYear() + 1);
	opencarto.date_fin.setValue(dated);
}
/*
if (window.outerWidth)
    window.outerWidth = window.outerWidth - 1;
else if (document.documentElement.clientWidth)
    window.resizeTo(document.documentElement.clientWidth-1,document.documentElement.clientHeight + 160);
 */
    
    
opencarto.map = opencarto.mapPanel.getMap();
for (i=0;i<globalParams.rasters.length;i++){
	obj = globalParams.rasters[i];
	layer = new OpenLayers.Layer.WMS(
	    obj.layer_name,
	    obj.url,
	    {
	    	"layers":obj.layer_name,
	    	"format":obj.format
	    },
	    {
	    	 "attribution":obj.attribution,
	    	 "buffer":0,
	    	 "alwaysInRange":false,
	    	 "transitionEffect":"none",
	    	 "visibility":false,
	    	 "isBaseLayer":true,
	    	 resolutions:globalParams.resolutions
	    }
	  );
	  opencarto.map.addLayer(layer);
	
}


opencarto.batlayer = new OpenLayers.Layer.WMS(
    'bati',
    'http://maps.cugt.org/maps/referentiel_cugt/',
    {
        'layers':'bat_pub_tlse',
        'format':'AGG'
     },
    {
    	'buffer':0,
        'singleTile':true,
    	'alwaysInRange':false,
    	'visibility':false,
    	resolutions:globalParams.resolutions,
    	'isBaseLayer':false
    }
);
opencarto.map.addLayer(opencarto.batlayer);
opencarto.batlayer.maxResolution = 3;

opencarto.vectorStyles = new OpenLayers.StyleMap({
    "default": new OpenLayers.Style({
        pointRadius:"${radius}",
        strokeColor:"#680404",
        fillColor:"#dc3838",
        strokeWidth:2,
        fillOpacity:0.3
    })
});
var measureStyles = new OpenLayers.StyleMap({
    "default": new OpenLayers.Style({
        strokeColor:"#666666",
        strokeDashstyle: "dash",
	strokeWidth:3,
        strokeOpacity:1
    })
});
opencarto.poilayer = new OpenLayers.Layer.WMS(
    'poi_wms',
    globalParams.mapserver.replace('__MAPNAME__', globalParams.map_file),
    //globalParams.mapserver+globalParams.map_file,
    {
        'layers':'fake,num',
        'format':'PNG'
    },
    {
        'visibility':true,
        resolutions:globalParams.resolutions,
        'isBaseLayer':false,
        'singleTile':true
    }
);
opencarto.map.addLayer(opencarto.poilayer);



/*
opencarto.batlayerlab = new OpenLayers.Layer.WMS(
    'batilab',
    globalParams.mapserver+'map='+globalParams.map_file,
    {
    	'layers':'bat_pub_tlse_labels',
    	'format':'AGG'
    },
    {
    	'visibility':false,
    	resolutions:globalParams.resolutions,
    	'isBaseLayer':false,
    	'singleTile':true
    }
);
opencarto.map.addLayer(opencarto.batlayerlab);
opencarto.batlayerlab.maxResolution = 3;
*/
// création de la couche des POI
opencarto.poiStyles = new OpenLayers.StyleMap({
	"default": new OpenLayers.Style({
	backgroundXOffset: -5,
	backgroundYOffset: -5,
	externalGraphic: globalParams.mediaURL+"${icon}",
	//backgroundGraphic: globalParams.mediaURL+"${shadow}",
	graphicZIndex:11,
	backgroundGraphicZIndex:10,
	graphicWidth: '${iconsize}',
	graphicHeight: '${iconsize}',
	cursor: 'pointer',
	strokeColor: "#ff9933",
    strokeWidth: 2,
    fillColor:"#FFFFFF"
	
	
}),
	"select": new OpenLayers.Style({
		graphicWidth: 24,
		graphicHeight: 24
	}),
	"hidden": new OpenLayers.Style({
		graphicWidth: 0,
		graphicHeight: 0
	})
});

opencarto.poi_layer = new OpenLayers.Layer.Vector("POI", {
	styleMap: opencarto.poiStyles,
	visibility: true
});
opencarto.map.addLayer(opencarto.poi_layer);


opencarto.poi_hoverControl = new OpenLayers.Control.Hover(
	opencarto.poi_layer, {
		overFeature: function(feature) {
		
			opencarto.preparePopup(feature);
		},
		outFeature: function(feature) {
			if (opencarto.tm) {
				clearTimeout(opencarto.tm);
			}
			if (opencarto.popup) {
				opencarto.tm = setTimeout("opencarto.deletePopup()", 2000);
			}
		},
		clickFeature: function(feature) {
			//opencarto.showInfo(feature);
		},
		clickoutFeature: function(feature) {
			opencarto.poi_layer.drawFeature(feature, "default");
			
		}
	}
);
opencarto.map.addControl(opencarto.poi_hoverControl);
opencarto.poi_hoverControl.activate();


var overview1 = new OpenLayers.Control.OverviewMap({
            maximized: false,
            size: new OpenLayers.Size(200,200),
            minRatio:16,
            maxRatio:64
       });
      
opencarto.map.addControl(overview1)


opencarto.vector_layer = new OpenLayers.Layer.Vector('recherche', {
	visibility: true,
	styleMap: opencarto.vectorStyles,
	geometryType:OpenLayers.Geometry.Point
});
opencarto.map.addLayer(opencarto.vector_layer);

// info standard WMS
opencarto.infoCtrl = new OpenLayers.Control({
    CLASS_NAME:'infoCtrl',
    displayClass:'olInfoCtrl',
    activate: function() {
        var handlerOptions = {
           'single': true,
           'double': false,
           'pixelTolerance': 0,
           'stopSingle': false,
           'stopDouble': false
        };
        this.handler = new OpenLayers.Handler.Click(this, {
            'click': this.onClick
        }, handlerOptions);
        this.protocol = new OpenLayers.Protocol.HTTP({
            //url: '/cgi-bin/mapserv?map='+globalParams.map_file, 
            url: '../info/',
	       format: new OpenLayers.Format.WMSGetFeatureInfo()
        });
        OpenLayers.Control.prototype.activate.call(this);
     },
     x:0,
     y:0,
     onClick: function(e) {
        this.x = e.xy.x;
        this.y = e.xy.y;
        this.protocol.read({
            params: {
                REQUEST: "GetFeatureInfo",
                EXCEPTIONS: "application/vnd.ogc.se_xml",
                VERSION: "1.1.1",
                BBOX: opencarto.map.getExtent().toBBOX(),
                SERVICE:'WMS',
                X: e.xy.x,
                Y: e.xy.y,
                SRS:'EPSG:3943',
                INFO_FORMAT: 'gml',
                LAYERS: opencarto.poilayer.params.LAYERS.replace('fake,num,',''),
                QUERY_LAYERS: opencarto.poilayer.params.LAYERS.replace('fake,num,',''),
                WIDTH: opencarto.map.size.w,
                HEIGHT: opencarto.map.size.h
            },
            callback: this.onResponse,
            scope: this
        });
     },

     onResponse: function(response) {
         if (response.features && response.features.length > 0){
            var a = response.features[0].attributes;
            a["x"] = this.x;
            a["y"] = this.y;
            opencarto.preparePopupXML(a); 
         }
     }
});

opencarto.map.addControl(opencarto.infoCtrl);


opencarto.map.addControl(new OpenLayers.Control.Attribution());

 drawStyle = new OpenLayers.StyleMap({
        "default": new OpenLayers.Style({
            fillOpacity: 0.6,
            strokeColor: "#911111",
            fillColor: "#dc3838",
            strokeWidth: 3,
            cursor: 'pointer',
            pointRadius:8
        }),
        "select": new OpenLayers.Style({
            fillOpacity: 0.9,
            strokeColor: "#00FF00",
            pointRadius:5
        })
    }) ;
opencarto.resultLayer = new OpenLayers.Layer.Vector("vector",{
        styleMap:  drawStyle                                                                                                  
    }); 
 opencarto.map.addLayer(opencarto.resultLayer);

    if (globalParams.add_measure){

      opencarto.measureLayer = new OpenLayers.Layer.Vector("measure",{
         styleMap:  drawStyle, geometryType:OpenLayers.Geometry.Line
      }); 
      opencarto.measureLayer.events.register(
		  "featureadded",
		  this,
		  opencarto.calculate_length
     );
     opencarto.map.addLayer(opencarto.measureLayer);
     opencarto.calculateLengthControl = new OpenLayers.Control.DrawFeature(
         opencarto.measureLayer,
         OpenLayers.Handler.Path,
         {
             displayClass: "olControlCalculateLength",
     handlerOptions:{layerOptions:{styleMap:measureStyles}}
        }
    );
    opencarto.map.addControl(opencarto.calculateLengthControl);
    }
/*
      if (window.outerWidth)
        window.outerWidth = window.outerWidth - 1;
    else if (document.documentElement.clientWidth)
        window.resizeTo(document.documentElement.clientWidth-1,document.documentElement.clientHeight + 160);
*/	
	
	if (globalParams.center && globalParams.zoom){
		opencarto.map.setCenter(globalParams.center, globalParams.zoom);
		opencarto.map.setBaseLayer(opencarto.map.getLayersByName(globalParams.baselayer)[0])
		
	}
	else{
		lon = 1573780;
		lat = 2268957;
		zoom = 3; 
		opencarto.map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); 
	}
   
    opencarto.map.updateSize();
    

    opencarto.mapPanel.doLayout();
    if (opencarto.coordonne)
        opencarto.coordonne.init();
    if (opencarto.deviation)
        opencarto.deviation.init();
    
    
    opencarto.toolbar.add({
	    text:'Choix du fond de plan',
	    iconCls: 'bmenu',
	    menu:menu
    }); 
    
    
    if (globalParams.adr != ''){
        tok = globalParams.adr.split('$$');	
    	opencarto.searchForm.getForm().findField('adresse').setValue(tok[0]);
        opencarto.gtCities.value = tok[1];
    	opencarto.getLocation();
    	
    }    
    
}


Ext.grid.CheckColumn = function(config){
    Ext.apply(this, config);
    if(!this.id){
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype ={
    init : function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown : function(e, t){
        if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
            e.stopEvent();
            var index = this.grid.getView().findRowIndex(t);
            var record = this.grid.store.getAt(index);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
            // récupération du nom du layer
            displayLayer(record.get('id'),record.get('checked'),record.get('mode'));
        }
    },

    renderer : function(v, p, record){

        p.css += ' x-grid3-check-col-td'; 
        return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
    }
};

Ext.ux.SliderTip = Ext.extend(Ext.Tip, {
    minWidth: 10,
    offsets : [0, 40],
    init : function(slider){
        slider.on('dragstart', this.onSlide, this);
        slider.on('drag', this.onSlide, this);
        //slider.on('dragend', this.onEnd, this);
        slider.on('destroy', this.destroy, this);
        slider.on('change', this.onChange, this);
    },
    onChange : function(slider){
        if (slider.getValue() == 0)
            this.hide();
    },
    onSlide : function(slider){
        this.show();
        this.body.update(this.getText(slider));
        this.doAutoWidth();
        this.el.alignTo(slider.thumb, 'b-t?', this.offsets);
        if (slider.getValue() == 0)
            this.hide();
    },

    getText : function(slider){
        return slider.getValue()+" mètres";
    }
});
Ext.apply(Ext.form.VTypes, {
    daterange : function(val, field) {
        var date = field.parseDate(val);

        if(!date){
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        } 
        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
            var end = Ext.getCmp(field.endDateField);
            end.setMinValue(date);
            end.validate();
            this.dateRangeMin = date;
        }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
});

OpenLayers.Util.modifyAlphaImageDiv = function(div, id, px, sz, imgURL, 
                                       position, border, sizing, 
                                       opacity) {

        OpenLayers.Util.modifyDOMElement(div, id, px, sz, position,
                                         null, null, opacity);
    
        var img = div.childNodes[0];
    
        if (imgURL) {
            img.src = imgURL;
        }
        OpenLayers.Util.modifyDOMElement(img, div.id + "_innerImage", null, sz, 
                                         "relative", border);
        
        if (OpenLayers.Util.alphaHack()) {
            if(div.style.display != "none") {
                div.style.display = "inline-block";
            }
            if (sizing == null) {
                sizing = "scale";
            }
            div.style.filter = 'progid:DXImageTransform.Microsoft' +
                               '.AlphaImageLoader(src="' + img.src + '", ' +
                               'sizingMethod="' + sizing + '")';
            if (parseFloat(div.style.opacity) >= 0.0 && 
                parseFloat(div.style.opacity) < 1.0) {
                div.style.filter += " alpha(opacity=" + div.style.opacity * 100 + ")";
            }
    
            img.style.filter = "alpha(opacity=0)";
        }
    };
    
Ext.override(Ext.form.Field, {
    onRender : function(ct, position){
        Ext.form.Field.superclass.onRender.call(this, ct, position);
        if(!this.el){
            var cfg = this.getAutoCreate();
            if(!cfg.name){
                cfg.name = this.name || this.id;
            }
            if(this.inputType){
                cfg.type = this.inputType;
            }
            if(this.tooltip){
                cfg['ext:qtip'] = this.tooltip.tip;
                cfg['ext:qwidth'] = this.tooltip.width || 100;
            }
            this.el = ct.createChild(cfg, position);
        }
        var type = this.el.dom.type;
        if(type){
            if(type == 'password'){
                type = 'text';
            }
            this.el.addClass('x-form-'+type);
        }
        if(this.readOnly){
            this.el.dom.readOnly = true;
        }
        if(this.tabIndex !== undefined){
            this.el.dom.setAttribute('tabIndex', this.tabIndex);
        }
       
        this.el.addClass([this.fieldClass, this.cls]);
        this.initValue();
    }
});






