<?php 

$idField = "id_plugin";

$ajax  = "webcati/_forms/plugins/_ajax/ajax.plugin.php";

$tableName = $_POST['tableName'];
$questionId = $_POST['questionId'];
$projectId = $_POST['projectId'];


$pluginId = $_POST['pluginId'];

$panelName = "copySettings_" . $tableName;


?>

Ext.ns('Ext.ux.grid');
Ext.ux.grid.CheckColumn = Ext.extend(Ext.grid.Column, {
 processEvent: function(name, e, grid, rowIndex, colIndex){
  if(name == 'mousedown'){
   var record = grid.store.getAt(rowIndex);
   record.set(this.dataIndex, !record.data[this.dataIndex]);
   return false;
  }else{
   return Ext.grid.ActionColumn.superclass.processEvent.apply(this, arguments);
  }
 },
 renderer: function(v, p, record){
  p.css += ' x-grid3-check-col-td';
  return String.format('<div class="x-grid3-check-col{0}">&#160;</div>',v ? '-on' : '');
 },
 init: Ext.emptyFn
});
Ext.preg('checkcolumn', Ext.ux.grid.CheckColumn);
Ext.grid.CheckColumn = Ext.ux.grid.CheckColumn;
Ext.grid.Column.types.checkcolumn = Ext.ux.grid.CheckColumn;


Ext.getCmp('pluginSettings_<?php echo $tableName; ?>').add(
 {
     title: 'Copy settings' ,
     id: '<?php echo $panelName; ?>',
     plain:true,
     closable: false,
     height: 300,
     layout: 'border',
     items: [{
         height: 300,
            region: 'west',
            split: true,
            //anchor:'70%',
           layout: 'fit',
           autoScroll:true, 
            animCollapse : true,
            width: 200,
            
         //   id: 'pluginList_<?php echo $tableName; ?>',
            items:[{
               id: '<?php echo $panelName; ?>_projectsList',
               xtype: 'treepanel',
                autoScroll:true, 
                
              // layout: 'fit',
              tbar: ['->', new Ext.form.TwinTriggerField({
                    trigger2Class: 'x-form-clear-trigger',
                    width: 100,
                    fieldLabel: 'Find project',
                    trigger1Class: 'x-form-search-trigger',
                    onTrigger1Click: function() {
                        var tree = Ext.getCmp('<?php echo $panelName; ?>_projectsList');
                        tree.loader.baseParams.action = "GetProjects";
                        tree.loader.baseParams.filter = this.getValue();
                        
                        tree.loader.load(tree.getRootNode());
                        tree.getRootNode().expand();
                        tree.loader.baseParams.action = "GetQuestions"
                    },
                    onTrigger2Click: function() {
                        var tree = Ext.getCmp('<?php echo $panelName; ?>_projectsList');
                        tree.loader.baseParams.action = "GetProjects";
                        delete tree.loader.baseParams.filter;
                        this.setValue('');
                        tree.loader.load(tree.getRootNode());
                        tree.getRootNode().expand();
                        tree.loader.baseParams.action = "GetQuestions"
                    },
                    listeners: {
                        specialkey: function(field, e) {
                            // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
                            // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
                            if (e.getKey() == e.ENTER) {
                                field.onTrigger1Click();
                            }
                        }
                    }
                })],
               loader: new Ext.tree.TreeLoader({ 
                   listeners:{
                     beforeload : {
                         fn: function(a, b)
                         {
                            if(this.baseParams.action == "GetQuestions")
                                this.baseParams.projectName = b.attributes.projectName; 
                                this.baseParams.projectId = b.attributes.projectId;
                         }
                     }  
                   },
                   url:'<?php echo $ajax; ?>',
                   baseParams: {
                       action: 'GetProjects',
                       pluginId: <?php echo $pluginId; ?>,
                       questionId: '<?php echo $questionId; ?>'
                       
                   }
               }),
               root: {text: "Projects", expanded: true},
               listeners: {
               click: {
                    fn:function(e, b)
                    {
                        if(e.leaf)
                        {
                            /*console.log(e.attributes.questionId);
                            console.log(e.attributes.projectId);*/
                           Ext.getCmp('avaible_<?php echo $panelName; ?>').loadOptions(e.attributes.projectId, e.attributes.questionId)
                        }
                        else
                        {
                           
                        }  
                    }
                  
                },
                load: {
                    fn: function(e, b)
                    {
                        this.loader.baseParams.action = "GetQuestions";
                    }
                }
            },
            }],
            border: false,
            margins:'3 0 3 3',
            cmargins:'3 3 3 3'
     },
     {
            region: 'center',
            split: true, 
           // anchor:'70%',
            autoScroll:true,
            layout: 'fit', 
            items:[{
                xtype: 'editorgrid',
                id: 'avaible_<?php echo $panelName; ?>',
                editable : false,
                border : false,
                projectId: '',
                questionId: '',
                pluginName: '',
                layout: 'fit',
                height: 300,
                plugins:[
                    new Ext.ux.grid.Search({
                        searchText:'Search',  
                        minChars:3,
                        position:'top',
                        disableIndexes: ['option', 'type', 'value'],
                        paramNames:{
                            fields:'srcfields', 
                            query:'srcquery'
                        },
                        ref: 'searchField'
                    })
            ],
                loadOptions: function(projectId, questionId)
                {
                    var grid = Ext.getCmp('avaible_<?php echo $panelName; ?>');
                    grid.getStore().removeAll();
                    grid.getStore().reload({params: {action: 'GetOptions', questionId: questionId, projectId: projectId, pluginId: <?php echo $pluginId; ?>}});
                    
                    grid.projectId = projectId;
                    grid.questionId = questionId;
                },
                selModel : new Ext.grid.RowSelectionModel(),
                closable : true,
                viewConfig: {
                    markDirty: false
                },
                store: new Ext.data.JsonStore({
                        url : '<?php echo $ajax; ?>',
                        root : 'rows',
                        autoLoad: false,
                        fields:[
                                 { name:"option", type: 'string' },
                                 { name:"optionLabel", type: 'string' },
                                 { name:"value", type: 'string' },
                                 { name:"tableName", type:'string'},
                                 { name:"copy", type: 'bool' }
                        ],
                }),
                cm: new Ext.grid.ColumnModel({
                    columns: [{
                        header: 'Option',
                        dataIndex: 'optionLabel',
                        width: 200,
                        
                    },{
                        header: 'Value',
                        dataIndex: 'value',
                        width: 175,
                        flex: 1
                    },
                    {
                        
                        header: 'Copy',
                        dataIndex: 'copy',
                        xtype: 'checkcolumn'
                        
                    }
                    ]}
                ),
                tbar:[{
                    text: 'Copy',
                    iconCls: 'RMicon_copy',
                    handler: function()
                    {
                        var grid = Ext.getCmp('avaible_<?php echo $panelName; ?>');
                        
                        //console.log(grid);
                        
                        var data = Array();
                        var table = "";
                        grid.getStore().each(function(rec){
                            table = rec.get('tableName');
                            if(rec.get('copy'))
                            {
                                var dat= {};
                                dat[rec.get('option')] = rec.get('value');
                                data.push(dat);
                            }
                        });
                        
                        data = Ext.encode(data);
                        CallScript('<?php echo $ajax; ?>',{
                            action: 'CopySettings',
                            questionId: <?php echo $questionId; ?>,
                            projectId: <?php echo $projectId; ?>,
                            table: table,
                            data: data
                        },function(){
                            Ext.MessageBox.alert('Status', 'Properties were successfully copied.');
                        });
                    }
                }, {
                    text: 'Select all',
                    handler: function()
                    {
                        var grid = Ext.getCmp('avaible_<?php echo $panelName; ?>');
                        Ext.each(grid.getStore().getRange() , function(rec){
                            rec.set('copy', true);
                        });
                        
                    }
                },{
                    text: 'Select none',
                    handler: function()
                    {
                        var grid = Ext.getCmp('avaible_<?php echo $panelName; ?>');
                        Ext.each(grid.getStore().getRange() , function(rec){
                            rec.set('copy', false);
                        });
                        
                    }
                }, '->']
            }],    
            border: false,
            margins:'3 0 3 3',
            cmargins:'3 3 3 3'
     }
     ]
 }
);
