<?php

include_once("_dirinfo.php");
include_once (PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."config.php");

$idField = "id";

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

$gridName = "settingsGrid_" . $tableName;

$ajax = $pluginDir . "/_forms/_ajax/ajax.settings.php";

$sql = "SELECT * FROM " .  DB_WARPIT_WEBCATI_BASE . "._Plugin_label WHERE id_plugin = 9 ORDER BY order_by" ;
$res= $db->SQLexecute($sql);

$sourceArray = array();
$propertysNameArray = array();
$fieldsArray = array();

while ($dat = $db->fetchAssoc($res)) {  
    $sourceArray[] = $dat['name'] . ": ''";
    $propertysNameArray[] = $dat['name'] . " : '" . $dat['label'] . "'";
    $fieldsArray[]  = "{ name:'" . $dat['name'] ."', type: '" . $dat['type'] . "' }";
}

//print_r($propertysNameArray);  

?>
var font_combo = new Ext.form.ComboBox({
       allowBlank     : false,
       store: [
            ['Verdana'],
            ['Arial'],
            ['Times New Roman']
        ],
       typeAhead    : true,
        mode        : 'local',
        triggerAction    : 'all',
        emptyText    :'-- Select scale type--',
        selectOnFocus    :true
   });
   
var <?php echo $gridName;?> = new Ext.grid.PropertyGrid({
        id : '<?php echo $gridName; ?>',
        title: "Basic settings",
        editable : true,
        border : false,
        //autoHeight: true,
        layout: 'fit',
        source: {
            <?php echo implode(',', $sourceArray); ?>
        },
        propertyNames: {
            <?php echo implode(',', $propertysNameArray); ?>
        },
        customEditors:{
        	'default_value': new Ext.grid.GridEditor(new Ext.form.TextField({
        		validator: function(value){
        			//var regex = new RegExp('^[0-9]+$');
        			return true;
        			
        		}
        	})),
        	
            'scale_type':  new Ext.grid.GridEditor(new Ext.form.ComboBox({
                            fieldLabel    : 'Scale type',
                            name        : 'scale',
                           allowBlank     : false,
                           store: [
                                ['1','Interval'],
                                ['2','Time']
                            ],
                            renderer : function(a) {
                                if (a == 1) return 'Interval';
                                else if (a == 2) return 'Time';
                            },
                           typeAhead    : true,
                            mode        : 'local',
                            triggerAction    : 'all',
                            emptyText    :'-- Select scale type--',
                            selectOnFocus    :true
                       })),
           'scale_font': new Ext.grid.GridEditor(new Ext.form.ComboBox({
                   allowBlank     : false,
                   store: [
                        ['Verdana', 'Verdana'],
                        ['Arial', 'Arial'],
                        ['Times New Roman', 'Times New Roman']
                    ],
                   typeAhead    : true,
                    mode        : 'local',
                    triggerAction    : 'all',
                    selectOnFocus    :true
           })),
           'slider_font': new Ext.grid.GridEditor(new Ext.form.ComboBox({
                   allowBlank     : false,
                   store: [
                        ['Verdana', 'Verdana'],
                        ['Arial', 'Arial'],
                        ['Times New Roman', 'Times New Roman']
                    ],
                   typeAhead    : true,
                    mode        : 'local',
                    triggerAction    : 'all',
                    selectOnFocus    :true
           })),
           'extreme_font': new Ext.grid.GridEditor(new Ext.form.ComboBox({
                   allowBlank     : false,
                   store: [
                        ['Verdana', 'Verdana'],
                        ['Arial', 'Arial'],
                        ['Times New Roman', 'Times New Roman']
                    ],
                   typeAhead    : true,
                    mode        : 'local',
                    triggerAction    : 'all',
                    selectOnFocus    :true
           })),
           'slider_type': new Ext.grid.GridEditor(new Ext.form.ComboBox({
                   allowBlank     : false,
                   name: 'extreme_type_cb',
                   store: [
                        ['1', 'Circle'],
                        ['2', 'Squar']
                    ],
                   typeAhead    : true,
                    mode        : 'local',
                    triggerAction    : 'all',
                    selectOnFocus    :true,
                  closeAction: 'hide'}))
        },
        customRenderers:{
            'scale_type' : function(a) {
                                if (a == 1) return 'Interval';
                                else if (a == 2) return 'Time';
                        },
            'slider_type' : function(a) {
                    if (a == 1) return 'Circle';
                    else if (a == 2) return 'Squar';
                }
        },
        loadData: function() 
        {
            new Ext.data.JsonStore({
                url : '<?php echo $ajax; ?>',
                root : 'rows',
                autoLoad: true,
                idProperty : '<?php echo $idField; ?>',
                baseParams: {
                    action: 'get',
                    projectId: '<?php echo $projectId; ?>',
                    questionId: '<?php echo $questionId; ?>'
                    
                    },
                fields:[
                         <?php echo implode(',', $fieldsArray); ?>
                         
                ],
                listeners: {
                    load: {
                        fn: function(store, records, options){
                                <?php echo $gridName; ?>.setSource(store.getAt(0).data);
                        }
                    }
                }
           });
        },
        saveData: function()
        {
            var source = <?php echo $gridName; ?>.getSource();
            
            var jsonData = Ext.encode(source);
            
            CallScript('<?php echo $ajax; ?>', {
                action: 'Save',
                data: jsonData,
                projectId: <?php echo $projectId; ?>,
                questionId: <?php echo $questionId; ?>
            }) 
        },
        listeners:{
            propertychange: function(record){
                    <?php echo $gridName; ?>.saveData();
                    //<?php echo $gridName; ?>.loadData();
            },
            beforeedit: function(e)
            {
                if(e.record.id == 'scale_values')
                {
                    var data = e.value;
                    var window = new Ext.Window({
                        width:500,
                        height:300,
                        layout: 'column',
                        title: 'Custom scale values',
                        items:[{
                            xtype:'form',
                            width: '100%',
                            region:'center',
                            items:[{
                              layout: 'column',
                              anchor: '0',
                              items:[{
                                  xtype:'container',
                                  layout:'form',
                                  items: [{
                                        xtype:'numberfield',
                                        columnWidth:.7,
                                        layout:'form',
                                        id: 'steps_input_<?php echo $tableName; ?>',
                                        fieldLabel: 'Number of steps'
                                    }]
                              },{
                              xtype:'button',
                              text: 'Update',
                              columnWidth:.2,
                              handler: function(e)
                                {
                                    var grid = Ext.getCmp('grid_<?php echo $tableName; ?>');
                                    
                                    var data = [];
                                    data.push(Ext.getCmp('steps_input_<?php echo $tableName; ?>').getValue());
                                    grid.getStore().each(function(rec){
                                        data.push(rec.get('value'));
                                    });
                                    grid.getStore().baseParams.data = data.join(';');
                                    grid.getStore().removeAll();
                                    grid.getStore().reload();
                                    
                                },
                              layout:'form'
                            }]  
                            },
                            new Ext.grid.EditorGridPanel({
                                height: 200,
                                id: 'grid_<?php echo $tableName; ?>',
                                autoScroll: true,
                                clicksToEdit: 1,
                                border: 0,
                                listeners:{
                                    beforerender: function(e)
                                    {
                                        e.getStore().baseParams.data = data;
                                        
                                        var splitData = data.split(';');
                                        if(splitData[0])
                                            Ext.getCmp('steps_input_<?php echo $tableName; ?>').setValue(splitData[0]);
                                    }
                                },
                                store: new Ext.data.JsonStore({
                                        url : '<?php echo $ajax; ?>',
                                        root : 'rows',
                                        autoLoad: true,
                                        baseParams: {
                                            action: 'getGridData'
                                            },
                                        fields:[
                                                 {name: 'value', type:'string'}
                                        ]}),
                                    colModel: new Ext.grid.ColumnModel({
                                        defaults: {
                                            width: 120,
                                            sortable: true
                                        },
                                        columns: [
                                            {
                                                id: 'company', 
                                                header: 'Value', 
                                                dataIndex: 'value',
                                                width: '100%',
                                                editor: new  Ext.form.TextField({
                                                }) 
                                            },
                                        ]
                                    }),
                                    sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
                                    frame: true,
                                })]
                            
                        }],
                        buttons: [{
                            text: 'Save',
                            handler: function(){
                               var grid = Ext.getCmp('grid_<?php echo $tableName; ?>');
                                        
                                var data = [];
                                data.push(Ext.getCmp('steps_input_<?php echo $tableName; ?>').getValue());
                                grid.getStore().each(function(rec){
                                    data.push(rec.get('value'));
                                });
                                
                                CallScript('<?php echo $ajax; ?>', {
                                    action: 'saveScaleValue',
                                    data: data.join(';'),
                                    projectId: <?php echo $projectId; ?>,
                                    questionId: <?php echo $questionId; ?>
                                });
                                
                                <?php echo $gridName; ?>.loadData();
                                window.close();
                            }
                        },{
                            text: 'Reset',
                            handler: function(){
                                
                                var grid = Ext.getCmp('grid_<?php echo $tableName; ?>');
                                grid.getStore().baseParams.data = '';
                                grid.getStore().removeAll();
                                grid.getStore().reload();
                                
                                Ext.getCmp('steps_input_<?php echo $tableName; ?>').setValue('');
                                
                                
                            }
                        }]
                    }).show();
                }
            }
        }
        
}).show();

<?php echo $gridName; ?>.loadData();

Ext.getCmp('pluginSettings_<?php echo $tableName; ?>').insert(0, <?php echo $gridName; ?>);
Ext.getCmp('pluginSettings_<?php echo $tableName; ?>').setActiveTab(<?php echo $gridName; ?>);
