/*jslint devel: true, undef: true, plusplus: true, bitwise: true, regexp: true, immed: true */
/*global Ext: false*/

/*!
 * Ext JS Library 3.0.3
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 * to make spaces use &nbsp;
 */
Ext.onReady(function () {
    Ext.QuickTips.init();

  var sm = new Ext.grid.CheckboxSelectionModel();

  // //////////////////////////////////////////////////////////////////////////
  // 
  //  Funzioni varie
  //
  // //////////////////////////////////////////////////////////////////////////
  function confrontaInit(rec){
  // funzione che crea l'array di accordi e chiama la pagina dei confronti
    var record = new Array();
    if (5 < rec.length){
      Ext.Msg.show({
         title:'Troppi accordi selezioanti',
         msg: 'Puoi confrontare fino a 5 accordi fra loro.',
         buttons: Ext.Msg.OK,
         //fn: processResult,
         animEl: 'elId',
         icon: Ext.MessageBox.WARNING
      });
      return false;

    } else {
    
      for (var i=0; i< rec.length; i++) {
          record[i] = rec[i].data.idAccordo;
      } 
      DetailTableCompareInit(record);
    }
  }

  // //////////////////////////////////////////////////////////////////////////
  // 
  //  Pannello principale
  //
  // //////////////////////////////////////////////////////////////////////////
  var filterPanel = new Ext.Panel({
      title: 'Filtri di ricerca',
      //height: 100,
      layout: 'anchor',
      border: true,
      frame: true,
      renderTo: 'formFilter1',
      defaults: {
          xtype: 'form',
          frame: true,
          anchor: '95%',
          layout: 'column'
      },
      items: [{ // prima riga dei filtri
              items: [{
                  xtype: 'label',
                  labelStyle: 'font-weight:bold; padding:5; left:5px; text-align:right',
                  html: '<b>Anno:</b>'
                }, {
                  xtype: 'combo',
                  id: 'annoCombo',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
            			  root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'annoente' },
                    fields: [
                      {name: 'annoEnte', type: 'string'}, {name: 'descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'annoEnte',
                  displayField: 'descrizione',
                  triggerAction: 'all',
                  emptyText: 'Seleziona un anno...',
                  listeners: {
                      beforequery: function(qe){
                          // delete the previous query in the beforequery event or set
                          // combo.lastQuery = null (this will reload the store the next time it expands)
                          if (!this.store.getCount()){
                            delete qe.combo.lastQuery;
                          }  
                      }
                  }
                }, {
                  xtype: 'label',
                  labelStyle: 'font-weight:bold; padding:5; left:5px; text-align:right',
                  html: '&nbsp;&nbsp;<b>Provincia:</b>'
                }, {
                  xtype: 'combo',
                  id: 'provinciaCombo',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'provincia' },
                    fields: [
                      {name: 'idprovincia', type: 'string'}, {name: 'Provincia', type: 'string'}
                    ]
                  },
                  valueField: 'idprovincia',
                  displayField: 'Provincia',
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona una Provincia...',
                  listeners: {
                      beforequery: function(qe){
                          // delete the previous query in the beforequery event or set
                          // combo.lastQuery = null (this will reload the store the next time it expands)
                          if (!this.store.getCount()){
                            delete qe.combo.lastQuery;
                          }  
                      }
                  }
              }, {
                  xtype: 'label',
                  labelStyle: 'font-weight:bold; padding:5; left:5px; text-align:right',
                  html: '&nbsp;&nbsp;<b>Tipo Ente:'
              }, {
                  xtype: 'combo',
                  id: 'tipoenteCombo',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'tipoente' },
                    fields: [
                      {name: 'idTipoente', type: 'string'}, {name: 'Descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'idTipoente',
                  displayField: 'Descrizione',
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona una tipo di ente...',
                  listeners: {
                      beforequery: function(qe){
                          if (!this.store.getCount()){
                            delete qe.combo.lastQuery;
                          }  
                      },
                      select: function(combo, value) {
                        var enteCombo = Ext.getCmp('enteCombo');        
                      	enteCombo.clearValue();
                      	//enteCombo.store.filter('cid', combo.getValue());
                      }
                  }
              }, {
                  xtype: 'label',
                  labelStyle: 'font-weight:bold; padding:50; left:50px; text-align:right',
                  html: '&nbsp;&nbsp;<b>Ente:'
              }, {
                  xtype: 'combo',
                  id: 'enteCombo',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'ente' },
                    fields: [
                      {name: 'idEnte', type: 'string'}, {name: 'Descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'idEnte',
                  displayField: 'Descrizione',
                  //typeAhead: true,
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona un Ente...',
                  listeners: {
                      beforequery: function(qe){
                          //if (!this.store.getCount())
                          {
                            delete qe.combo.lastQuery;
                            this.store.load({
                                        params: {
                                            anno: Ext.getCmp('annoCombo').getValue(),
                                            provincia: Ext.getCmp('provinciaCombo').getValue(),
                                            tipoente: Ext.getCmp('tipoenteCombo').getValue()
                                        }
                            });
                          }
                          return false;  
                      }
                  }
              }]
      }, {
              items: [{
                  html: '<hr>'
                }]
      }, {  // Seconda riga dei filtri
              items: [{
                  xtype: 'label',
                  //width: '80',
                  labelStyle: 'font-weight:bold; padding:50; text-align:right',  //left:50px; 
                  html: '<b>Tipologia <br>di contratto:'
                }, {
                  xtype: 'combo',
                  id: 'tipologiaCombo',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'tipologia' },
                    fields: [
                      {name: 'idTipologia', type: 'string'}, {name: 'Descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'idTipologia',
                  displayField: 'Descrizione',
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona una tipologia...',
                  listeners: {
                      beforequery: function(qe){
                          // delete the previous query in the beforequery event or set
                          // combo.lastQuery = null (this will reload the store the next time it expands)
                          if (!this.store.getCount()){
                            delete qe.combo.lastQuery;
                          }  
                      }
                  }
                  // ----------------------------
                }, {
                  xtype: 'label',
                  //width: '80',
                  labelStyle: 'font-weight:bold; padding:50; text-align:right',  //left:50px; 
                  html: '&nbsp;&nbsp;&nbsp;&nbsp;<b>Area <br>&nbsp;&nbsp;tematica:'
                }, {
                  xtype: 'combo',
                  id: 'argomentoCombo',
                  width: '300',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'argomento' },
                    fields: [
                      {name: 'idArgomento', type: 'string'}, {name: 'Descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'idArgomento',
                  displayField: 'Descrizione',
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona un area tematica...',
                  listeners: {
                      beforequery: function(qe){
                          // delete the previous query in the beforequery event or set
                          // combo.lastQuery = null (this will reload the store the next time it expands)
                          if (!this.store.getCount()){
                            delete qe.combo.lastQuery;
                          }  
                      },
                      select: function(combo, value) {
                        var temaCombo = Ext.getCmp('temaCombo');        
                      	temaCombo.clearValue();
                      	//enteCombo.store.filter('cid', combo.getValue());
                      }
                  }
                  // ----------------------------
              }, {
                  xtype: 'label',
                  //width: '80',
                  labelStyle: 'font-weight:bold; padding:50; left:50px; text-align:right',
                  html: '&nbsp;&nbsp;<b>Tema:'
                }, {
                  xtype: 'combo',
                  id: 'temaCombo',
                  width: '300',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'tema' },
                    fields: [
                      {name: 'idTema', type: 'string'}, {name: 'Descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'idTema',
                  displayField: 'Descrizione',
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona un tema...',
                  listeners: {
                      beforequery: function(qe){
                          //if (!this.store.getCount())
                          {
                            delete qe.combo.lastQuery;
                            this.store.load({
                                        params: {
                                            argomento: Ext.getCmp('argomentoCombo').getValue()
                                        }
                            });
                          }
                          return false;  
                      }
                  }
                  // ----------------------------
              }, {
                  xtype: 'label',
                  //width: '80',
                  labelStyle: 'font-weight:bold; padding:50; left:50px; text-align:right',
                  html: '&nbsp;&nbsp;<b>Beneficiario:'
              }, {
                  xtype: 'combo',
                  id: 'beneficiarioCombo',
                  store: {
                    xtype: 'jsonstore',
                    url : './filtriRicerca.ctrl.php',
                    root: 'data',
                    autoLoad: false,
                    baseParams: { action: 'beneficiario' },
                    fields: [
                      {name: 'idBeneficiario', type: 'string'}, {name: 'Descrizione', type: 'string'}
                    ]
                  },
                  valueField: 'idBeneficiario',
                  displayField: 'Descrizione',
                  forceSelection: true,
                  triggerAction: 'all',
                  emptyText: 'Seleziona un beneficiario...',
                  listeners: {
                      beforequery: function(qe){
                          // delete the previous query in the beforequery event or set
                          // combo.lastQuery = null (this will reload the store the next time it expands)
                          if (!this.store.getCount()){
                            delete qe.combo.lastQuery;
                          }  
                      }
                  }
              }, {  // Stanziamenti e agevolazioni le metto come blocco a se stante
                  layout: 'form',
                  labelWidth: 200,
                  labelAlign: 'right',
                  //margins: '30',
                  items: [{
                      xtype: 'checkbox',
                      id: 'stanziamentiCombo',
                      fieldLabel: 'Stanziamenti',
                      width: '20'
                  }, {
                    xtype: 'checkbox',
                    id: 'agevolazioniCombo',
                    fieldLabel: 'aliquote/tariffe contrattate',
                    width: '20'
                  }]
              }],
              bbarCfg: {
                height: '800'
              },
              bbar: ['->', {  // barra dei pulsanti di ricerca e reset
                        text: 'Rimuovi filtri',
                        cls: 'x-btn-text-icon',
                        iconAlign: 'left',
                        icon: './images/001_39.png',
                        width: '105',
                        tooltip: 'Rimuove tutti i filtri selezionati',
                        handler: function () {
                              // prima riga dei filtri
                              Ext.getCmp('annoCombo').store.removeAll();
                              Ext.getCmp('annoCombo').clearValue();
                              Ext.getCmp('provinciaCombo').store.removeAll();
                              Ext.getCmp('provinciaCombo').clearValue();
                              Ext.getCmp('tipoenteCombo').store.removeAll();
                              Ext.getCmp('tipoenteCombo').clearValue();
                              Ext.getCmp('enteCombo').store.removeAll();
                              Ext.getCmp('enteCombo').clearValue();
                              // seconda riga dei filtri
                              Ext.getCmp('tipologiaCombo').store.removeAll();
                              Ext.getCmp('tipologiaCombo').clearValue();
                              Ext.getCmp('argomentoCombo').store.removeAll();
                              Ext.getCmp('argomentoCombo').clearValue();
                              Ext.getCmp('temaCombo').store.removeAll();
                              Ext.getCmp('temaCombo').clearValue();
                              Ext.getCmp('beneficiarioCombo').store.removeAll();
                              Ext.getCmp('beneficiarioCombo').clearValue();
                              Ext.getCmp('stanziamentiCombo').setValue('false');
                              Ext.getCmp('agevolazioniCombo').setValue('false');

                           }
                        
                        // chiude la bottom bar delle combo di ricerca
                    }, {
                        text: 'Cerca Accordi',
                        cls: 'x-btn-text-icon',
                        iconAlign: 'left',
                        icon: './images/001_38.png',
                        width: '125',
                        tooltip: 'Cerca gli accordi in base ai filtri selezionati',
                        handler: function () {
                            // deve semplicemente chiamare lo store della griglia che si occuperà poi di collezionare i giusti valori
                            Ext.getCmp('accordoGrid').store.load({
                                  params: {
                                      anno: Ext.getCmp('annoCombo').getValue(),
                                      provincia: Ext.getCmp('provinciaCombo').getValue(),
                                      tipoente: Ext.getCmp('tipoenteCombo').getValue(),
                                      ente: Ext.getCmp('enteCombo').getValue(),
                                      tipologia: Ext.getCmp('tipologiaCombo').getValue(),
                                      argomento: Ext.getCmp('argomentoCombo').getValue(),
                                      beneficiario: Ext.getCmp('beneficiarioCombo').getValue(),
                                      stanziamenti: Ext.getCmp('stanziamentiCombo').getValue(),
                                      agevolazioni: Ext.getCmp('agevolazioniCombo').getValue(),
                                      tema: Ext.getCmp('temaCombo').getValue()
                                  }
                            });
                        }
                        // chiude la bottom bar delle combo di ricerca
              }]
      }, { // riga di separazione fra filtri e grigli
        html: '<hr>' // proprio solo una riga di separazione
      }, { // Griglia dei risultati di ricerca dei contratti
        xtype: 'panel',
        title: 'Accordi rispondenti ai criteri riscontrati',
        layout: 'fit',
        //collapsible: true,
        //collapsed: false,
        items: [{        
            xtype: 'grid',
            id: 'accordoGrid',
            //collapsible: true,
            //collapsed: false,
            store: {
              xtype: 'jsonstore',
              url : './filtriRicerca.ctrl.php',
              root: 'data',
              autoLoad: false,
              baseParams: { action: 'grigliaAccordo' },
              fields: [
                  {name: 'idAccordo',         type: 'int'},  
                  {name: 'Descrizione',       type: 'string'}, 
                  {name: 'data',              type: 'date',dateFormat: 'Y-m-d'}, 
                  {name: 'anno',              type: 'string'}, 
                  {name: 'tipologia',         type: 'string'},
                  {name: 'tipoente',          type: 'string'},
                  {name: 'ente',              type: 'string'},
                  {name: 'link',              type: 'string'}
                  //{name: 'contrICIORD',       type: 'string'}, 
                  //{name: 'contraliq1casa',    type: 'string'}, 
                  //{name: 'contradetraz1casa', type: 'string'}, 
                  //{name: 'contraliquIrpef',   type: 'string'}, 
                  //{name: 'impegnospesa',      type: 'string'},
              ],
              sortInfo: {
                  field: 'idAccordo',
                  direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
              }
            },
            columns: [
                sm,
                {id: 'Accordo', header: 'Contratto N.', dataIndex: 'idAccordo',  sortable: true},
                {header: 'Descrizione',         dataIndex: 'Descrizione',       sortable: true, hidden: true},
                {header: 'Data di stipula',     dataIndex: 'data',              sortable: true, renderer: Ext.util.Format.dateRenderer('d/m/Y')},
                {header: 'Anno di riferimento', dataIndex: 'anno',              sortable: true},
                {header: 'Tipologia Contratto', dataIndex: 'tipologia',         sortable: true},
                {header: 'Tipologia Ente',      dataIndex: 'tipoente',          sortable: true},
                {header: 'ente',                dataIndex: 'ente',              sortable: true},
                {header: 'scarica l\'accordo',  dataIndex: 'link', 
                    renderer: function() { return '<img src="./images/001_53.png" class="ico_download" />' }
                }
                //{header: 'contrICIORD',       dataIndex: 'contrICIORD',       sortable: true}, 
                //{header: 'contraliq1casa',    dataIndex: 'contraliq1casa',    sortable: true}, 
                //{header: 'contradetraz1casa', dataIndex: 'contradetraz1casa', sortable: true}, 
                //{header: 'contraliquIrpef',   dataIndex: 'contraliquIrpef',   sortable: true}, 
                //{header: 'impegnospesa',      dataIndex: 'impegnospesa',      sortable: true}
            ],
            stripeRows: true,
            //autoExpandColumn: 'Accordo',
            height: 350,
            width: 600,
            viewConfig:{
              deferEmptyText: true,
              emptyText: 'Nessun Accordo trovato per i parametri di ricerca',
              forceFit:true
            },
            selectedRow: '',
            selModel: new Ext.grid.CheckboxSelectionModel({
              singleSelect: false,
              listeners: {
                rowselect: {
                  fn: function (obj, b, rec) {
                      // ad ogni selezione si prdispone per la pagina di dettaglio
                      // questo permette di chiamare il dettaglio anche se ci sono più righe già selezionate
                      // a patto di bicliccare sul checkbox
                      Ext.getCmp('accordoGrid').selectedRow = rec.data.idAccordo;
                  }
                }
    	        }
            }),
            tbar: [{  // barra del pulsante di confronto degli accordi
                  text: 'Confronta gli accordi selezionati',
                  cls: 'x-btn-text-icon',
                  iconAlign: 'left',
                  icon: './images/001_39.png',
                  width: '105',
                  tooltip: 'Puoi selezionare fino a 5 accordi da confrontare',
                  scope: this,
                  handler: function () {
                    var sel = Ext.getCmp('accordoGrid').selModel;
                    if (sel.hasSelection()){
                      confrontaInit(sel.selections.items);
                    } else {
                      return false;
                    }
                  }
            }],
            listeners: {
              celldblclick : {
                fn: function (Grid, rowIndex, columnIndex, e) {
                  //console.log('celldblclick', Grid, rowIndex, columnIndex, e);
                  if (8 == columnIndex){  // la colonna del download.. se si cambiano le colonne va cambiata anche questa
                    //alert('Sto scaricando l\'accordo ' + Grid.store.data.items[rowIndex].data);
                    //window.open('./Contratti/' + Grid.store.data.items[rowIndex].data.idAccordo + '.doc');
                    window.open('./Contratti/redirect.php?id=' + Grid.store.data.items[rowIndex].data.idAccordo);
                    //patch stefano cudini
                    return false;
                  } else {
                    // la pagina di dettaglio si apre con l'ultima riga selezionata.
                    DetailTableInit(this.selectedRow);
                    return true;
                  }
                }
              }
            }
        }]
      }, { // riga di separazione fra griglia accordi e griglia statistich
        html: '<hr>' // proprio solo una riga di separazione
      }, { // griglia delle statistiche
        xtype: 'panel',
        title: 'Elenco delle statistiche disponibili',
        layout: 'fit',
        //collapsible: true,
        //collapsed: false,
        items: [{        
            xtype: 'grid',
            id: 'statisticheGrid',
            store: {
              xtype: 'jsonstore',
              url : './filtriRicerca.ctrl.php',
              root: 'data',
              autoLoad: true,
              baseParams: { action: 'grigliaStat' },
              fields: [
                  {name: 'idStat',      type: 'string'},  
                  {name: 'Nome',        type: 'string'}, 
                  {name: 'Descrizione', type: 'string'}, 
                  {name: 'data',        type: 'date',dateFormat: 'Y-m-d'}, 
                  {name: 'link',        type: 'string'} 
              ],
              sortInfo: {
                  field: 'data',
                  direction: 'DESC' // or 'ASC' (case sensitive for local sorting)
              }
            },
            columns: [
                {id: 'idStat', header: 'idStat', dataIndex: 'idStat',  sortable: true, hidden: true},  
                {header: 'Nome',         dataIndex: 'Nome',         sortable: true}, 
                {header: 'Descrizione',  dataIndex: 'Descrizione',  sortable: true}, 
                {header: 'data',         dataIndex: 'data',         sortable: true, renderer: Ext.util.Format.dateRenderer('d/m/Y')}, 
                {header: 'collegamento', dataIndex: 'link',         hidden: true} 
            ],
            stripeRows: true,
            autoExpandColumn: 'Nome',
            autoHeight: true,
            //height: 350,
            width: 600,
            viewConfig:{
              deferEmptyText: true,
              emptyText: 'Nessuna pagina di statistica trovata',
              forceFit:true
            },
            selModel: new Ext.grid.RowSelectionModel({
              singleSelect: true,
              listeners: {
                rowselect: function(obj, rowIndex, record) {
                  window.open(record.data.link);
                }
              }
            })
          }]
      }]
  });    

  function DetailTableInit (id) {
    var posx = (Ext.getBody().getWidth()-600)/2;
    //var posy = (Ext.getBody().getHeight()-600)/2;
    var DetailTable = new Ext.Window({
      id: 'DetailTableWindow',
      //iconCls		: 'win_replaced',
      layout: 'fit',
      renderTo: document.body,
      title: 'Dettaglio Accordo',
      x: posx,
      y: 20,
      autoEight: true,
      maximizable: true,
      //width: 700,
      //height: 900,
      //plain: false,
      closable: true,
      modal: true,
      buttons: [{
          text: 'Chiudi la finestra di dettaglio',
          handler: function(){
            DetailTable.destroy();
          }
      }],
      buttonAlign: 'right',
      closeAction:'close',
      items: {
        autoScroll: true,
        border: false,
        autoLoad: {
          url: './tabelladettaglio.php',
          //scripts: true,
          //text: "Loading...",
          //timeout: 30,
          params: { 
            idAccordo: id
          }
          //callback: function () {
            // Ha caricato il tpl della finestra, ora, 1 ad 1 carico i valori
            //Ext.get('invoiceOrdern').insertHtml('afterBegin',txt.hd_invoiceOrdern, false);
          //}
        }
      }
    });
    DetailTable.show();
  }

  function DetailTableCompareInit (rec) {
    var DetailTableCompare = new Ext.Window({
      id: 'DetailTableCompareWindow',
      //iconCls		: 'win_replaced',
      layout: 'fit',
      renderTo: document.body,
      title: 'Confronto fra Accordi',
      x: '10',
      y: '10',
      //width: 800,
      //height: 600,
      //plain: false,
      autoEight: true,
      maximizable: true,
      closable: true,
      modal: true,
      buttons: [{
        text: 'Chiudi la finestra del confronto',
        handler: function(){
          DetailTableCompare.destroy();
        }
      }],
      buttonAlign: 'right',
      closeAction:'close',
      items: {
        autoScroll: true,
        border: false,
        autoLoad: {
          url: './tabellacompare.php?idAccordi='+rec
        }
      }
    });
    DetailTableCompare.show();
  }

});
