Ext.onReady(function(){
    teamstatus.showstaffmemberspics = 0;
	teamstatus.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'
	})
	});
	teamstatus.gridstore.setDefaultSort('name', 'asc');
	teamstatus.gridstore.load();
	
	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({
	autoHeight:true,
	store: teamstatus.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,
	    scrollOffset:1,
            emptyText: lang("There are no groups available to view at this time")
	},
	buttons:[
	    followgroups = new Ext.Button({
	        id:'followgroups',
	        autoHeight:true,
	        arrowAlign:'right',
	        xtype:'splitbutton',
	        text:lang('Follow'),
	        disabled: true,
	        handler:  function(){
	            teamstatus.updateFollowGroup(1);
	        }
	    }),
	    unfollowgroups = new Ext.Button({
	        id:'unfollowgroups',
	        autoHeight:true,
	        arrowAlign:'right',
	        xtype:'splitbutton',
	        text:lang('Unfollow'),
	        disabled: true,
	        handler:  function(){
	            teamstatus.updateFollowGroup(0);
	        }
	    })
	]
	});
	
	teamstatus.updateFollowGroup = function(follow)
	{
        var requesturl = "index.php?fuse=home&action=UpdateFollowGroup";
        Ext.Ajax.request({
            url: requesturl,
            success: function(xhr) {
                //refreshgrid
                teamstatus.gridstore.load({params:{showpics:teamstatus.showstaffmemberspics}});
            },
            failure: function() {
                Ext.Msg.alert("Fail");
            },
            params: {groupids: Ext.util.JSON.encode(getSelectedItems()),
                      follow: Ext.util.JSON.encode(follow)
            }
        });
	}
    
    teamstatus.pluginteamconfigwindow = new Ext.FormPanel({
        labelAlign:'top',
        border: false,
        autoHeight:true,
        items:[grid],
        bodyStyle:'background:transparent;padding-top:10px;padding-left:10px;'
    });
    
    teamstatus.postinchatroom = new Ext.FormPanel({
        labelAlign:'top',
        border: false,
        autoHeight:true,
        items:[{
            layout:'column',
            border: false,
            items:[{
                columnWidth:.5,
                layout: 'form',
                border: false,
                items: [
                 new Ext.form.ComboBox({
                    id: 'postinchatroom',
                    fieldLabel: lang('Post status msg in external chat room'),
                    triggerAction:    'all',
                    editable:         false,
                    width: 220,
                    store:new Ext.data.ArrayStore({
                        idIndex:  0,
                        fields:   [ 'id', 'name' ],
                        data:     [[ 0,lang('None')],[1,'Campfire'],[2,'HipChat'],[3,'Jaconda.im']]
                    }),
                    valueField:       'id',
                    displayField:     'name',
                    value:            0,
                    mode: 'local',
                    lazyRender:       true,
                    listeners : {
                        'select' : function(cb){
                            //hide all panels and buttons
                            teamstatus.cfsettings.setVisible(false);
                            teamstatus.hipchatsettings.setVisible(false);
                            teamstatus.jacondasettings.setVisible(false);
                            var val = cb.getValue();
                            if (val == 0) {
                                Ext.getCmp('toggle_ts_settings').setVisible(false);
                            } else {
                                Ext.getCmp('toggle_ts_settings').setVisible(true);
                            }
                            Ext.Ajax.request({
                                url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=teamstatus&pluginAction=SaveAPIProvider',
                                success: function(xhr) {
                                    json = ce.parseAjaxResponse(xhr);
                                    //clear out all fields
                                    Ext.getCmp('cfURL').setRawValue('');
                                    Ext.getCmp('cftoken').setRawValue('');
                                    Ext.getCmp('cfroomid').setRawValue('');
                                    Ext.getCmp('hctoken').setRawValue('');
                                    Ext.getCmp('hcroomname').setRawValue('');
                                    Ext.getCmp('jatoken').setRawValue('');
                                    Ext.getCmp('jaroomname').setRawValue('');
                                },
                                params: {providerid: val}
                            });
                        }
                    }
                })]
            },{
                id: 'updatecontainer',
                columnWidth:.5,
                layout: 'form',
                border: false,
                items: [
                  new Ext.Button({
                    id: 'toggle_ts_settings',
                    hidden: true,
                    text: lang('Toggle') + ' ' + lang('Settings'),
                    listeners : {
                        'click' : function() {
                            //getvalue of combo
                            var val = Ext.getCmp('postinchatroom').getValue();                            
                            if (val == 1) {
                                teamstatus.hipchatsettings.setVisible(false);
                                teamstatus.jacondasettings.setVisible(false);
                                if (teamstatus.cfsettings.isVisible()) {
                                    teamstatus.cfsettings.setVisible(false);
                                } else {
                                    teamstatus.cfsettings.setVisible(true);
                                }
                            } else if (val == 2) {
                                teamstatus.cfsettings.setVisible(false);
                                teamstatus.jacondasettings.setVisible(false);
                                if(teamstatus.hipchatsettings.isVisible()) {
                                    teamstatus.hipchatsettings.setVisible(false);
                                } else {
                                    teamstatus.hipchatsettings.setVisible(true);
                                }
                            } else if (val == 3) {
                                teamstatus.hipchatsettings.setVisible(false);
                                teamstatus.cfsettings.setVisible(false);
                                if(teamstatus.jacondasettings.isVisible()) {
                                    teamstatus.jacondasettings.setVisible(false);
                                } else {
                                    teamstatus.jacondasettings.setVisible(true);
                                }
                            }
                        }
                    }
                })
                ]
            }
        ]
        }],
        bodyStyle:'background:transparent;padding-top:10px;padding-left:10px;'
    });
    
    teamstatus.hipchatsettings = new Ext.FormPanel({
        hidden:true,
        labelAlign:'left',
        border: false,
        autoHeight:true,
        items:[
            new Ext.form.TextField({
                 id: 'hctoken',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('Token'),
                 width: 300
             }),
             new Ext.form.TextField({
                 id: 'hcroomname',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('Room')
             }),
             new Ext.Button({
                id: 'updateteamstatushc',
                text: lang('Update'),
                listeners: {
                    'click' : function(){
                        Ext.Ajax.request({
                            url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=teamstatus&pluginAction=SaveAPISettings',
                            success: function(xhr) {
                                json = ce.parseAjaxResponse(xhr);
                                teamstatus.hipchatsettings.setVisible(false);
                            },
                            params: {token: Ext.getCmp('hctoken').getValue(), room: Ext.getCmp('hcroomname').getValue()}
                        });
                    }
                }
            })
        ],
        bodyStyle:'background:transparent;padding-top:2px;padding-left:10px;'
    });
    
    teamstatus.jacondasettings = new Ext.FormPanel({
        hidden:true,
        labelAlign:'left',
        border: false,
        autoHeight:true,
        items:[
            new Ext.form.TextField({
                 id: 'jatoken',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('Token'),
                 width: 300
             }),
             new Ext.form.TextField({
                 id: 'jaroomname',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('Room Id')
             }),
             new Ext.Button({
                id: 'updateteamstatusja',
                text: lang('Update'),
                listeners: {
                    'click' : function(){
                        Ext.Ajax.request({
                            url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=teamstatus&pluginAction=SaveAPISettings',
                            success: function(xhr) {
                                json = ce.parseAjaxResponse(xhr);
                                teamstatus.jacondasettings.setVisible(false);
                            },
                            params: {token: Ext.getCmp('jatoken').getValue(), room: Ext.getCmp('jaroomname').getValue()}
                        });
                    }
                }
            })
        ],
        bodyStyle:'background:transparent;padding-top:2px;padding-left:10px;'
    });
    
    teamstatus.cfsettings = new Ext.FormPanel({
        hidden:true,
        labelAlign:'left',
        border: false,
        autoHeight:true,
        items:[
            new Ext.form.TextField({
                 id: 'cfURL',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('URL'),
                 width: 300
             }),
            new Ext.form.TextField({
                 id: 'cftoken',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('Token'),
                 width: 300
             }),
             new Ext.form.TextField({
                 id: 'cfroomid',
                 labelStyle: 'width:60px;',
                 fieldLabel: lang('Room Id')
             }),
             new Ext.Button({
                id: 'updateteamstatuscf',
                text: lang('Update'),
                listeners: {
                    'click' : function(){
                        Ext.Ajax.request({
                            url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=teamstatus&pluginAction=SaveAPISettings',
                            success: function(xhr) {
                                json = ce.parseAjaxResponse(xhr);
                                teamstatus.cfsettings.setVisible(false);
                            },
                            params: {url: Ext.getCmp('cfURL').getValue(), token: Ext.getCmp('cftoken').getValue(), room: Ext.getCmp('cfroomid').getValue()}
                        });
                    }
                }
            })
        ],
        bodyStyle:'background:transparent;padding-top:2px;padding-left:10px;'
    });
    
    teamstatus.createWindow = function(){
        teamstatus.win = new Ext.Window({
            title:"Team Status Configuration",
            layout:'fit',
            width:550,
            shadow:false,
            autoHeight:true,
            modal:true,
            plain: true,
            items: [teamstatus.postinchatroom,
                teamstatus.hipchatsettings,
                teamstatus.cfsettings,
                teamstatus.jacondasettings,
                teamstatus.pluginteamconfigwindow]
        });
        teamstatus.pluginteamconfigwindow.getForm().reset();
        teamstatus.win.show(this);
        $('#x-form-el-cftoken').css('paddingLeft','0px');
        $('#x-form-el-cfURL').css('paddingLeft','0px');
        $('#x-form-el-cfroomid').css('paddingLeft','0px');
        $('#x-form-el-hcroomname').css('paddingLeft','0px');
        $('#x-form-el-hctoken').css('paddingLeft','0px');
        $('#updatecontainer').css("left","-33px");
        $('#updatecontainer').css("position","relative");
        $('#updatecontainer').css("top","17px");
        
        //need to populate the window with valid data
        Ext.Ajax.request({
            url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=teamstatus&pluginAction=GetAPISettings',
            success: function(xhr) {
                json = ce.parseAjaxResponse(xhr);
                if (json.data.apiprovider == 1) {
                    Ext.getCmp('toggle_ts_settings').setVisible(true);
                    Ext.getCmp('cfURL').setRawValue(json.data.vars.url);
                    Ext.getCmp('cftoken').setRawValue(json.data.vars.token);
                    Ext.getCmp('cfroomid').setRawValue(json.data.vars.room);
                } else if(json.data.apiprovider == 2) {
                    Ext.getCmp('toggle_ts_settings').setVisible(true);
                    Ext.getCmp('hctoken').setRawValue(json.data.vars.token);
                    Ext.getCmp('hcroomname').setRawValue(json.data.vars.room);
                } else if(json.data.apiprovider == 3) {
                    Ext.getCmp('toggle_ts_settings').setVisible(true);
                    Ext.getCmp('jatoken').setRawValue(json.data.vars.token);
                    Ext.getCmp('jaroomname').setRawValue(json.data.vars.room);
                }
                Ext.getCmp('postinchatroom').setValue(json.data.apiprovider);
            }
        });
        
    }

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