var grid;
var gridstore;
var publishstatus = 'all';
var gridLimit = 25;

var KBcommentsWaitingMask;
var toggleButtons;

Ext.onReady(function(){
    
    var limitcombo = new Ext.form.ComboBox({
        triggerAction:  'all',
        id:             "limitcombo",
        lazyRender:     true,
        editable:       false,
        value:          gridLimit,
        mode:           'local',
        store:          new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                [
                    10,
                    "10"
                ],
                [
                    25,
                    "25"
                ],
                [
                    50,
                    "50"
                ],
                [
                    150,
                    "150"
                ],
                [
                    300,
                    "300"
                ]
            ]
        }),
        valueField:     'id',
        displayField:   'name',
        width:          50,
        applyTo:        'filterByLimit',
        listeners:      {
            'select': function(cb,record){
                toggleButtons(0);
                
                gridLimit = record.data.id
                
                gridbb.pageSize = gridLimit;
                
                gridstore.load({
                    params: {
                        start:  0,
                        limit:  gridLimit
                    }
                });
            }
        }
    });
    
    var publishstatuscombo = new Ext.form.ComboBox({
        triggerAction:  'all',
        id:             "publishstatuscombo",
        lazyRender:     true,
        editable:       false,
        value:          publishstatus,
        mode:           'local',
        store:          new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                [
                    "all",
                    lang('All')
                ],
                [
                    "Approved",
                    lang('Approved')
                ],
                [
                    "NonApproved",
                    lang('Not Approved')
                ],
                [
                    "Internal",
                    lang('Internal')
                ]
            ]
        }),
        valueField:     'id',
        displayField:   'name',
        width:          100,
        applyTo:        'filterByPublishStatus',
        listeners:      {
            'select': function(cb,record){
                toggleButtons(0);
                
                publishstatus = record.data.id;
                
                gridstore.setBaseParam('filterComents', publishstatus);
                
                gridstore.load({
                    params: {
                        start:  0,
                        limit:  gridLimit
                    }
                });
            }
        }
    });
    
    gridstore = new Ext.data.JsonStore({
        id:             "gridstore",
        root:           'responses',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        fields:         [
            'id',
            'name',
            'response',
            'username'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=support&action=getCannedResponses'
        })
    });
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        id:         'KBcomments-sm',
        width:      30,
        listeners:  {
            'rowdeselect':    function(model, rowIndex, record){
                toggleButtons();
            },
            'rowselect':      function(model, rowIndex, record){
                toggleButtons();
            }
        }
    });
    
    function renderArticleTitle(value, p, record){
        return String.format('<a href="javascript:editKBComment(\'{0}\');" style="cursor: pointer" id="{0}" >{1}</a>', record.data.id, record.data.name);
    }
    
    var gridbb = new Ext.PagingToolbar({
        id :          'KBcommentsgridpagingbar',
        pageSize:     gridLimit,
        store:        gridstore,
        //displayInfo:  true,
        //displayMsg:   lang('Displaying Knowledge Base Comments') +' {0} - {1}' + ' of ' + '{2}',
        emptyMsg:     "",
        listeners:    {
            'change': function(bb,data){
                    if(data.total == 0) { var addBy = 0;} else { var addBy = 1;}
                    from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
                    to = from+ bb.pageSize - 1;
                    if(to>data.total) to = data.total;

				document.getElementById('KBcommentsgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				document.getElementById('KBcommentslistlabel').innerHTML =  String.format(lang('Displaying Canned Responses') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
            }
        }
    });
    
    
    var expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
           'expand': function(re,response,body,index){
               
               expanderBody = "<div class='ext-expanderframe'>";
               expanderBody += "<div class='ext-expanderframe-details'>";
               expanderBody += response.data.response;
               expanderBody += "</div>";
               expanderBody += "</div>";
               body.innerHTML = expanderBody;
               
            }
        }
    });
    
    grid = new Ext.grid.GridPanel({
        id:               'KBcomments-grid',
        el:               'KBcomments-grid',
        autoHeight:       true,
        store:            gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,
        
        
        // grid columns
        columns:          [expander,
            sm,
            {
                id:         'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Name",
                width:      300,
                renderer:   renderArticleTitle,
                dataIndex:  "name"
            },
            {
                id:         'username', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Private",
                width:      100,
                dataIndex:  "username"
            }
        ],
        stripeRows:       true,
        // customize view config
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:      lang("There are currently no Knowledge Base Comments matching the search"),
            scrollOffset:   1
        },
        sm:               sm,
        plugins: expander,
        // paging bar on the bottom
        bbar:             gridbb,
        buttons:          [
            approvebutton = new Ext.Button({
                id:         'approvebutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Approve')+ "&nbsp;&nbsp;",
                disabled:   true
            }),
            deletebutton = new Ext.Button({
                id:         'deletebutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Delete')+ "&nbsp;&nbsp;",
                disabled:   true
            }),
        ],
        buttonAlign:      'left'
    });
    
    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
        
        for(x = 0; x < rows.length; x++){
           arrayofids[x] = rows[x].data.articleId;
        }
        
        return arrayofids;
    }
    
    var btnButtonActionHandler = function(button, event){
        grid.disable();
        
        var usepackageplugin = 0;
        var useregistrarplugin = 0;
        var usedeletecustomer = 0;
        
        switch(button.id){
            case "approvebutton":
                requesturl = "index.php?fuse=knowledgebase&action=KB_ApproveComments";
                
                break;
            case "deletebutton":
                requesturl = "index.php?fuse=knowledgebase&action=KB_DeleteComments";
                
                var confirmmsg = "Are you sure you want to delete the comment(s)?";
                
                var deleteClientPacks = confirm(confirmmsg);
                
                if(deleteClientPacks == false){
                    grid.enable();
                    return false;
                }
                
                break;
        }
        
        showKBcommentsWaitingMask();
        
        Ext.Ajax.request({
            url:      requesturl,
            success:  function(xhr){
                hideKBcommentsWaitingMask();
                
                //refreshgrid
                toggleButtons(0);
                
                grid.enable();
                
                gridstore.load({
                    params: {
                        start:  0,
                        limit:  gridLimit
                    }
                });
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                if(data.error){
                    //we do not need to repopulate the filters if there was a validation error
                    if(data.message){
                        msg(data.message);
                    }else{
                        msg(lang("There was an error performing this action"));
                    }
                }else{
                    if(data.message){
                        msg(data.message);
                    }else{
                        msg(lang("The action has been performed"));
                    }
                }
            },
            failure:  function(){
                hideKBcommentsWaitingMask();
                grid.enable();
                Ext.Msg.alert("Fail");
            },
            params:   {
                articleId:  Ext.util.JSON.encode(GetSelectedRowIds())
            }
        });
    }
    
    function showKBcommentsWaitingMask(){
        if(!KBcommentsWaitingMask){
            KBcommentsWaitingMask = new Ext.LoadMask('KBcomments-grid', {msg:"Please wait..."});
        }
        
        KBcommentsWaitingMask.show();
    }
    
    function hideKBcommentsWaitingMask(){
        KBcommentsWaitingMask.hide();
    }
    
    // option button code
    toggleButtons = function(count){
        if(count == undefined){
            count = sm.getCount();
        }
        
        if(count > 0){
            approvebutton.setDisabled(false);
            deletebutton.setDisabled(false);
        }else{
            approvebutton.setDisabled(true);
            deletebutton.setDisabled(true);
        }
    }
    
    function addButtonListeners(){
        approvebutton.addListener("click",btnButtonActionHandler);
        deletebutton.addListener("click",btnButtonActionHandler);
    }
    
    addButtonListeners();
    
    // render it
    grid.render();
    
    // trigger the data store load
    gridstore.load({
        params: {
            start:  0,
            limit:  gridLimit
        }
    });
});