Ext.onReady(function(){
    
    if(document.getElementById('addroutingrulebutton') != null){
            new Ext.Button({
                id:"addroutingrule",
                renderTo:"addroutingrulebutton",
                text: lang('Add Routing Rule'),
                iconAlign: 'left',
                handler:function(){
                    addRoutingRule();
                }
            });
    }

    if(document.getElementById('addroutingfilterbutton') != null){
            new Ext.Button({
                id:"addroutingfilter",
                renderTo:"addroutingfilterbutton",
                text: lang('Add Filter'),
                iconAlign: 'left',
                handler:function(){                     
                    routingfilter.addRoutingFilter();
                }
            });
    }
    
    var gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'groups',
            totalProperty: 'totalcount',
            idProperty: 'routingId',
            remoteSort: true,
            baseParams: {
            filter: ""
        },
        fields: [
                'routingId','routingName', 'routingEmails','routingUserType','routingAutoresponder','routingCreateTicket','routingType'
        ],
        // 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=GetSupportRoutings'
        })
    });
    gridstore.setDefaultSort('id', 'asc');
    function renderName(value, p, record){
        name = record.data.routingName;
        if(gridstore.reader.jsonData.canEditRoutings){
            //name = String.format("<a href='index.php?fuse=support&view=AddEditEmailRouting&routing={1}'>{0}</a>",record.data.routingName,record.data.routingId);
            name = '<a href="javascript:editRoutingRule(' + record.data.routingId + ');" id="' + record.data.routingId + '" class="editroutingrule" qtip="' + lang('Click to edit this routing rule') + '">' + record.data.routingName + '</a>';
        }
        return name;
    }    

    var expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
           'expand': function(re,response,body,index){
               expanderBody = "<div class='ext-expanderframe'>";
               expanderBody += "<div class='ext-expanderframe-details'>";
               expanderBody += "<b>Creates Ticket</b>: "+ response.data.routingCreateTicket+" <span class='ext-expanderframe-delim'>•</span> <b>Source</b>: "+response.data.routingType;
               expanderBody += "<br/><b>Users Affected</b>: " + response.data.routingUserType;
               expanderBody += "<br/><b>Routing E-mails</b>: " + response.data.routingEmails;
               expanderBody += "</div>";
               expanderBody += "</div>";
               body.innerHTML = expanderBody;
               
            }
        }
    });


    var grid = new Ext.grid.GridPanel({
        id: 'supportrouting-grid',
        el: 'supportrouting-grid',
        autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        // *************** Commented for Drag N Drop ****************************
        //disableSelection:true,
        // *************** Commented for Drag N Drop ****************************
        loadMask: true,

        // grid columns
        columns:[expander,{
            id: 'routingId', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Id"),
			dataIndex : "routingId",
			hidden:true,
            sortable: false,
			align:"left"
        },{
            id: 'routingName', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Name"),
            width: 100,
            renderer : renderName,
    		dataIndex : "routingName",
            sortable: false
        },{
            id: 'routingAutoresponder', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Autoresponder"),
            width: 30,
            align: 'center',
            dataIndex : "routingAutoresponder",
            sortable: false
        }
        ],
        // ******DND**************
        enableDragDrop    : true,
        ddGroup     : 'myGridDD',
        dragConfig : {
            containerScroll : true
        },
        plugins: expander,
        // ******DND**************
		stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no groups available to view at this time"),
            scrollOffset:1
        }
    });

    // ******************************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=UpdateEmailRoutingRulesOrder',
                method: 'POST',
                success: function(xhr) {
                },
                failure: function() { },
                params: {routingRules: 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('routingId');

        }
	    return arrayofids;
    }
// ******************************CODE for Drag N Drop*******************************************



    // render it
    grid.render();
    gridstore.on('load',function(){

       var notice = document.getElementById('notice');
       var noticeOrder = document.getElementById('noticeOrder');
       var noGuestsEmailRulesWarning = document.getElementById('noGuestsEmailRulesWarning');
       var noPublicSectionRulesWarning = document.getElementById('noPublicSectionRulesWarning');

       if(gridstore.reader.jsonData.noGuestsEmailRulesWarning){
          noGuestsEmailRulesWarning.style.display = "block";
       }else{
           noGuestsEmailRulesWarning.style.display = "none";
       }
       if(gridstore.reader.jsonData.noPublicSectionRulesWarning){
            noPublicSectionRulesWarning.style.display = "block";
       }else{
            noPublicSectionRulesWarning.style.display = "none";
       }
       if(gridstore.reader.jsonData.support_edit_emailroutings){
            noticeOrder.style.display = "block";
       }else{
            noticeOrder.style.display = "none";
       }
       if(gridstore.reader.jsonData.notice){
            notice.style.display = "block";
       }else{
            notice.style.display = "none";
       }

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

});
