var gridstore ;

Ext.onReady(function(){
    var deletebutton1;
    new Ext.Button({
        id:"adddepartment",
        renderTo:"adddepartment",
        text: lang('Add Department'),
        iconAlign: 'left',
        handler:function(){
            addDepartment();
        }
    });

    gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'groups',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: ""
        },
        fields: [
                'departmentId','departmentName','isGeneral' ,'lead','groupMembers','staffMembers','applicableRoutingRules','applicableEscalationRules','canEditDepartments'
        ],
        // 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=support&action=GetDepartmentList'
        })
    });
    gridstore.setDefaultSort('id', 'asc');

    /*function renderBox(value,p,record){
        //alert("dptmt="+record.data.departmentName)
        if(record.data.departmentName == "General"){
            
        }
        return ;
    }*/

    function renderName(value, p, record){
        name = record.data.departmentName;
        if(record.data.canEditDepartments){
            //name = String.format("<a href='index.php?fuse=support&view=AddEditDepartment&department={1}'>{0}</a>",record.data.departmentName,record.data.departmentId);
            name = String.format("<a onClick='editDepartment({1})'>{0}</a>",record.data.departmentName,record.data.departmentId);
        }

        return name;
    }

    var hinderSelection = false; // Create the flag

    var sm = new Ext.grid.CheckboxSelectionModel({
        //renderer : renderBox,

        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'beforerowselect' : function (sm, rowIndex, keep, rec) {
                    //var id = parseInt(rec.id);
                    if(hinderSelection) {
                        hinderSelection = false;
                        return false;
                    }

                    if (rec.data.isGeneral == 1){
                        alert("Can't erase the general department(s)");
                        return false;
                    }

              }

        }
    });

    function toggleButtons(record, count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count > 0){
            deletebutton1.setDisabled(false);
        }else{
            deletebutton1.setDisabled(true);
        }
    }

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

        // grid columns
        columns:[
        sm,
        {
            id: 'departmentId', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Id"),
			dataIndex : "departmentId",
			hidden:true,
            sortable: false,
			align:"left"
        },{
            id: 'isGeneral', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("isGeneral"),
			dataIndex : "isGeneral",
			hidden:true,
            sortable: false,
			align:"left"
        },{
            id: 'departmentName', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Department Name"),
            width: 30,
            renderer : renderName,
    		dataIndex : "departmentName",
            sortable: false
        },{
            id: 'groupMembers', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Group Members"),
            width: 45,
            dataIndex : "groupMembers",
            sortable: false
        },{
            id: 'staffMembers', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Staff Members"),
            width: 45,
            dataIndex : "staffMembers",
            sortable: false
        },{
            id: 'lead', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Lead"),
            width: 30,
            dataIndex : "lead",
            sortable: false
        },{
            id: 'applicableRoutingRules', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Routing Rules"),
            width: 30,
            align:'center',
            dataIndex : "applicableRoutingRules",
            sortable: false
        },{
            id: 'applicableEscalationRules', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Escalation Rules"),
            width: 30,
            align:'center',
            dataIndex : "applicableEscalationRules",
            sortable: false
        }
        ],
        stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no groups available to view at this time"),
	    scrollOffset:1
        },sm: sm,
        // inline buttons
        buttons:[deletebutton1 = new Ext.Button({
                     id:'deletebutton1',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Delete'),
                     disabled: true
                 })],
        buttonAlign:'left',
        listeners: {
        rowmousedown: function() {
            hinderSelection = true;
        }
    }


    });

    var btnButtonActionHandler = function(button, event){
        requesturl = "index.php?fuse=support&action=DeleteDepartment";
        var confirmDelete = "";
        var confirmmsg = lang("Do you want to delete the selected department(s)? (Ok=YES , Cancel=No)");
        if(!confirm(confirmmsg)){
            return true;
        }
        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                grid.enable()
                gridstore.load({params:{start:0}});
                toggleButtons(0, 0);
		var data = ce.parseAjaxResponse(xhr);
           },
           failure: function() {
                grid.enable()
                Ext.Msg.alert("Fail");
           },
           params: { departmentIds : Ext.util.JSON.encode(getDepartmentIds())
           }
        });
    }
    function addButtonListeners(){
        deletebutton1.addListener("click",btnButtonActionHandler);
    }

    function getDepartmentIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
        for(x=0;x<rows.length;x++){
            arrayofids[x] = rows[x].data.departmentId;
        }
        return arrayofids;
    }
    addButtonListeners();

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

});