var gridstore = '';
var showstaffmemberspics = 0;

Ext.onReady(function(){

    gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'groups',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
        fields: [
                'id','groupname', 'description', 'staffmembers'
        ],
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=home&action=GetFollowGroupsList'
        })
    });
    gridstore.setDefaultSort('name', 'asc');

    var sm = new Ext.grid.CheckboxSelectionModel({
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });

    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }

        if(count > 0){
            followgroups.setDisabled(false);
            unfollowgroups.setDisabled(false);
        }else{
            followgroups.setDisabled(true);
            unfollowgroups.setDisabled(true);
        }
    }

    function getSelectedItems(){
        //var arrayofids = new Array();
        var selectedItems = "";
        rows = sm.getSelections();
        //var i = 0;
        for(x=0;x<rows.length;x++){
            var commavar = ",";
            if(x !=0){
               selectedItems += commavar;
            }
            selectedItems += rows[x].data.id;
          //  i++;
        }
        return selectedItems;
    }

    var expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
            'expand': function(re,response,body,index){
                body.innerHTML = '<div style="padding-top: 10px; padding-left: 10px; padding-bottom: 10px; padding-right: 10px">' + response.data.staffmembers + '</div>';
            }
        }
    });

    var grid = new Ext.grid.GridPanel({
        el:'accessgroup-grid',
        autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,

        // grid columns
        columns:[
            expander,
            sm,
            {
                id: 'groupname', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header: lang("Group"),
                dataIndex : "groupname",
                sortable: false
            },{
                id: 'description', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header: lang("Following"),
                width: 20,
                dataIndex : "description",
                sortable: false
            }
        ],
        sm: sm,
        stripeRows: true,
        plugins: expander,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no groups available to view at this time"),
            scrollOffset:1
        },
        buttons:[
            followgroups = new Ext.Button({
                id:'followgroups',
                autoHeight:true,
                arrowAlign:'right',
                xtype:'splitbutton',
                text:lang('Follow'),
                disabled: true,
                handler:  function(){
                    updateFollowGroup(1);
                }
            }),
            unfollowgroups = new Ext.Button({
                id:'unfollowgroups',
                autoHeight:true,
                arrowAlign:'right',
                xtype:'splitbutton',
                text:lang('Unfollow'),
                disabled: true,
                handler:  function(){
                    updateFollowGroup(0);
                }
            })
        ]
    });

    gridstore.on('load',function(){
        toggleButtons(0);
    });

    function updateFollowGroup(follow)
    {
        var requesturl = "index.php?fuse=home&action=UpdateFollowGroup";
        Ext.Ajax.request({
            url: requesturl,
            success: function(xhr) {
                //refreshgrid
                gridstore.load({params:{showpics:showstaffmemberspics}});
            },
            failure: function() {
                Ext.Msg.alert("Fail");
            },
            params: { groupids: Ext.util.JSON.encode(getSelectedItems()),
                      follow: Ext.util.JSON.encode(follow)
            }
        });
    }

    // render it
    grid.render();
    gridstore.load({params:{showpics:showstaffmemberspics}});
});

function staffmemberspics(showpics){
    if(showpics.checked){
        showstaffmemberspics = 1;
    }else{
        showstaffmemberspics = 0;
    }
    gridstore.load({params:{showpics:showstaffmemberspics}});
}

