<script type="text/javascript">
    var ExtGridEditorAutomailer = {};

    Ext.onReady(function(){
        function renderName(value, p, record){
            //You can just look at this store and find the match for the name
            var elementIndex = ExtGridEditorAutomailer.templateNameDropDownStore.find('optionvalue', value);
            if(elementIndex > -1){
                var elementObject = ExtGridEditorAutomailer.templateNameDropDownStore.getAt(elementIndex);
                return elementObject.data['optionname'];
            }else if(value == 'Choose One...'){
                return value;
            }else{
                return lang('TEMPLATE WITH ID % NOT FOUND!', value);
            }
        }
        
        ExtGridEditorAutomailer.gridstore = new Ext.data.ArrayStore({
            fields:   ["templateid","days","event"],
            data:     <?php echo $this->gridData; ?>
        });
        
        ExtGridEditorAutomailer.templateNameDropDownStore =  new Ext.data.ArrayStore({
            fields: ['optionvalue', 'optionname'], 
            data: <?php echo $this->emailTemplates; ?>
       });
        
        ExtGridEditorAutomailer.grid = new Ext.grid.EditorGridPanel({
            id:               'automailergrid',
            name:             'automailergrid',
            renderTo:         'ExtGridEditorAutomailer',
            autoHeight:       true,
            store:            ExtGridEditorAutomailer.gridstore,
            trackMouseOver:   true,
            loadMask:         true,
            selModel:         new Ext.grid.RowSelectionModel(),
            clicksToEdit:     1,
            x:                5,
            y:                40,
            width:            516,
            height:           250,
            columns:[
                {
                id: 'templateid', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header: lang("Template Name"),
                width: 150,
                dataIndex : "templateid",
                sortable: false,
                align:"left",
                menuDisabled: true,
                renderer: renderName,
                editor: new Ext.form.ComboBox({
                   store : ExtGridEditorAutomailer.templateNameDropDownStore,
                   typeAhead: true,
                   triggerAction: 'all',
                   mode: 'local',
                   editable: false,
                   displayField: 'optionname',
                   valueField: 'optionvalue'
                })
            },{
                id: 'days', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header: lang("Days"),
                width: 40,
                dataIndex : "days",
                sortable: false,
                menuDisabled: true, 
                editor: new Ext.form.NumberField({allowDecimals: false, allowNegative: false})
            },{
                id: 'event', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header: lang("Event"),
                width: 100,
                dataIndex : "event",
                sortable: false,
                menuDisabled: true, 
                editor: new Ext.form.ComboBox({
                   store : new Ext.data.ArrayStore({
                        fields: ['optionvalue', 'optionname'], 
                        data: [
                            ['After Account Activated', 'After Account Activated'],
                            ['After Account Canceled',  'After Account Canceled'],
                            ['After Package Activated', 'After Package Activated'],
                            ['After Package Canceled',  'After Package Canceled']
                            
                            // This Option will be hidden at the moment.
                            //,['Before Domain Expires',   'Before Domain Expires']
                        ]
                   }),
                   typeAhead: true,
                   triggerAction: 'all',
                   mode: 'local',
                   editable: false,
                   displayField: 'optionname',
                   valueField: 'optionvalue'
                })
            }],
            tbar: [
            {
                text:     'Add',
                //disabled: true,
                id:       'ExtGridEditorAutomailerAdd',
                handler:  function(){
                    var Record = ExtGridEditorAutomailer.grid.getStore().recordType;
                    var p = new Record({templateid: 'Choose One...', days: 0, event: 'Choose One...'});
                    // Code to insert a new row
                    ExtGridEditorAutomailer.grid.stopEditing();
                    var rownum = ExtGridEditorAutomailer.gridstore.getCount();
                    ExtGridEditorAutomailer.gridstore.insert(rownum,p);
                    ExtGridEditorAutomailer.grid.startEditing(rownum, 0);
                }
            },
            '-',
            {
                text:     'Delete',
                //disabled: true,
                id:       'ExtGridEditorAutomailerDelete',
                handler:  function(){
                    var rec = ExtGridEditorAutomailer.grid.getSelectionModel().getSelected();
                    if (!rec) {
                        return false;
                    }
                    ExtGridEditorAutomailer.grid.store.remove(rec);
                }
            },
            '-',
            {
                text:     'Save',
                //disabled: true,
                id:       'ExtGridEditorAutomailerSave',
                handler:  function(){
                    var rec = ExtGridEditorAutomailer.grid.getStore();
                    if (!rec) {
                        return false;
                    }else{
                        var ArrayData = {};

                        rows = rec.data['items'];
                        for(x=0; x<rows.length; x++){
                            rows2 = rows[x].data;

                            for(var item in rows2) {
                                if(rows2[item] == 'Choose One...'){
                                    Ext.Msg.alert('Error', lang('There are some invalid values. Please correct them and try again.'));
                                    exit;
                                }
                            }
                            ArrayData[x] = rows[x].data;
                        }

                        Ext.Ajax.request({
                            url:      "index.php?fuse=admin&action=updatePluginSettingGrid",
                            params:{
                                settingId:  <?php echo $this->settingId;?>,
                                settingValues: Ext.util.JSON.encode(ArrayData)
                            },
                            success: function(xhr){
                                var data = Ext.util.JSON.decode(xhr.responseText);
                                if(data.error){
                                    msg(lang("There was an error performing this action"));
                                }else if(data.message){
                                    msg(data.message);
                                }else{
                                    msg(lang("The action has been performed"));
                                }
                                ExtGridEditorAutomailer.gridstore.commitChanges();
                            },
                            failure: function(){
                                var data = Ext.util.JSON.decode(xhr.responseText);

                                if(data.error){
                                    msg(lang("There was an error performing this action"));
                                }else if(data.message){
                                    msg(data.message);
                                }else{
                                    msg(lang("The action has been performed"));
                                }
                            }
                        });
                    }
                }
            }
            ],
            stripeRows:       true,
            viewConfig:       {
                forceFit:       true,
                enableRowBody:  true,
                emptyText:      lang("There are no items to display"),
                scrollOffset:   1
            }
        });

        ExtGridEditorAutomailer.grid.render();
    });
        
</script>
<span id='ExtGridEditorAutomailer'></span>