Ext.onReady(function(){

    gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'groups',
            totalProperty: 'totalcount',
            idProperty: 'ticketTypeId',
            remoteSort: true,
            baseParams: {
            filter: ""

        },
        fields: [
                'ticketTypeId','ticketTypeName', 'ticketTypeDescription','ticketTypeEnabled','ticketTypeDefaultAssignee','numTickets','canEditTicketTypes','canDeleteTicketType'
        ],
        // 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=GetTicketTypeList'
        })
    });
    gridstore.setDefaultSort('id', 'asc');
    function renderName(value, p, record){
        name = record.data.ticketTypeName;
        if(gridstore.reader.jsonData.canEditTicketTypes){
            name = '<a href="javascript:editTicketType('+record.data.ticketTypeId+','+record.data.canDeleteTicketType+');" id="'+record.data.ticketTypeId+'" class="editbillingtype" qtip="'+lang('Click to edit this ticket type')+'">'+record.data.ticketTypeName+'</a>';
        }

        return name;
    }

    /*var sm = new Ext.grid.CheckboxSelectionModel({
        id:'tickettype-sm',
        width: 30,
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });*/
    
    var grid = new Ext.grid.GridPanel({
        id:'tickettype-grid',
        el:'tickettype-grid',
        autoHeight:true,
        store: gridstore,
        /*trackMouseOver:true,
        disableSelection:true,*/
        loadMask: true,  
        

        // grid columns
        columns:[/*sm,*/{
            id: 'ticketTypeId', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Id"),
			dataIndex : "ticketTypeId",
			hidden:true,
            sortable: false,
			align:"left"
        },{
            id: 'ticketTypeName', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Name"),
            width: 35,
            renderer : renderName,
    		dataIndex : "ticketTypeName",
            sortable: false
        },{
            id: 'ticketTypeDescription', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Description"),
            width: 90,
    		dataIndex : "ticketTypeDescription",
            sortable: false
        },{
            id: 'ticketTypeDefaultAssignee', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Default Assignee"),
            width: 35,
    		dataIndex : "ticketTypeDefaultAssignee",
            sortable: false
        },{
            id: 'ticketTypeEnabled', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Enabled"),
            width: 35,
            dataIndex : "ticketTypeEnabled",
            sortable: false
        },{
            id: 'numTickets', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Tickets"),
            width: 40,
            dataIndex : "numTickets",
            sortable: false
        }
        ],
        enableDragDrop    : true,
        ddGroup     : 'myGridDD',
        dragConfig : {
            containerScroll : true

        },
	stripeRows: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no groups available to view at this time"),
	    scrollOffset:1
        }

    });
    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count>0){
            deletebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
        }
    }

    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
	    for(x=0;x<rows.length;x++){
	       arrayofids[x] = rows[x].data.ticketTypeId;
	    }
	    return arrayofids;
    }
//******************************CODE for Drag N Drop*******************************************
// This will make sure we only drop to the view container

    var dropTargetCfg = {

        ddGroup         : 'myGridDD',
        onContainerOver : function(ddSrc, evtObj, ddData) {
            var grid        = ddSrc.view.grid;
            var targetDiv   = evtObj.getTarget();
            var targetIndex = grid.getView().findRowIndex(targetDiv);
            this.clearDDStyles(ddSrc);
            
            // is this a row?
            if (targetIndex !== false) {
                var targetRow        = grid.getView().getRow(targetIndex);
                var targetRowEl      = Ext.get(targetRow);
                var targetRowHeight  = targetRowEl.getHeight();
                var targetRowTop     = targetRowEl.getY();
                var targetRowCtr     = targetRowTop + Math.floor(targetRowHeight / 2);
                var mouseY           = evtObj.getXY()[1];

                // below
                if (mouseY >= targetRowCtr) {
                    this.point = 'below';
                    targetRowEl.addClass('gridRowInsertBottomLine');
                    targetRowEl.removeClass('gridRowInsertTopLine');
                }
                // above
                else if (mouseY < targetRowCtr) {
                    this.point = 'above';
                    targetRowEl.addClass('gridRowInsertTopLine');
                    targetRowEl.removeClass('gridRowInsertBottomLine')
                }
                this.overRow = targetRowEl;
//                this.targetIndex = targetIndex;
            }
            else if (targetIndex === false) {
                targetIndex =  grid.store.getCount();
            }
            this.targetIndex = targetIndex;

            grid.body.addClass('gridBodyNotifyOver');

            return 'x-dd-drop-ok';
        },
        notifyOut : function(ddSrc) {
            var grid        = ddSrc.view.grid;
            grid.body.removeClass('gridBodyNotifyOver');
            this.clearDDStyles(ddSrc);
            delete this.point;
            delete this.targetIndex;
            return true;
        },
        clearDDStyles : function(ddSrc) {
            var grid        = ddSrc.view.grid;
            if (this.overRow) {
                this.overRow.removeClass('gridRowInsertBottomLine');
                this.overRow.removeClass('gridRowInsertTopLine');
            }
            grid.body.removeClass('gridBodyNotifyOver');
        },
        notifyDrop  : function(ddSrc, evtObj, ddData){
            var grid        = ddSrc.view.grid;
            var store       = grid.store;
            var records     = ddSrc.dragData.selections;
            var origIndex   = store.indexOf(records[0]);
            var targetIndex = this.targetIndex;

            if (typeof targetIndex === 'boolean' && targetIndex === false) {
                targetIndex = store.getCount();
            }

            Ext.each(records, store.remove, store);

            if (origIndex < targetIndex && this.point == 'above') {
                targetIndex--;
            }
            else if (origIndex > targetIndex && this.point == 'below') {
                targetIndex++;
            }

            if (targetIndex > store.getCount()) {
                targetIndex = store.getCount();
            }

            store.insert(targetIndex, records);

            this.clearDDStyles(ddSrc);
            Ext.Ajax.request({
                url: 'index.php?fuse=support&action=UpdateTicketTypesOrder',
                method: 'POST',
                success: function(xhr) {
                },
                failure: function() {
                     alert("fail");
                },
                params: { ids: Ext.util.JSON.encode(getRowIds())
                }
            
            });

            return true;
        }
    };
    var leftGridDropTarget   = new Ext.dd.DropZone(grid.el, dropTargetCfg);

    function getRowIds(){
        
        var arrayofids = new Array();
        for(x=0;x<gridstore.getCount();x++){
            arrayofids[x] = gridstore.getAt(x).get('ticketTypeId');
            
        }
	    return arrayofids;
    }

//******************************CODE for Drag N Drop*******************************************

    function ProcessAction(requesturl){
	    grid.disable();

	   Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                grid.enable()
                gridstore.load({params:{start:0}});
                toggleButtons(0);

                var data = Ext.util.JSON.decode(xhr.responseText);
                if(data.message){
                    msg(data.message,"");
                }else{
                    msg(lang("Ticket Type(s) have been updated"),"");
                }
           },
           failure: function() {
                grid.enable()
                msg(lang("There was an error performing this action"),"");
           },
           params: {
            ids: Ext.util.JSON.encode(GetSelectedRowIds())
            }
        });
    }

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

    gridstore.on('load',function(){        
        var noticeOrder = document.getElementById('noticeOrder');
        if(gridstore.reader.jsonData.canEditTicketTypes){
            noticeOrder.style.display = "block";
       }else{
            noticeOrder.style.display = "none";
       }
    });
});