Ext.ns('ES');

ES.PhysicDatasGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'PhysicDatasGrid'
  ,autoload:true
  ,enableHdMenu:false
  ,datastpl:new Ext.XTemplate('<table cellspacing="0" cellpadding="0" class="physicdatasgrid"><tr>'
            +'<td class="title" colspan="2">Surface [m2] : </td>'
            +'<td class="title" colspan="2">Autre : </td>'
            +'</tr><tr>'
            +'<td class="data-first">Surface du toit :</td>'
            +'<td class="data2">{roofarea}</td>'
            +'<td class="data">Nombre d\'étages :</td>'
            +'<td class="data2">{floornumber}</td>'
            +'</tr><tr>'
            +'<td class="data-first">Surface des façades :</td>'
            +'<td class="data2">{wallarea}</td>'
            +'<td class="data">Hauteur du plafond :</td>'
            +'<td class="data2">{ceilingheight} m</td>'
            +'</tr><tr>'
            +'<td class="data-first">Surface au sol :</td>'
            +'<td class="data2">{floorarea}</td>'
            +'<td class="data">Nombre de pièces :</td>'
            +'<td class="data2">{roomnumber}</td>'
            +'</tr><tr>'
            +'<td class="data-first">Surface chauffée :</td>'
            +'<td class="data2">{heatedarea}</td>'
            +'<td class="data">&nbsp;</td>'
            +'<td class="data2">&nbsp;</td>'
            +'</tr><tr>'
            +'<td class="data-first">Surface des fenêtres :</td>'
            +'<td class="data2">{windowarea}</td>'
            +'<td class="data">&nbsp;</td>'
            +'<td class="data2">&nbsp;</td>'
            +'</tr></table><br><br>'
                    )
  //clicksToEdit:1,
  ,initComponent:function() {
    this.action = new Ext.ux.grid.RowActions({
      header:'Modifier'
      ,width: 50
      ,scope:this
      ,autoWidth:false
      ,hideMode:'display'
      ,keepSelection:true
      ,actions:[{
         iconCls:'icon-edit'
        ,tooltip:'Modifier'
      }]
      ,callbacks:{
        'icon-edit':function(grid, record, action, row, col) {
          this.initEditPhysicDatasFormWindow2(grid, record, action, row, col);
        }.createDelegate(this)
      }
    });
    var CheckColumn = new Ext.grid.CheckColumn({
      header: "&nbsp;",
      dataIndex: 'checkbox',
      hideable:false,
      width: 27
    });
    var config = {
      plugins:[CheckColumn,this.action],
      tbar: new Ext.Toolbar({
        items:[new Ext.Toolbar.Button({
          text: 'Insertion des données physiques'
          ,iconCls:'add'
        }),
          new Ext.Toolbar.Button({
            text: 'Suppression',
            iconCls:'remove'
        })]}),
      store: new Ext.data.Store({
        id:"PhysicDatasCounterPanelStore"
        ,ownerCt:this
        ,physicDatas:Ext.data.Record.create([
          { name : 'roofarea'}
          ,{ name : 'wallarea'}
          ,{ name : 'floorarea'}
          ,{ name : 'heatedarea'}
          ,{ name : 'windowarea'}
          ,{ name : 'floornumber'}
          ,{ name : 'ceilingheight'}
          ,{ name : 'roomnumber'}
          ,{ name : 'flatnumber'}
        ]),
        proxy: new Ext.data.HttpProxy({
          url:'/process/extjs/site/profil/physicdatas/physicdatas.php',
          method: 'POST'
        }),
        reader: new Ext.data.JsonReader({
          root: 'results',
          totalProperty: 'totalCount',
          id: 'id'
        },[
          {name: 'entry_id', type: 'int', mapping: 'entry_id'},
          {name: 'datas', type: this.physicDatas, mapping: 'datas'},
          {name: 'startdate', type: 'string', mapping: 'startdate'},
          {name: 'totalCount', type: 'int'}

        ])
    //    ,sortInfo:{field: 'countername', direction: "ASC"}
      }),
      cm: new Ext.grid.ColumnModel([
        {
          header: 'entry_id',
          dataIndex:'entry_id'
          ,hidden:true
          ,hideable:false
        },
        CheckColumn,
        {
          header: 'Depuis',
          width: 75,
          dataIndex:'startdate'
        },{
          ownerCt:this,
          header: 'Données',
          dataIndex: 'datas',
          width: 525,
          renderer: function(json,v2,results) {return results.store.ownerCt.datastpl.applyTemplate(json);}
        },
        this.action
      ])
    };
     // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent initComponent
    ES.PhysicDatasGrid.superclass.initComponent.call(this);
    this.topToolbar.items.itemAt(0).on('click',this.initAddPhysicDatasFormWindow,this);
    this.topToolbar.items.itemAt(1).on('click',this.deleteEntries,this);
    this.on('rowdblclick',this.initEditPhysicDatasFormWindow1,this);
  } // end of function initComponent
  ,onRender:function() {
    ES.PhysicDatasGrid.superclass.onRender.apply(this, arguments);
    this.refresh();
  } // eo function onRender
  ,refresh:function() {
    this.store.load({
         url:this.url
        ,waitMsg:'Loading...'
        ,params:{cmd:'list'}
    });
  }
  ,initAddPhysicDatasFormWindow:function (grid, record, action, row, col){
    if(this.physicDatasFormWindow == null || !this.physicDatasFormWindow.isVisible()){
      this.physicDatasFormWindow = new ES.physicDatasFormWindow();
      this.physicDatasForm = this.physicDatasFormWindow.items.itemAt(0);
      this.physicDatasFormAreaHelp = this.physicDatasFormWindow.items.itemAt(1);
      this.physicDatasFormButton = this.physicDatasForm.buttons[0];
      var scope_physicdatas = this;
      this.physicDatasFormButton.on({
         scope:scope_physicdatas,
         click:function(scope){
           this.addPhysicDatas();
         }
      });
      this.physicDatasForm.setField('startdate',this.store.reader.jsonData.addStartDate);

      this.physicDatasFormWindow.show();
    } else {
      this.physicDatasFormWindow.toFront();
    }
    this.physicDatasForm.getIconHelp('roofareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['roofarea']));
    this.physicDatasForm.getIconHelp('wallareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['wallarea']));
    this.physicDatasForm.getIconHelp('floorareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['floorarea']));
    this.physicDatasForm.getIconHelp('heatedareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['heatedarea']));
    this.physicDatasForm.getIconHelp('windowareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['windowarea']));
  }
  ,addPhysicDatas: function() {
    if(this.physicDatasForm.isPhysicDatasFormValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/profil/physicdatas/physicdatas.php',
        params: {
          cmd:"add",
          //counter_id:this.counter_id,
          startdate: this.physicDatasForm.getField('startdate').getValue().format("Ymd"),
          roofarea: this.physicDatasForm.getField('roofarea').getValue(),
          wallarea: this.physicDatasForm.getField('wallarea').getValue(),
          floorarea: this.physicDatasForm.getField('floorarea').getValue(),
          heatedarea: this.physicDatasForm.getField('heatedarea').getValue(),
          windowarea: this.physicDatasForm.getField('windowarea').getValue(),
          floornumber: this.physicDatasForm.getField('floornumber').getValue(),
          ceilingheight: this.physicDatasForm.getField('ceilingheight').getValue(),
          roomnumber: this.physicDatasForm.getField('roomnumber').getValue()
          //flatnumber: this.physicDatasForm.getField('flatnumber').getValue()
        },
        success: function(response,scope){
          var result = Ext.util.JSON.decode(response.responseText);
          switch(result.success){
          case 1:
//            Ext.MessageBox.alert(
//              'Saisie des données physiques du bâtiement'
//              ,'Les données physiques ont été insérées.'
//              ,function(){
                scope.ownerCt.refresh(scope.ownerCt.counter_id);
                scope.ownerCt.physicDatasFormWindow.close();
//              }
//            ,scope);
            break;
          default:
            Ext.MessageBox.alert('Attention',result.error);
            break;
          }
        },
        failure: function(response) {
          Ext.MessageBox.alert('error','L application n a pas pu se connecter a la base de données. Veuillez réessayer plus tard');
        }
      });
    } else {
      Ext.MessageBox.alert('Attention','Le formulaire n est pas valide');
    }
  }
  ,initEditPhysicDatasFormWindow1:function (grid,rowIndex,e){
    this.initEditPhysicDatasFormWindow(grid,rowIndex);
  }
  ,initEditPhysicDatasFormWindow2:function (grid, record, action, rowIndex, col){
    this.initEditPhysicDatasFormWindow(grid,rowIndex);
  }
  ,initEditPhysicDatasFormWindow:function (grid, rowIndex){
    cm = grid.colModel;
    readindex = cm.findColumnIndex('entry_id');
    var record = grid.getStore().getAt(rowIndex);
    this.entry_id = record.get('entry_id');
    if(this.physicDatasFormWindow == null || !this.physicDatasFormWindow.isVisible()){
      this.physicDatasFormWindow = new ES.physicDatasFormWindow();
      this.physicDatasFormWindow.title = "Modification des données physiques";
      this.physicDatasForm = this.physicDatasFormWindow.items.itemAt(0);
      this.physicDatasFormAreaHelp = this.physicDatasFormWindow.items.itemAt(1);
      this.physicDatasFormButton = this.physicDatasForm.buttons[0];
      var scope_physicdatas = this;
      this.physicDatasFormButton.on({
         scope:scope_physicdatas,
         click:function(scope){
           this.editPhysicDatas();
         }
      });
      this.physicDatasFormWindow.show();
    } else {
      this.physicDatasFormWindow.toFront();
    }
    this.physicDatasForm.getIconHelp('roofareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['roofarea']));
    this.physicDatasForm.getIconHelp('wallareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['wallarea']));
    this.physicDatasForm.getIconHelp('floorareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['floorarea']));
    this.physicDatasForm.getIconHelp('heatedareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['heatedarea']));
    this.physicDatasForm.getIconHelp('windowareaicon').getEl().on('click',this.physicDatasFormAreaHelp.showHelpImage.createDelegate(this.physicDatasFormAreaHelp,['windowarea']));
    this.physicDatasForm.setField('startdate',record.get('startdate'));
    this.physicDatasForm.setField('roofarea',record.get('datas').roofarea);
    this.physicDatasForm.setField('wallarea',record.get('datas').wallarea);
    this.physicDatasForm.setField('floorarea',record.get('datas').floorarea);
    this.physicDatasForm.setField('heatedarea',record.get('datas').heatedarea);
    this.physicDatasForm.setField('windowarea',record.get('datas').windowarea);
    this.physicDatasForm.setField('floornumber',record.get('datas').floornumber);
    this.physicDatasForm.setField('ceilingheight',record.get('datas').ceilingheight);
    this.physicDatasForm.setField('roomnumber',record.get('datas').roomnumber);
  }
  ,editPhysicDatas: function() {
    if(this.physicDatasForm.isPhysicDatasFormValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url:'/process/extjs/site/profil/physicdatas/physicdatas.php',
        params: {
          cmd:"update",
          entry_id:this.entry_id,
          startdate: this.physicDatasForm.getField('startdate').getValue().format("Ymd"),
          roofarea: this.physicDatasForm.getField('roofarea').getValue(),
          wallarea: this.physicDatasForm.getField('wallarea').getValue(),
          floorarea: this.physicDatasForm.getField('floorarea').getValue(),
          heatedarea: this.physicDatasForm.getField('heatedarea').getValue(),
          windowarea: this.physicDatasForm.getField('windowarea').getValue(),
          floornumber: this.physicDatasForm.getField('floornumber').getValue(),
          ceilingheight: this.physicDatasForm.getField('ceilingheight').getValue(),
          roomnumber: this.physicDatasForm.getField('roomnumber').getValue()
        },
        success: function(response,scope){
          var result = Ext.util.JSON.decode(response.responseText);
          switch(result.success){
          case 1:
            Ext.MessageBox.alert(
              'Modification des données physiques'
              ,'Les données physiques ont été modifiées.'
              ,function(){
                scope.ownerCt.refresh(scope.ownerCt.counter_id);
                scope.ownerCt.physicDatasFormWindow.close();
              }
            ,scope);
            break;
          default:
            Ext.MessageBox.alert('Attention',result.error);
            break;
          }
        },
        failure: function(response) {
          Ext.MessageBox.alert('error','L application n a pas pu se connecter a la base de données. Veuillez réessayer plus tard');
        }
      });
    } else {
      Ext.MessageBox.alert('Attention','Le formulaire n est pas valide');
    }
  }
  ,deleteEntries: function() {
    if(this.countCheck() > 0) {
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/profil/physicdatas/physicdatas.php',
        params: {
          entry_ids:Ext.util.JSON.encode(this.getCheckBoxValues())
          ,cmd:'delete'
        },
        success: function(response,scope){
          scope.ownerCt.refresh(scope.ownerCt.counter_id);
        },
        failure: function() {
        }
      });
    } else {
      Ext.MessageBox.show({
        title: 'Aucun élément sélectionné',
        msg: 'Pour supprimer, veuillez sélectionner les éléments à supprimer avec les checkbox',
        width: 300
      });
    }
  }
  ,getCheckBoxValues:function() {
    var physicdatas = [];
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){
        physicdatas.push(this.getStore().getAt(i).get('entry_id'));
      }
    }
    return physicdatas;
  }
  ,demoModality: function() {
    var cm= this.colModel;
    cm.setHidden(4, true);
    cm.setHidden(1, true);
    this.un('rowdblclick',this.initEditPhysicDatasFormWindow1,this);
    this.topToolbar.items.itemAt(0).disable();
    this.topToolbar.items.itemAt(1).disable();
  }
  ,countCheck:function() {
    var check = 0;
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){
        check++;
      }
    }
    return check;
  }
});

Ext.reg('ESphysicdatasgrid', ES.PhysicDatasGrid);

