Ext.namespace('opencarto.datagrid');
opencarto.datagrid.layer_id = null;
opencarto.datagrid.dataStore = new Ext.data.JsonStore({
        root: 'records',
        fields: ['information'],
        autoLoad: true,
        data: {
            records:[{ "information" : oMessages.no_layer_sel }]
        }
    });
 var colModel = new Ext.grid.ColumnModel([{
                id:"info",
                header: oMessages.message_info, 
                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.datagrid.panel = new Ext.Panel({
                        id:'dataLayer',
                        region: 'south',
                        layout: 'fit',
                        title: oMessages.data_txt,
                        collapsible: true,
                        collapsed: true,
                        split: true,
                        height: 300,
                        minSize: 100,
                        maxSize: 500,
                        listeners: {
                            collapse:opencarto.onGridCollapse
                        },
                        items: [opencarto.datagrid.grid]
                    });




opencarto.datagrid.prepareGeom = function()
{
   if (opencarto.tm) {
      clearTimeout(opencarto.tm);
    }
   opencarto.vectorLayer.destroyFeatures(opencarto.vectorLayer.features);
   opencarto.tm = setTimeout("opencarto.datagrid.getGeom()", 50);
}
opencarto.datagrid.getGeom = function(){
  //opencarto.selectHandler.activate();
      
      if(opencarto.datagrid.grid.getSelectionModel().hasSelection())
      {
         rows = opencarto.datagrid.grid.getSelectionModel().getSelections();
         aID = new Array();
         for (i=0;i<rows.length;i++)
         {
            aID.push(rows[i].get('id'));
         }
         try{
            
            layer_id = opencarto.datagrid.layer_id;
            
         }
         catch(e){
            if (opencarto.search.target_id)
               layer_id = opencarto.search.target_id;
            else
               return;
            
         }
         Ext.Ajax.request({
            url:'../layer/'+layer_id+'/geom/?ids=' + aID.join(',')+'&res=' + parseInt(opencarto.map.getResolution()) + '&proj=' + globalParams.projection.replace('epsg:',''),
            success:function(res,opt) {
               eval('opencarto.vectorfeatures = ' + res.responseText);
               var format = new OpenLayers.Format.WKT();
               var error = 0
               for (i=0;i<opencarto.vectorfeatures.records.length;i++){
                  theFeature = opencarto.vectorfeatures.records[i];
                  try{
                     var feature = format.read(theFeature.geom);
                     if (feature){
                    	feature.attributes = { rowid : theFeature.id };
                        opencarto.vectorLayer.addFeatures([feature]);
                     }
                  }
                  catch(e){
                     error = 1
                  }
               }
               if (error == 1){
                  Ext.Msg.show({
                   title: oMessages.error_title,
                   msg: oMessages.object_aff,
                   buttons: Ext.Msg.OK,
                   icon: Ext.MessageBox.ERROR
                  });
               }
            },
            failure: function(res,opt){
               Ext.Msg.show({
                   title: oMessages.error_title,
                   msg: oMessages.objetc_imp,
                   buttons: Ext.Msg.OK,
                   icon: Ext.MessageBox.ERROR
               });
               return;
           }
         });
      }
}


opencarto.datagrid.displayData = function(layerID, fieldName, fieldValue, fieldType){
   // récupération du layer_id appelé et mise en variable globale.
   // ceci évite d'avoir des erreurs quand on change de couche sans vider le tableau
   opencarto.datagrid.layer_id = layerID;
 
   // -------------------------------------------------------------------
   
   
   opencarto.Mask.show();
   // un peu de ménage...
   opencarto.datagrid.grid.getSelectionModel().clearSelections();
   opencarto.vectorLayer.destroyFeatures(opencarto.vectorLayer.features);
   if (opencarto.vector) {
                opencarto.vector.destroy();
                opencarto.vector = null;
   }
   // -----------------------------------------------------------------------
   
   // Récupération des champs de la table et de leur type
   Ext.Ajax.request({
      url:'../layer/'+layerID+'/data_structure/',
      success:function(res,opt) {
      eval('opencarto.layerdata = ' + res.responseText);
      if (opencarto.layerdata == '0')
      	return;
      var  dsfields = [];
      for (i=0;i<opencarto.layerdata.fields.length;i++)
      {
         f = opencarto.layerdata.fields[i];
         dsfields[i] = f.name;
      }
      if (opencarto.selection && opencarto.selection.wkt && opencarto.selection.mode){
      	 if (opencarto.selection.mode == 'ST_Distance')
            opencarto.selection.mode = 'ST_Intersects'
         bp = {'selectionWKT':opencarto.selection.wkt,'proj':globalParams.projection.replace('epsg:',''),'mode':opencarto.selection.mode};
      }
      else if (fieldName && fieldValue)
         bp= {'filter[0][field]':fieldName,'filter[0][data][value]':fieldValue,'filter[0][data][type]':fieldType,'filter[0][data][comparison]':'='};
      else if (opencarto.search && opencarto.search.geom != '' && opencarto.selection.mode){
         if (opencarto.search.queryID)
            bp={'queryID':opencarto.search.queryID,'selectionWKT':opencarto.search.geom,'proj':globalParams.projection.replace('epsg:',''),'mode':opencarto.selection.mode,'origin':'search'};
         else
            bp={'selectionWKT':opencarto.search.geom,'proj':globalParams.projection.replace('epsg:',''),'mode':opencarto.selection.mode,'origin':'search'};
      }
      else if (opencarto.search && opencarto.search.queryID)
         bp={'queryID':opencarto.search.queryID,'proj':globalParams.projection.replace('epsg:',''),'origin':'search'}
      else
         bp = {};
      if (bp.mode && opencarto.selection && opencarto.selection.mode == 'ST_Distance'){
         bp.distance = opencarto.search.distance;
      }
      if (opencarto.search && opencarto.search.attributeValues)
      {
         toks = opencarto.search.attributeValues.split('&');
         for (i=0;i<toks.length;i++)
         {
            fieldData = toks[i].split('=');
            if (fieldData[0].indexOf('attField')>-1)
            {
               eval("bp."+fieldData[0]+"=fieldData[1]");
            }
         }
         
      }
      if (opencarto.search)
      	opencarto.search.attributeValues = null;
      var ds = new Ext.data.JsonStore({
         url:url = '../layer/'+layerID+'/data/',
         layerId: layerID,
         baseParams:bp,
         storeId: 'id',
         totalProperty: 'total',
         root: 'data',
         fields: dsfields,
         sortInfo: {field: dsfields[1].name, direction: 'ASC'},
         remoteSort: true
       });
      if (opencarto.selection){
      	ds.addListener('load',opencarto.selection.selectAll);
      }
      // reconfiguration du cm
      var cmfields = [];
      var dataFilters = [];
      colWidth = parseInt(600 / opencarto.layerdata.fields.length-1);
      for (i=0;i<opencarto.layerdata.fields.length;i++)
      {
         f = opencarto.layerdata.fields[i];
         if (f.fieldtype == 'url')
         {
		//alert(f.verbose_name);
            cmfields[i] = {name:f.name,header:f.verbose_name,width:i>0?colWidth:15, sortable:true,dataIndex:f.name,renderer: renderURL};
            f.fieldtype = 'string'
         }
         else
         {
            cmfields[i] = {name:f.name,header:f.verbose_name,width:i>0?colWidth:15, sortable:true,dataIndex:f.name};
         }
         dataFilters[i] = {type:f.fieldtype,dataIndex:f.name};
      }
      var colModel = new Ext.grid.ColumnModel(cmfields);
      
      var filters = new Ext.grid.GridFilters({
            filters:dataFilters});
      if (opencarto.selection && opencarto.selection.wkt )
         myPageSize = 250;
      else if (opencarto.search && (opencarto.search.queryID || opencarto.search.geom != ''))
      	myPageSize = 250;
      else
         myPageSize = 10;
      var pt = new Ext.PagingToolbar({
           store:ds,
           pageSize: myPageSize,
           plugins: filters,
           items:[
               {id:'zoom',text: oMessages.zoom_obj, handler: opencarto.zoomVector},
               {id:'center',text: oMessages.center_obj, handler: opencarto.centerVector}
               ]
         })

      grid = new Ext.grid.GridPanel({
         id:'dataGrid',
         store: ds,
         cm: colModel,
         border:false,
         enableColLock: false,
         loadMask: true,
         plugins: filters,
         stripeRows:true,
         
         viewConfig: {
            forceFit: true
         },
         bbar: pt,
         sm: new Ext.grid.RowSelectionModel({singleSelect:false}),
         autoExpandColumn: dsfields[1].name
      });
      
      //Editeur de lignes ( clic droit = editer ) si on a des champs editables
      if( opencarto.dataEditor && opencarto.layerGrid.getSelectionModel().getSelected().get('options.editable') && opencarto.layerGrid.getSelectionModel().getSelected().get('options.editable') != false ){
      	grid.addListener('rowcontextmenu',opencarto.dataEditor.onContextEdit);
      }
      
      opencarto.datagrid.grid.destroy();
      opencarto.datagrid.grid = grid;
      opencarto.datagrid.grid.getSelectionModel().on(
         'rowselect',
         opencarto.datagrid.prepareGeom
     );
      
      
      target = Ext.getCmp('dataLayer');
      target.add(opencarto.datagrid.grid);
      
      ds.load({params:{start: 0, limit: myPageSize, sort:dsfields[1].name}});
      target.doLayout();
      opencarto.datagrid.panel.expand();
      opencarto.Mask.hide();
      if (opencarto.selection){     	
      	pt.addButton({id:'deselect',text: oMessages.unselect_all, handler: opencarto.selection.unSelectAll});
      }
  },
   failure: function(res,opt){
                  Ext.Msg.show({
          title: oMessages.error_title,
          msg: oMessages.no_layer,
          buttons: Ext.Msg.OK,
          icon: Ext.MessageBox.ERROR
      });
                  return;
          }   
  });
   
   
}
    

