Ext.onReady(function(){
    var win;
    var gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'groups',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
        fields: [
                'id','groupname', 'description'
        ],
        // 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=admin&action=GetAccessGroupList'
        })
    });
    gridstore.setDefaultSort('id', 'asc');
    gridstore.on('load',function(store,records,options){
        toggleButtons(0);
    });

    function renderName(value, p, record){

        name = record.data.groupname;
        if (record.data.id == 1 || record.data.id == 2) {
            name = "<span style='font-weight:bold;'>"+name+"</span>";
        }

        if(record.data.id != 2){
            name = String.format("<a href='index.php?fuse=admin&view=AddEditGeneralGroup&group={1}'>{0}</a>",name,record.data.id);
        }
        
        return name;
    }

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

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

        // grid columns
        columns:[
            sm,
            {
            id: 'id', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Id"),
            width: 50,
            dataIndex : "id",
            hidden:true,
            sortable: false,
            align:"left"
        },{
            id: 'groupname', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Role"),
            width: 20,
            renderer : renderName,
            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("Description"),
            dataIndex : "description",
            sortable: false
        }],
        sm:sm,
        stripeRows: true,
        // customize view config
                
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no groups available to view at this time"),
            scrollOffset:1
        },
        buttonAlign:'left',
        buttons:[ deletebutton = new Ext.Button({
                     id:'deletebutton',
                     autoHeight:true,
                     xtype:'button',
                     text:lang('Delete'),
                     disabled: true,
                     hidden: false
                 })]

    });

    var btnButtonActionHandler = function(button, event){
        grid.disable();
        requesturl = "index.php?fuse=admin&action=Admin_DeleteGeneralGroup";
        if(button.id == "delete"){
            var confirmmsg = lang("Click OK if you are sure you want to delete this group.");
            var deleteItems = confirm(confirmmsg);
            if(deleteItems == false){
                grid.enable();
                return false;
            }
        }

        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                grid.enable();
                gridstore.load({params:{start:0}});
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                if(data.message){
                    msg(data.message);
                }else if(data.error){
                    //we do not need to repopulate the filters if there was a validation error
                   msg(lang("There was an error performing this action"));
                }else{
                    msg(lang("Invoice(s) have been updated"));
                }
            },
           failure: function() {
                grid.enable();
                Ext.Msg.alert("Fail");
           },
           params: {ids: getItems(),
                     actionbutton: Ext.util.JSON.encode(button.id)
            }
        });
    }
    deletebutton.addListener("click",btnButtonActionHandler);

    // render it
    grid.render();
    gridstore.setBaseParam('limit', 50);
    gridstore.load({params:{start:0}});

    var addstaffgroup = new Ext.Button({
        id:"addstaffgroup",
        renderTo:"addstaffgroupbutton",
        text: lang('Add Role'),
        iconAlign: 'left',
        handler:function(){
             createWindow();
        }

    });



    var simpleForm = new Ext.FormPanel({
        labelWidth: 75, // label settings here cascade unless overridden
        frame:true,
        border:false,
        hideBorders:true,
        bodyStyle:'padding:8px 15px 0',
        width: 350,
        defaults: {width: 230},
        defaultType: 'textfield',

        items: [{
                fieldLabel: 'Id',
                name: 'groupId',
                xtype: "hidden"
            },{
                fieldLabel: lang('Group Name'),
                type: 'textfield',
                name: 'groupName',
                allowBlank:false
            },{
                xtype:"textarea",
                name:"groupDescription",
                fieldLabel: lang('Description')
            }
            ]
    });



    function createWindow(update){
        if(update){
            requesturl = 'index.php?fuse=clients&action=Admin_UpdateProfileAccounts';
            buttonText = 'Update';
            titleText = '&nbsp;&nbsp;'+lang('Edit Customer Group');
        }else{
            requesturl = 'index.php?fuse=admin&action=Admin_AddGeneralGroup';
            buttonText = 'Save';
            titleText = '&nbsp;&nbsp;'+lang('Add Customer Group');
        }

        // create the window on the first click and reuse on subsequent clicks
        //if(!win){
            win = new Ext.Window({
                layout:'fit',
                title:titleText,
                width:380,
                height:220,
                modal:true,
                closeAction:'hide',
                plain: true,
                items: [simpleForm],
                buttons: [
                    {
                    text: 'Close',
                    handler: function(){
                        win.hide();
                    }
                }]
            });

            // simple button save (update)
            win.addButton(buttonText, function(){
                simpleForm.getForm().submit({
                    clientValidation: true,
                    url: requesturl,
                    success: function(form, action) {
                       win.hide();
                       gridstore.load({params:{start:0}});
                    },
                    failure: function(form, action) {
                        switch (action.failureType) {
                            case Ext.form.Action.CLIENT_INVALID:
                                Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                break;
                            case Ext.form.Action.CONNECT_FAILURE:
                                Ext.Msg.alert('Failure', 'Ajax communication failed');
                                break;
                            case Ext.form.Action.SERVER_INVALID:
                               Ext.Msg.alert('Failure', action.result.message);
                       }
                    }

                });
            });
        //}else{
            simpleForm.getForm().reset();
        //}

        win.show(this);
    }

    // option button code
    function toggleButtons(count){
        if(count == undefined){
                count = sm.getCount();
        }
        
        //get the deletebutton if there is one
        //if we are in the currency view
        //if not then skip
        deletebutton = Ext.getCmp("deletebutton");

        if(count>0){
            if(deletebutton!=null){
                deletebutton.setDisabled(false);
            }
        }else{
            if(deletebutton!=null){
                deletebutton.setDisabled(true);
            }
        }
            
    }


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


});