<?php 
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");

    $tabId = $_POST['uniqueTabId'];
    $tabTitle = $_POST['name'];
    
    define(REQ_URL, "webuserspool/_ajax/panelistsOverview/ajax.panelistsOverview.php");
    
    $grpTree = "PoolMenu_1";
    
    // ############################################### MAIN GRID ##################################################################
    $grid = new MakeGrid($tabId);
    $grid->setCheckBoxSelectionModel();
    $grid->setReqUrl(REQ_URL)
        ->setFiltering();
    $grid->addColumn('id','ID')->hidden(true);
    $grid->addColumn('email', 'Email')->width(250)->table('a');
    $grid->addColumn('points', 'Points')->width(60)->type('int');
  /*  $grid->addColumn('proj_name', "Project")->width(150)->addSummaryRenderer("function(v, params, data){
                    return ((v === 0 || v > 1) ? '<b>(' + v +' Projects)<b>' : '<b>(1 Project)<b>');
                }")->addSummaryType('count');
    $grid->addColumn('webPoints', 'Web points')->table('d')->type('int')->tableAs('d')->width(80)->addSummaryType('sum');*/
    $grid->addSummaryGroup();
    $grid->addConfig('selectedUser', "''");
    $grid->addConfig('user_id','function(id){
        if(id)
            this.selectedUser = id;
        else 
            return this.selectedUser;            
    }');
    $grid->addConfig('id_group','-1');
    $grid->setPaging(30);
    $grid->addConfig('region', '"center"');
    $grid->addConfig('where', '""');
/*    $grid->addTbarItem("{ text: 'Recalculate',
        handler: function() {
            rec = ".$grid.".getSelectionModel().getSelected();
            $grid.RMconn.request({
                      url:'webcati/_ajax/webPoints/ajax.webPoints.php',
                      params:{ action:'recalculate', id_project: rec.data.id_project },
                      success:function(){ 
                        alert('done');
                      }
                })
            
        }
    }");*/

        // ############################################### PURPOSE GRID ##################################################################
    
   $purposeGrid = new MakeGrid($tabId . "_purposeGrid");
   $purposeGrid->setReqUrl(REQ_URL);
   $purposeGrid->setMainTable(DB_WARPIT_WEBCATI_BASE . '._wwwPurpose', DB_WARPIT_WEBCATI_BASE);
   $purposeGrid->addColumn('id');
   $purposeGrid->addColumn('label', 'Purpose', 'new Ext.form.TextField()') -> width(300);
   $purposeGrid->addColumn('negative', 'Positive') -> width(160) -> type('checkColumn')->width(80);
   $purposeGrid->setCheckBoxSelectionModel();
   $purposeGrid->setTitle('Purposes');
   $purposeGrid->createAddButton();
   
   $purposeGrid->activateAdd();
   $purposeGrid->activateRemove();
   
    
    // ############################################### DETAILS GRID ##################################################################
   $detailsGrid = new MakeGrid($tabId . "_details");
   $detailsGrid->dateSQL = 'U';
   $detailsGrid->addSummaryGroup();
   $detailsGrid->setReqUrl(REQ_URL);
//   $detailsGrid->setMainTable('_wwwPurpose', DB_WARPIT_WEBCATI_BASE);
   $detailsGrid->addColumn('id', 'ID')->hidden(true);
   $detailsGrid->addColumn('label', 'Purpose') -> width(300)->addSummaryRenderer("function(v, params, data){
                    return ((v === 0 || v > 1) ? '<b>(' + v +' Projects)<b>' : '<b>(1 Project)<b>');
                }")->addSummaryType('count');
   $detailsGrid->addColumn('modificationDate',"Date")->type('date')->width(150)->renderer("function(v) {
                 if(v.format('U') > 100) return Ext.util.Format.date(v, 'd.m.Y h:i:s');
            }");
   $detailsGrid->addColumn('points', 'Points') -> width(80) -> type('int')->addSummaryType('sum');
   $detailsGrid->addColumn('naziv_proj', 'Project') -> width(200);
   $detailsGrid->setAutoLoad(false);
   $detailsGrid->setPaging(30);
   $detailsGrid->setCheckBoxSelectionModel();
   $detailsGrid->setTitle('Details');
   $detailsGrid->addBottomBarItem('{
       xtype: "button",
       iconCls: "x-tbar-loading",
       handler: function()
       {
           var selectedId = Ext.getCmp("' . $grid->getName() . '").getSelectionModel().getSelected();
           if(selectedId)
           {
               Ext.getCmp("' . $detailsGrid->getName() . '").reload(selectedId.id);
           }
           else
               Ext.Msg.show({ title:"Info", msg: "You have to select panelist first!", icon: Ext.MessageBox.INFO, buttons: Ext.Msg.OK});
       }
   }');
   $detailsGrid->addConfig('closable', 'false');
   $detailsGrid->addConfig('reload', 'function(id){
        this.getStore().load({params:{
            id_interviewer: id
        }}); 
    }');
    $detailsGrid->activateRemove();
  
   
   // ############################################### ADD POINTS FORM ##################################################################
   
   $storeDataType = 'StoreBaseType_'. $tabId;
    
    echo "var $storeDataType =  new Ext.data.Store({ 
                        reader: new Ext.data.JsonReader({ 
                                        fields: ['id', 'label'],
                                        root: 'rows'
                        }),
                        baseParams: {
                          action: 'selectPurposes'  
                        },
                        proxy: new Ext.data.HttpProxy({
                                        
                                        url: 'webuserspool/_ajax/panelistsOverview/ajax.panelistsOverview.php'
                        }),
                        
                        autoLoad: 'true'                
    });";
   $propertiesForm = new MakeForm($tabId . "_addPoints");
//   $propertiesForm->setMainTable('_IncentiveProperties',DB_WARPIT_USERSPOOL);
     $propertiesForm->setTitle('Add points')
        //->setAutoUpdate()
        ->addConfig('labelWidth',160)
        ->addConfig('labelAlign',"'right'")
        ->addConfig('closable',"true")
        ->flex(1);
    
   $propertiesForm->addField('id_purpose','Purpose','combo')->setProperty('store',$storeDataType)->setProperty('displayField','"label"')
        ->setProperty('valueField','"id"')->setProperty('mode','"remote"')->setProperty('triggerAction','"all"')->setProperty('editable','false')->width(300);
    $propertiesForm->addField('numberOfPoints','Points','numberfield');
    $propertiesForm->setReqUrl(REQ_URL);
    $propertiesForm->addtBarItem("{
        text:'Add',
        iconCls:'RMicon_save_as', 
        menu: [
        {
            text:'Add to selected',
            iconCls:'RMicon_save_as',
            handler: function()
            {
                var id = $grid.user_id();
            
                if(id.length > 0)
                {
                    $propertiesForm.getForm().submit({
                        params: {
                            id_user: $grid.getSelectedIds('id').join(',')
                        },
                        success: function()
                        {
                            $detailsGrid.reload(id);
                            $grid.getStore().reload({
                                    params: {
                                        id_group: $grid.id_group
                                    }
                                });
                            $propertiesForm.ownerCt.remove($propertiesForm);
                        }
                    });    
                }
                else 
                {
                    Ext.Msg.show({ title:'Info', msg: 'You have to select user from list!', icon: Ext.MessageBox.INFO, buttons: Ext.Msg.OK});
                }
        
            }
        },
        {
            text:'Add to all',
            iconCls:'RMicon_save_as',
            handler: function()
            {
                $propertiesForm.getForm().submit({
                    params: {
                        where : " . $grid->getName() . ".where
                    },
                    success: function()
                    {
                        $detailsGrid.reload(id);
                        $grid.getStore().reload({
                            params: {
                                id_group: $grid.id_group
                            }
                        });
                        //$propertiesForm.close();
                        $propertiesForm.ownerCt.remove($propertiesForm);
                    }
                });    
      
        
            }
        }
        ]}
       
    ");
    /*
    $propertiesForm->addtBarItem("{text:'Add',iconCls:'RMicon_save_as',handler: function(){
        var id = $grid.user_id();
        
        if(id.length > 0)
        {
            $propertiesForm.getForm().submit({
                params: {
                    id_user: $grid.getSelectedIds('id').join(',')
                },
                success: function()
                {
                    $detailsGrid.reload(id);
                    $grid.getStore().reload();
                    //$propertiesForm.close();
                    $propertiesForm.ownerCt.remove($propertiesForm);
                }
            });    
        }
        else 
        {
            Ext.Msg.show({ title:'Info', msg: 'You have to select user from list!', icon: Ext.MessageBox.INFO, buttons: Ext.Msg.OK});
        }
        
    }}");
    $propertiesForm->addtBarItem("{text:'Add to all',iconCls:'RMicon_save_as',handler: function(){
            $propertiesForm.getForm().submit({
                params: {
                    where : " . $grid->getName() . ".where
                },
                success: function()
                {
                    $detailsGrid.reload(id);
                    $grid.getStore().reload();
                    //$propertiesForm.close();
                    $propertiesForm.ownerCt.remove($propertiesForm);
                }
            });    
      
        
    }}");*/
   // ###############################################  ##################################################################
   echo $detailsGrid->createGrid();
   echo $detailsGrid->getName() . ".on('afterlayout', function(){
       Ext.getCmp('" . $detailsGrid->getName() . "').getBottomToolbar().refresh.hide()
   })";
    $grid->addTbarItem("{ text: 'Purposes',
        iconCls: 'iconPurpose',
        handler: function() {
        " . $purposeGrid->createGrid() . "
            Ext.getCmp('" . $tabId . "_propertiesPanel').add($purposeGrid).show();
        }
    }");
    
    $grid->addTbarItem("{ text: 'Add points',
        iconCls: 'icon-add-record',
        handler: function() {
        " .  $propertiesForm->createForm() . "
            Ext.getCmp('" . $tabId . "_propertiesPanel').add($propertiesForm).show();
        }
    }");
    
    $grid->addTbarItem("{
        text: 'Select group',
        enableToggle:true,
        iconCls: 'icon-webuserspool-tab',
        toggleHandler: function(bt, state) 
        {
            if(state)
            {
               var grTree = Ext.getCmp('$grpTree');
                if(!grTree) { addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'});Ext.Msg.alert('Warning!','Please select a group!'); return;}
                var n = grTree.getSelectionModel().getSelectedNode();
                if(n && n.isLeaf())
                {
                    bt.setText('Deselect group');
                    $grid.id_group = n.attributes.id;
                    
                }
                else 
                {
                    Ext.Msg.alert('Warning!','Please select a group!')    
                } 
            }
            else
            {
                $grid.id_group  = -1;
                bt.setText('Select group');
            }
            
          $grid.getStore().setBaseParam('id_group', $grid.id_group);
          $grid.getStore().reload({
                    params: {
                        id_group: $grid.id_group
                    }
                });
            
            
        }
    }");
     $grid->addtBarItem("'->'");
    $grid->setSearchField();
    
    
    // ############################################### MAIN ################################################################## 
   echo $grid->createGrid();
   echo $grid->getName().".getSelectionModel().on( 'rowselect', function(sm,index,r){
            var id = r.get('id');
            $grid.user_id(id);
            $detailsGrid.reload(id);
   });"; 
   echo $grid->getName().".getStore().on('load', function(a){
      " . $grid->getName() . ".where = a.reader.jsonData.where;
      
   });"; 
   echo " var " . $tabId . "_mainPanel = new Ext.Panel({
        id:'" . $tabId . "_mainPanel',
        title:'Active panelists',
        defaults:{split:true,border:false},
        layout:'border',
        border: false,
        closable:true,
        items:[$grid,
              {
                xtype:'tabpanel',
                height: 300,
                id:'" . $tabId ."_propertiesPanel',
                region:'south',
              //  items: [ $purposeGrid ] 
        
        }   ]
    });
    
    mainTabPanel.add(" . $tabId . "_mainPanel ).show();  
    Ext.getCmp('" . $tabId . "_propertiesPanel').add($detailsGrid).show();
    ";
  //  echo $purposeGrid .".getStore().load();";
?>