/*
 * 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/>.
 */
Ext.BLANK_IMAGE_URL = '/insee_media/js/ext-2.2/resources/images/default/s.gif';


Ext.namespace('opencarto');
Ext.namespace('opencarto.datagrid');
Ext.namespace('opencarto.selection');
Ext.namespace('opencarto.sld');
Ext.namespace('opencarto.print');
Ext.namespace('opencarto.search');
opencarto.tm = null; // timeout
opencarto.gisobjects = {};
opencarto.layercounter = 0;
opencarto.lastControlUsed = 'olControlNavigation';

function init() {
   
    // fonction de chargement du flux JSON d'initialisation
   // statusBar.showBusy();
    
    Ext.Ajax.request({
      
		url:'layers/',
		success:function(res,opt) {
                   
            eval('opencarto.gisobjects = ' + res.responseText);
            
  
            // ajout éventuel du fond Google
            if(globalParams.googlelayer){

                opencarto.gisobjects.layers.unshift({"name":"Google Layer","label":"Couche Google","alwaysInRange":false,"url":"",
                "params":{"type":globalParams.googlelayer,'sphericalMercator': false},
                "options":{"layerid":0,"alpha":true,"opacity":100,"resolutions":globalParams.resolutions,"buffer":0,"exporter":false,"visibility":true,"groupe":0,
                    "groupname":"GOOGLE","grouporder":"0","rang":1,"typegeo":"RASTER","sld":"null","search":false}});
            }
            
            var reader = new Ext.data.JsonReader({}, [
                {name: 'options.layerid'},
                {name: 'name'},
                {name: 'label'},
                {name: 'options.groupname'},
                {name: 'options.rang'},
                {name: 'options.grouporder'},
                {name: 'options.visibility'},
                {name: 'options.exporter'},
                {name: 'options.typegeo'},
                {name: 'options.sldFiles'},
                {name: 'options.opacity'},
                {name: 'options.search'}
             ]);
            opencarto.layerStore = new Ext.data.GroupingStore({
                reader: reader,
                data: opencarto.gisobjects.layers,
                sortInfo:{field: 'options.rang', direction: "ASC"},
                groupField:'options.grouporder'
                
            });
            var visibilityColumn = new Ext.grid.CheckColumn({
                header: "Aff.",
                dataIndex: 'options.visibility',
                menuDisabled:true,
                width: 2,
                hidden:false,
                sortable: false,
                resizable:true
             });

            opencarto.sm = new Ext.grid.RowSelectionModel({ singleSelect:true});
            opencarto.layercm = new Ext.grid.ColumnModel([
                visibilityColumn,
                {id:'id',header: "ID", width: 60, hidden:true, sortable: false, dataIndex: 'options.layerid'},
                
                {id:'name',header: "Nom", width: 60, hidden:true, sortable: false, dataIndex: 'name'},
                {header: "Nom de la couche", width:150, menuDisabled:true,sortable: false, dataIndex: 'label', renderer: Ext.util.Format.capitalize, tooltip:'Liste des couches disponibles'},
                {header: "Groupe", width: 20, hidden:true, sortable: false,  dataIndex: 'options.groupname'},
                {header: "Rang", width: 20, hidden:true, sortable: false, dataIndex: 'options.rang'},
                {header: "Catégorie", width: 20, hidden:true, sortable: false, dataIndex: 'options.grouporder'},
                {header: "Exporter", width: 20, hidden:true, sortable: false, dataIndex: 'options.exporter'},
                {header: "Type", width: 20, hidden:true, sortable: false, dataIndex: 'options.typegeo'},
                {header: "sldFiles", width: 20, hidden:true, sortable: false, dataIndex: 'options.sldFiles'},
                {header: "opacity", width: 20, hidden:true, sortable: false, dataIndex: 'options.opacity'},
                {header: "search", width: 20, hidden:true, sortable: false, dataIndex: 'options.search'}
                ]
                
                );
            opencarto.layerGrid = new Ext.grid.EditorGridPanel({
                
            store: opencarto.layerStore,
            cm: opencarto.layercm,
            sm:opencarto.sm,
            plugins:visibilityColumn,

            view: new Ext.grid.GroupingView({
                forceFit: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["options.groupname"])]}'
            }),
            autoHeight:true,
            autoExpandColumn:'label',
            width:'auto',
            
            frame:false,
            border:true,
            hideGroupedColumn:true,
            collapsible: true,
            title: 'Liste des couches',
            autoExpandColumn:'label',
            animCollapse: true,
            enableColLock: false,
            iconCls: 'layerList',
            loadMask: true,
            listeners: {
                      rowcontextmenu:opencarto.onContextClick
                }
            });
            
            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();
            
           
 
            opencarto.map = opencarto.mapPanel.getMap();
            
            
            opencarto.map.events.register('changelayer', this, function() {
                opencarto.showLegend();
            });
            opencarto.map.events.register('zoomend',this,function(){
                opencarto.showLegend();
            });
            opencarto.loadedLayers = new Array();
            for (i=0;i<opencarto.gisobjects.layers.length;i++){
                myLayer = opencarto.gisobjects.layers[i];
                
                if (opencarto.map.getNumLayers() == 0 && !globalParams.googlelayer)
                    myLayer.options.isBaseLayer = true;
                else
                    myLayer.options.isBaseLayer = false;
                if (myLayer.name == 'Google Layer')
                    opencarto.loadedLayers[i] = new OpenLayers.Layer.Google(myLayer.name,myLayer.params, myLayer.options);
                else
                    opencarto.loadedLayers[i] = new OpenLayers.Layer.WMS(myLayer.name,myLayer.url, myLayer.params, myLayer.options);  

                opencarto.loadedLayers[i].setOpacity(myLayer.options.opacity/100);
                opencarto.layerGrid.getSelectionModel()
                if (myLayer.options.sld != 'null'){
                    opencarto.loadedLayers[i].mergeNewParams({sld: myLayer.options.sld})
                }
                
                opencarto.loadedLayers[i].events.register('loadstart', this, function() {
                    opencarto.layercounter += 1;
                    Ext.getCmp('basic-statusbar').showBusy();
                    });
                opencarto.loadedLayers[i].events.register('loadend', this, function() {
                    opencarto.layercounter -= 1;
                    if (opencarto.layercounter == 0)
                        Ext.getCmp('basic-statusbar').clearStatus({useDefaults:true});
                });
                
                
                opencarto.map.addLayer(opencarto.loadedLayers[i]);
            }
            
            opencarto.layerGrid.doLayout();
            
            // indiquer que la couche vecteur est toujours "in range"
            opencarto.vectorLayer.calculateInRange = function() { return true; };
            opencarto.map.addLayer(opencarto.vectorLayer);
   
            // on ne met pas l'overview avec une couche google, car ça bugge !!!
            if (!globalParams.googlelayer)
            {
                
                opencarto.map.addControl(new OpenLayers.Control.OverviewMap(
                    {mapOptions:
                        {units:"m",
                        maxExtent: globalParams.maxExtent,

                        projection:globalParams.projection},
                        size:new OpenLayers.Size(250, 200),
                        minRatio:32,
                        maxRatio:128,
                        title:'Carte de localisation'
                    }
                ));
            }
            opencarto.vectorLayer.setZIndex(opencarto.map.Z_INDEX_BASE['Popup'] - 1);
            //alert(opencarto.map.maxExtent);
            opencarto.map.zoomToExtent(globalParams.maxExtent);
            
            opencarto.showLegend();
            
		},
		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;
		}   
	});
   

   
    /*opencarto.layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    opencarto.layer_style.fillOpacity = 1;
    opencarto.layer_style.graphicOpacity = 0.6;
    opencarto.layer_style.strokeColor = "#680404";
    opencarto.layer_style.fillColor =  "#dc3838";
    opencarto.layer_style.strokeWidth = 2;*/
    opencarto.vectorLayer = new OpenLayers.Layer.Vector("vector",{
        styleMap: new OpenLayers.StyleMap({
                "default": new OpenLayers.Style({
                    fillOpacity: 0.6,
                    strokeColor: "#706d10",
                    fillColor: "#ece523",
                    strokeWidth: 2,
                    cursor: 'pointer'
                }),
                "select": new OpenLayers.Style({
                    fillOpacity: 0.9,
                    strokeColor: "#00FF00"
                })
            })                                                                                                    
    });
    /*opencarto.selectHandler = new OpenLayers.Control.SelectFeature(opencarto.vectorLayer,{
        multiple:false,
        hover:true,
        selectStyle:'select'
    })
    */
    var zoomToMaxExtentControl = new OpenLayers.Control.ZoomToMaxExtent();
    var zoomBoxControl = new OpenLayers.Control.ZoomBox();
    var navigationControl = new OpenLayers.Control.Navigation();
    var calculateLengthControl = new OpenLayers.Control.DrawFeature(
        opencarto.vectorLayer,
        OpenLayers.Handler.Path,
        {
           featureAdded: calculate_length,
           displayClass: "olControlCalculateLength"
        }
    );
    var calculateAreaControl = new OpenLayers.Control.DrawFeature(
        opencarto.vectorLayer,
        OpenLayers.Handler.Polygon,
        {
           featureAdded: calculate_area,
           displayClass: "olControlCalculateArea"
        }
    );
    var getInfoControl = new OpenLayers.Control.DrawFeature(
        opencarto.vectorLayer,
        OpenLayers.Handler.Point,
        {
           featureAdded: getFeatureInfo,
           displayClass: "getInfoControl"
        }
    );
 
    mapOptions = {
        projection: globalParams.projection,
        units: "m",
        animate:true,
       // resolutions: globalParams.resolutions,
        maxExtent: globalParams.maxExtent,
        controls:[
                    new OpenLayers.Control.ScaleLine({maxWidth:200,title:'Echelle'}),
                    new OpenLayers.Control.MousePosition({'numDigits':1}),
                    new OpenLayers.Control.PanZoomBar(),
                    zoomToMaxExtentControl, zoomBoxControl, navigationControl,
       calculateLengthControl, calculateAreaControl,getInfoControl
                    ]};
        
    if (globalParams.googlelayer)
        mapOptions.resolutions = globalParams.resolutions;
    // Création du panel cartographique
    opencarto.mapPanel = new Ext.ol.OLPanel(mapOptions);

    opencarto.datagrid.dataStore = new Ext.data.JsonStore({
        root: 'records',
        fields: ['information'],
        autoLoad: true,
        data: {
            records:[{
                "information":"Aucune couche n'est sélectionnée."
            }]
        }
    });

    var colModel = new Ext.grid.ColumnModel([{
                id:"info",
                header: "Informations", 
                width: 350,
                sortable: true, 
                dataIndex: 'information'
            }]
    );
    
	
    opencarto.datagrid.grid = new Ext.grid.GridPanel({
        store: opencarto.datagrid.dataStore,
        enableColLock: false,
        loadMask: true,
        id:'dataGrid',
        enableHdMenu:false,
        colModel: colModel,
        viewConfig: {
            forceFit: true
        },
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        frame: false,
        border: false,
        autoExpandColumn: 'information'
	});
	//opencarto.datagrid.grid.render();
 
    opencarto.datagrid.grid.getSelectionModel().on(
        'rowselect',opencarto.datagrid.getGeom
    );
    
   
    opencarto.legendPanel = new Ext.Panel({
                id: 'legendPanel',
                title: 'Légende',
                iconCls: 'legend',
                collapsible:true,
                border:true,
                frame:false,
                autoScroll:true,
                autoHeight:true,
                titleCollapse: true
    });
    
    
    opencarto.positionStore = new Ext.data.JsonStore({
        url: 'positions/',
        root: 'positions',
        fields: [{name:'id'}, {name:'name'}, {name:'x'}, {name:'y'}, {name:'z'}],
        autoLoad:false                
    });
    opencarto.positionForm  =new Ext.form.FormPanel({
        labelWidth:40,
        frame:true,
        items:[
        
            new Ext.form.ComboBox({
            id: "pos",
            fieldLabel:'Aller à',
            displayField: 'name',
            valueField: 'id',
            width: 140, 
            editable: false,
            typeAhead: true,
            mode: 'remote',
            forceSelection: false, 
            triggerAction: 'all',
            emptyText: 'Choisir une position',
            selectOnFocus: true,
            store: opencarto.positionStore,
            listeners:{
                 select:opencarto.ZoomToPosition
            }
            })
        ]
    })
    opencarto.positionPanel = new Ext.Panel({
        id: 'positionPanel',
        title: 'Positions prédéfinies',
        iconCls: 'positions',
        collapsible:true,
        border:true,
        frame:false,
        titleCollapse: true,
        items :[
                opencarto.positionForm
               ]
        });
    if (globalParams.userAdmin)
        opencarto.positionForm.addButton({text: 'Ajouter la position courante', tooltipType:'title', tooltip:"Ajout de la position courante", handler: opencarto.addPosition})
    opencarto.bbar = new Ext.StatusBar({
        defaultText: 'Prêt',
        autoHeight:true,
        id: 'basic-statusbar',
        busyText:'Chargement en cours...',
        items: [{xtype: 'tbtext',text:'Système de coordonnées : ' + globalParams.projectionName}, ' ', ' ']
    });
    
    opencarto.toolbar = new Ext.Toolbar();
    
    var tip = new Ext.ux.SliderTip({
        getText: function(slider){
            return String.format('<b>Opacité : {0}% </b>', slider.getValue());
        }
    });

    opencarto.Mask = new Ext.LoadMask(Ext.getBody(), {msg:"Merci de patienter..."});
    
    opencarto.viewport = new Ext.Viewport({
            layout:'border',
            items:[new Ext.BoxComponent({
               region:'north',
               el : 'north',
               height:'60'

            }),
                {

                    region:'west',
                    id:'west-panel',
                    //title:'OUTILS',
                    split:true,
                    width: 210,
                    minSize: 175,
                    maxSize: 400,
                    animate:true,
                    collapsible: false,
                    collapseMode: 'mini',
                    collapsed:false,
                    border:false,
                    margins:'0 0 0 0',
                    autoScroll:true,
                    items: [opencarto.positionPanel,opencarto.legendPanel],
                    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.mapLibelle,
                        layout: 'fit',
                        collapsible: true,
                        collapsed: false,
                        split: true,
                        
                        minSize: 100,
                        maxSize: 500,
                        items: [opencarto.mapPanel]
                    },{
                        id:'dataLayer',
                        region: 'south',
                        layout: 'fit',
                        title: 'Données',
                        collapsible: true,
                        collapsed: true,
                        split: true,
                        height: 300,
                        minSize: 100,
                        maxSize: 500,
                        listeners: {
                            collapse:opencarto.onGridCollapse
                        },
                        items: [opencarto.datagrid.grid]
                    }]
                }
             ]
        });

   
    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',
                //text: 'Zoom +',
                enableToggle: true,
                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: true,
                pressed: true,
                handler: opencarto.toolbarHandler
            })
    );
    opencarto.toolbar.add(
            new Ext.Toolbar.Button({
                id: 14,
                iconCls: 'mes_line',
                
                tooltip: 'Mesure de linéaires',
                tooltipType:'title',
                //text: 'Mesure linéaire',
                enableToggle: true,
                pressed: false,
                handler: opencarto.toolbarHandler
            })
    );
    opencarto.toolbar.add(
            new Ext.Toolbar.Button({
                id: 15,
                iconCls: 'mes_surf',
                tooltip: 'Mesure de surfaces',
                tooltipType:'title',
                //text: 'Mesure surfacique',
                enableToggle: true,
                pressed: false,
                handler: opencarto.toolbarHandler
            })
    );
    opencarto.toolbar.add(
            new Ext.Toolbar.Button({
                id: 16,
                iconCls: 'info',
                tooltip: 'Informations',
                tooltipType:'title',
                //text: 'Info',
                enableToggle: true,
                pressed: false,
                handler: opencarto.toolbarHandler
            })
    );
    
    
    
    opencarto.selection.toolbar = new Ext.Toolbar.MenuButton({
        id: 99,
        iconCls: 'selectionPanel',
        tooltip: 'Outils de sélection',
        tooltipType:'title',
        //text: 'Sélection',
        enableToggle: true,
        pressed: false,
        disabled:true,
        handler:opencarto.toolbarHandler,
        menu:{
            items:[
                '<b class="menu-title">Outils</b>',
                {
                    id:'circle',
                    text: 'Cercle',
                    group:'tool',
                    checked: opencarto.selection.tool == 'circle' ? true:false,
                    checkHandler: opencarto.selection.onSmCheck
                },
                {
                    id:'rectangle',
                    text: 'Rectangle',
                    group:'tool',
                    checked: opencarto.selection.tool == 'rectangle' ? true:false,
                    checkHandler: opencarto.selection.onSmCheck
                },{
                    id:'polygon',
                    text: 'Polygone',
                    group:'tool',
                    checked: opencarto.selection.tool == 'polygon' ? true:false,
                    checkHandler: opencarto.selection.onSmCheck
                },'-',
                '<b class="menu-title">Mode de sélection</b>',
                {
                    id:'ST_Intersects',
                    text: 'Intersection',
                    group:'mode',
                    checked: true,
                    checkHandler: opencarto.selection.onSmCheck
                },
                {
                    id:'ST_Contains',
                    text: 'Inclusion',
                    group:'mode',
                    checked: false,
                    checkHandler: opencarto.selection.onSmCheck
                }
                /*,'-',
                '<b class="menu-title">Comportement</b>',
                {
                    id:'new',
                    text: 'Remplace',
                    tooltip: 'Remplace une sélection existante par la nouvelle.',
                    tooltipType:'title',
                    group:'behaviour',
                    checked: true,
                    checkHandler: opencarto.selection.onSmCheck
                },
                {
                    id:'add',
                    text: 'Ajoute',
                    tooltip: 'Ajoute la nouvelle sélection aux éléments déjà sélectionnés.',
                    tooltipType:'title',
                    group:'behaviour',
                    checked: false,
                    checkHandler: opencarto.selection.onSmCheck
                }  */
            ]
        }
    });
    opencarto.toolbar.add(opencarto.selection.toolbar);
     
    // récupération des templates d'impression
    Ext.Ajax.request({
      
		url:'../getPrintTemplates',
		success:function(res,opt) {
            eval('opencarto.print.printTpl = ' + res.responseText);
            printItems = new Array();
            
            for (i=0;i<opencarto.print.printTpl.length;i++)
            {
                var MyTpl = opencarto.print.printTpl[i];
                var myItem = new Ext.menu.CheckItem({
                    id:'printTpl'+MyTpl.id,
                    text: MyTpl.name,
                    group:'impression',
                    checked: i==0?true:false,
                    checkHandler: opencarto.print.onSmCheck
                });
                printItems.push(myItem);
            }
            if (printItems.length>0){
                opencarto.print.toolbar = new Ext.Toolbar.MenuButton({
                    id: 98,
                    iconCls: 'print',
                    tooltip: 'Impression',
                    tooltipType:'title',
                    //text: 'Imprimer',
                    enableToggle: false,
                    pressed: false,
                    disabled:false,
                    handler:opencarto.toolbarHandler,
                    menu:{
                        items:printItems
                    }
                });
                opencarto.print.selectedTemplate = opencarto.print.printTpl[0];
                
                opencarto.toolbar.add(opencarto.print.toolbar);
            }
        },
        failure: function(res,opt){
            Ext.Msg.show({
                title: "ERREUR",
                msg: "La données n'a pas pu être téléchargée",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
		   	return;
		}
    });
        
    
    // récupération des requêtes prédéfinies
    
    Ext.Ajax.request({
      
	url:'getQueries',
	success:function(res,opt) {
        eval('myQueries = ' + res.responseText);
        queryItems = new Array();
        queryItems.push('<b class="menu-title">Requêtes prédéfinies</b>');
        for (i=0;i<myQueries.length;i++)
        {
           
            var myItem = new Ext.menu.Item({
                id:'query'+myQueries[i].id,
                text: myQueries[i].name,
                group:'requetes',
                queryID:myQueries[i].id,
                labels:myQueries[i].labels,
                fieldtypes:myQueries[i].fieldtypes?myQueries[i].fieldtypes:'',
                target_id:myQueries[i].target,
                handler: opencarto.search.onItemClick
            });
            queryItems.push(myItem);
        }
        if (myQueries.length>0){
            opencarto.search.toolbar = new Ext.Toolbar.MenuButton({
                id: 95,
                iconCls: 'search',
                tooltip: 'Requêtes prédéfinies',
                tooltipType:'title',
                
                //text: 'Imprimer',
                enableToggle: false,
                pressed: false,
                disabled:false,
                handler:opencarto.toolbarHandler,
                menu:{
                    items:queryItems
                }
            });
            
            
            opencarto.toolbar.add(opencarto.search.toolbar);
        }
        },
        failure: function(res,opt){
            Ext.Msg.show({
                title: "ERREUR",
                msg: "La données n'a pas pu être téléchargée",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
		   	return;
		}
    });
   

    opencarto.toolbar.add(
            new Ext.Toolbar.Button({
                id: 17,
                iconCls: 'deleteSelected',
                tooltip: 'Effacer les sélections',
                tooltipType:'title',
                //text: 'Effacer',
                enableToggle: false,
                pressed: false,
                handler: opencarto.toolbarHandler
            })
    );
    
  
    //opencarto.toolbar.render('toolbar');
    //opencarto.bbar.render('bbar');
    opencarto.bbar.showBusy();
    // hack pour bon redimensionnement du MapPanel au lancement...
    
    if (window.outerWidth)
        window.outerWidth = window.outerWidth - 1;
    else if (document.documentElement.clientWidth)
        window.resizeTo(document.documentElement.clientWidth-1,document.documentElement.clientHeight + 160);
  
    
}

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('name'),record.data[this.dataIndex]);
        }
    },

    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>';
    }
};




