//
ccip.fdgp.CommuneGrid = Ext.extend(Ext.grid.GridPanel, {

  initComponent:function() {
    
    var NomCommune = new Ext.data.Record.create([
      {name: 'commune', type: 'string'}
    ]); // 
    
    var reader = new Ext.data.ArrayReader({}, NomCommune);

    // doesn't really like that but 'grid' is private
    // to avoid introducing the parameter to the store ...
	var grid = this;
	
	/*
	var boutons = new Ext.Button ([
		{
			iconCls:'x-custom-icon-imprimer',
			scope:  this,
			handler: this.print			
		},{

			iconCls:'x-custom-icon-fleche',
			scope:   this
		},{

			iconCls:'x-custom-icon-valider',
			scope:   this,
			handler: this.validate
		}
		]);
	*/
	
    var store = new Ext.data.Store({
        proxy: new Ext.ux.data.DWRProxy({
            dwrFunction: Commune.getNomCommunes,
            // retrieve the departements and pass that to the getNomCommunes fct
            listeners: {
                'beforeload': function(dataProxy, params){                
                     // pass the departement id to the request ...
                     params[dataProxy.loadArgsKey] = [Ext.get(grid.params.departementId || 'departement-id').getValue()];
                },
                'show': function() {
                       this.loadMask = new Ext.LoadMask(this.body, {msg:'Chargement communes'})
                 }
            } // eo listeners (DWRProxy)
        }), // eo ctor DWRProxy
        reader: reader/*,
        
        listeners: { // need to redefine onload for pre-selection for the store
            'load': function(store, records) {

              // retrieve existing communes
              var commune = Ext.getDom(grid.params.communeId || 'commune-id').value;
              if (commune !== '') { // empty string is falsy in js
                // split into part
                var communes = commune.split();                    
                var i=0;
                var j=0;
                // for each commune retrieve the value (index) in the grid
                var selected= [];
                // protection againsts too smart users ...
                for (i=0; i < communes.length && i < FDGP.global.MAX_COMMUNE; i++) {
                  // retrieve the entry in the grid if exist ...
                  for (j=0; j < records.length; j++) {
                    //debug console.log(communes[i] + "==" + records[j].data.commune);
                    if (communes[i] == records[j].get('commune')) { // match?
                      // set the column
                      selected.push(j);
                      break; // not necessary to continue on the records
                    }
                  }
                }
                if (selected.length > 0) {
                  grid.getSelectionModel().selectRows(selected);
                  //grid.getView().focusRow(j);
                }
              }
            } // eo load
        } // eo listeners (Store)*/
    }); //eo ctor Store
    
    var sm = new Ext.grid.CheckboxSelectionModel();
    
    var cm = new Ext.grid.ColumnModel([
       
        {id:'commune',header: "Sélectionnez une ou plusieurs villes.", width: 440, sortable: true, dataIndex: 'commune', menuDisabled: true},
		 sm //350
        //sm
        /*{id:'libelle',header: "Libelle", width: 40, sortable: true, dataIndex: 'libelle'},
        {id:'budi',header: "Budi", width: 10, sortable: true, dataIndex: 'budi'},
        {id:'codePostal',header: "CodePostal", width: 10, sortable: true, dataIndex: 'codePostal'}*/
     ]); //eo ctor ColumnModel

   /*
   var lm = new Ext.LoadMask(Ext.getBody() ,{
    msg : "Chargement des communes..."
   });
     */                       
    Ext.apply(this, {
      id: 'communegrid-id',
      cls: 'x-custom-grid',
      store:  store,
	  height: 800,
	  width:  450,
	  cm:     cm,
	  frame:  true,
	  stripeRows: true,
	  autoSizeColumns: true,
	  
	  //modal:  true,
	  // tried several things but doesn't work, test with FF 
	  //loadMask: lm,
	  loadMask: {msg: 'Chargement des communes...'},
      //title:  'Liste des communes',
            	
		tbar:[{
				xtype:'button',
				scope:  this,
				handler: this.print,
				iconCls:'x-custom-icon-imprimer'
				//listeners :{'mouseover': function (t, e){alert('Over');}}
				//onMouseover:function(event, target) {alert('Over');} 
				//overCls:'x-custom-icon-imprimer-over'
			},
			{xtype: 'tbfill'},
			{
				xtype:'button',								
				iconCls:'x-custom-icon-fleche',
				disabled:true
			},
			{
				xtype:'button',
				iconCls:'x-custom-icon-valider',
				//disabled:true,		
				scope:   this,
				handler: this.validate
		}],
		
		bbar:[{
				scope:  this,
				handler: this.print,
				iconCls:'x-custom-icon-imprimer'				
			},
			{xtype: 'tbfill'},
			{
				xtype:'button',
				iconCls:'x-custom-icon-fleche',
				disabled:true,
				scope:   this
			},{
				xtype:'button',
				iconCls:'x-custom-icon-valider',
				scope:   this,
				handler: this.validate
		}],
			
			
      // doesn't work, how to retrieve the grid ... the get('') doesn't work
	  /*
		buttons:[{
                 //text:    'Valider',
				 //icon: 'image/fr/valider.gif',
				 //ctCls:'x-custom-icon-size',
				 iconCls:'x-custom-icon-valider',
                 scope:   this,
                 handler: this.validate
				 				 
                 //icon: 'image/fondOnglet.gif'
                 //style: 'color:orange;background:orange;'
                 
                },
                {
                  //text:    'Annuler',
				  //icon: 'image/fr/annuler.gif',
				  iconCls:'x-custom-icon-annuler',
                  scope:   this,
                  handler: this.cancel
                },
                {
                  //text:  'Imprimer',
                  scope:  this,
                  handler: this.print,
				  //icon: 'image/gimp.gif',
				  iconCls:'x-custom-icon-imprimer'
				}
              ],*/

      buttonAlign:'center',
      sm: sm
      //viewConfig:{forceFit:true}
     }); // eo apply
  
  // call parent
     ccip.fdgp.CommuneGrid.superclass.initComponent.apply(this, arguments);
   }, // eo function initComponent
     
   load:function() {
    this.store.load();
  }, //eo function load
   

   /*
  onClick:function(event, target) {  
    if (this.getSelectionModel().getCount() > FDGP.global.MAX_COMMUNE) {
	  Ext.ux.form.XMessageAlert('Nombre maximal de communes atteint');
	  // Retrieve the row	 
	  var row = event.getTarget('.x-grid3-row'); // well 	  
	  // debug console.log("retrieve row " + row.rowIndex);
	  // revert the selection ...	 
      if (this.getSelectionModel().isSelected(row.rowIndex)) {
        this.getSelectionModel().deselectRow(row.rowIndex);
      }
	}
  }, // eo function onClick
*/

  onRender:function() {
        //this.store.load();
        ccip.fdgp.CommuneGrid.superclass.onRender.apply(this, arguments);
        // try here
    }, // eo function onRender
    
  // ok french is because french was requested ...
    validate:function() {
    	// Retrieve the existing selection(s)
    	//var communes = Ext.get(this.params.communeId || 'commune-id').getValue();
    	// no since the pre-selection applies now to avoid duplicate and/or extra computing
    	if (this.getSelectionModel().getCount() > FDGP.global.MAX_COMMUNE) {
			Ext.ux.form.XMessageAlert('Vous ne pouvez pas sélectionner plus de ' + FDGP.global.MAX_COMMUNE + ' communes');
    	}
    	else {
    		var communes=Ext.getDom(this.params.communeId || 'commune-id').value;
    		// Retrieve the selection from the Grid checkbox
    		var selections = this.getSelections();
    		if(communes != ""){

    			communes = communes.replace(/\r\n/g,';');
    			communes = communes.replace(/\n/g,';');
    			
    			communes=communes.toUpperCase();

    			var tabcommunes = communes.split(/\s*;\s*/); 

    			var codetrouve = false;
    			for (var i=0, n = selections.length; i < n; i++) {
    				for (j=0; j < tabcommunes.length ; j++) {
    					if(selections[i].get("commune") == tabcommunes[j]){
    						codetrouve = true;
    						break;
    					}
    				}
    				if(!codetrouve){
    					if (communes) {
    						communes += ";";
    					}
    					communes += selections[i].get("commune");
    				}
    				codetrouve = false;
    			}  
    		}
    		else{
    			for (var i=0, n = selections.length; i < n; i++) {
    				if(i<n-1){ 
    					communes += selections[i].get("commune") + ";";
    				}
    				else{
    					communes += selections[i].get("commune");
    				}
    			}  
    		}

    		// was Ext.getDom('commune-id').value = communes;
    		Ext.getDom(this.params.communeId || 'commune-id').value = communes;
    		wrapText(Ext.getDom(this.params.communeId || 'commune-id'));

    		//Ext.get('communewin-id').hide();
    		Ext.getCmp('communewin-id').destroy();
    	}
    }, // eo function validate
  
  // PB: restore focus on the caller ... parent???
  cancel:function() {
	Ext.getCmp('communewin-id').destroy();
    //Ext.get('communewin-id').hide();
  }, // eo function cancel
  
  print:function() {
    this.el.print({grid: this, title: 'Liste des communes'});
  }
  
}); // eo extend grid

 
Ext.reg('communegrid', ccip.fdgp.CommuneGrid);
