/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
var gridstore;
var intervalid = 0;
var intervalRate = 0;

// This is here to fix a bug with the checkboxes, clearing the selection does not clear the checkbox in the header.
// Please leave it here as it enables us to upgrade extJS library without having to keep re-adding code.
Ext.override(Ext.grid.CheckboxSelectionModel, {
     clearSelections : Ext.grid.CheckboxSelectionModel.prototype.clearSelections.createSequence(function(fast){
     var hdCheckbox = this.grid.getEl().select('.x-grid3-hd-checker-on');
          if(hdCheckbox) hdCheckbox.removeClass('x-grid3-hd-checker-on');
      })
});


function SearchTroubleTickets() {
    filtertext = Ext.get('ticketsearchinput').getValue();
    searchtype = Ext.getCmp('searchtype').getValue();
    if (trim(filtertext) == ""){
        gridstore.setBaseParam('filter', 'open');
    } else if(document.getElementById("includeclosed").checked){
        gridstore.setBaseParam('filter', 'searchclosed');
    }else{
        gridstore.setBaseParam('filter', 'searchopen');
    }

    gridstore.setBaseParam('searchtype', searchtype);

    if (trim(filtertext) == ""){
        document.getElementById('ticketlisttablelabel').innerHTML = lang("Viewing All Open Tickets");
    } else {
        gridstore.setBaseParam('query', filtertext);
        document.getElementById('ticketlisttablelabel').innerHTML = lang("Searching") + "&nbsp;" + Ext.get('ticketsearchinput').getValue();
    }
    gridstore.load({params:{start:0}});
}

//Lets move this a new common.js 
Ext.onReady(function(){
    ViewTickets()
});

/*
 * Class for saving grid state. Modeled on LayoutStateManager
 */
Ext.grid.GridStateManager = function(){
     // default empty state
     this.state = {
        hidden: { },
        locked: { },
        widths: { }
    };
};

Ext.grid.GridStateManager.prototype = {
    init : function(grid, provider){
        this.provider = provider;
        this.grid = grid;
        var state = columnsavedstate;
        if(state) {
            state.hidden = state.hidden || { };
            for (var colId in state.hidden) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setHidden(colIndex, state.hidden[colId]);
              }
            }
            state.locked = state.locked || { };
            for (var colId in state.locked) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setLocked(colIndex, state.locked[colId]);
              }
            }
            state.widths = state.widths || { };
            for (var colId in state.widths) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setColumnWidth(colIndex, state.widths[colId]);
              }
            }
            if (state.sortInfo) {
              //this.grid.getDataSource().setDefaultSort(state.sortInfo.field, state.sortInfo.direction);
            }
            if (state.colIds) {
              for (var i = 0; i < state.colIds.length; i++) {
                var savedColId = state.colIds[i];
                var initialColIndex = this.grid.getColumnModel().getIndexById(savedColId);
                if (!isNaN(initialColIndex) && initialColIndex > 0 && initialColIndex != i) {
                  this.grid.getColumnModel().moveColumn(initialColIndex, i);
                }
              }
            }
            this.state = state;
        }
        grid.getColumnModel().on("hiddenchange", this.onHiddenChange, this);
        // for some reason the widthchange event on ColumnModel always gives width = undefined
        // so have to list to the event on the grid directly
        grid.on("columnresize", this.onColumnResize, this);
        grid.getColumnModel().on("columnlockchange", this.onLockChange, this);
        grid.getColumnModel().on("columnmoved", this.onColumnMove, this);
        //grid.getDataSource().on("datachanged", this.onSort, this);
    },
    getStateKey : function() {
      return this.grid.id + "-grid-state";
    },
    storeState : function(){

        // Upadat the local var
        columnsavedstate = this.state;

        // Post it
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: {gridcustomfield: 'SupportTicketGridState',
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(this.state)
                     },
           method:'post'
        });
    },
    onHiddenChange : function(cm, colIndex, hidden){
        var colId = cm.getColumnId(colIndex);
        this.state.hidden[colId] = hidden;
        this.storeState();
    },
    onColumnResize : function(colIndex, width){
        var colId = this.grid.getColumnModel().getColumnId(colIndex);
        this.state.widths[colId] = width;
        this.storeState();
    },
    onLockChange : function(cm, colIndex, lockState){
        var colId = cm.getColumnId(colIndex);
        this.state.locked[colId] = lockState;
        this.storeState();
    },
    onColumnMove : function(cm, oldIndex, newIndex){
        // we do this one by saving array of current order of column ids
        var colIds = [];
        for(var i = 0; i < cm.getColumnCount(); i++){
            colIds.push(cm.getColumnId(i));
        }
        this.state.colIds = colIds;
        this.storeState();
    },
    onSort : function(dataSource){
        if (dataSource.sortInfo) {
          this.state.sortInfo = {field: dataSource.sortInfo.field, direction: dataSource.sortInfo.direction}
          this.storeState();
        }
    }
};

/*
 * @enhancements
 * Add method to Grid to restore state.
 */
Ext.apply(Ext.grid.GridPanel.prototype, {
  restoreState: function (provider) {
    if (!provider) {
      provider = Ext.state.Manager;
    }
    var sm = new Ext.grid.GridStateManager();
    sm.init(this, provider);
  }
});

var ViewTicketsInvoked = false;

function ViewTickets() {

    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    // Prevent this from being called 
    if (document.getElementById('tickets-grid') == null
      || ViewTicketsInvoked){
        return;
    }
    
    Ext.QuickTips.init();
    gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'tickets',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0",
            searchtype: "0"
        },
        fields: [
                'id','usergroupcolor','usergroupname','submittedby','timeelapsedinminutes','assignedtofull',
                'isguest','priority','tag', 'subject','hasAttachment','messagetype','messagetypename','datesubmitted',
                'datesubmittedclean','status','statusname','userid','assignedtoid','assignedtodeptid',
                'userstatus','assignedtoname','timeelapsed', 'method', 'method_tooltip'
        ],
        // 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=getTicketList'
        }),
        listeners:{
         'load': function(){
            toggleButtons();
         }
        }
    });
    gridstore.setDefaultSort(gridsavedstate.sortinfo.field, gridsavedstate.sortinfo.dir);
    gridstore.setBaseParam('limit', gridsavedstate.displaysize);

    // pluggable renders
    function renderName(value, p, record){
        bgcolor = "";
        if(record.data.clienttypebgcolor!=""){
                bgcolor = record.data.clienttypebgcolor;
        }
        return String.format(
                '<span style="background-color: {2};"><a href="index.php?fuse=clients&view=ShowCustomerData&frmClientID={1}">{0}</a></span>',
                record.data.firstname + " " + record.data.lastname, record.data.id, bgcolor);
    }
	
    function renderPriority(value,p,record){
        //get priority color
        if (record.data.priority==1){
            priorityname = lang("High");
            priorityclass="innerPriorityOne";
        }else if(record.data.priority==2){
            priorityname = lang("Medium");
            priorityclass="innerPriorityTwo";
        }else{
            priorityname = lang("Low");
            priorityclass="innerPriorityThree";
        }

        p.css = priorityclass;
            return String.format("{0}",priorityname);
    }

    function renderTicketType(value,p,record){
            return String.format("{0}",record.data.messagetypename);
    }

    // pluggable renders
    function renderStatus(value, p, record){
	return String.format("{0}",record.data.statusname);
    }

    function renderAssignedTo(value,p,record){
        return "<span ext:qtip='"+record.data.assignedtofull+"'>"+record.data.assignedtoname+"</span>"
    }

    function renderDateSubmited(value,p,record){
        return record.data.datesubmittedclean;
    }

    function renderTimeElapsed(value,p,record){
        var timeelapsed = record.data.timeelapsed;
        timeelapsed = timeelapsed.replace("d","<span style='color:orange'>d</span>");
        timeelapsed = timeelapsed.replace("h","<span style='color:orange'>h</span>");
        timeelapsed = timeelapsed.replace("m","<span style='color:orange'>m</span>");
        return "<span>"+timeelapsed+"</span>"
    }

    function renderMethod(value,p,record) {
        method = "<img qtip='" + record.data.method_tooltip + "' src='"+relativePath+"templates/admin/images/ticket/method-"+record.data.method+".png' width='10' height='10' />";
        return method;
    }

    function renderSubject(value, p, record){

        if(typeof(gridstore.baseParams['query']) != "undefined") {
            filter = "&expand=1&query=" + gridstore.baseParams['query'];
        } else {
            filter="";
        }

        if(record.data.userstatus!=1){
            colorstyle = "style='color:gray;'";
        }else{
            colorstyle = "";
        }

        attachment = "";
        if (record.data.hasAttachment) {
             attachment = "<img src='../images/190.png' alt='attachment' style='padding-left:4px;padding-right:3px;position: relative;top: 1px;' />";
        }

        if(record.data.isguest){
            colorstyle = "";
            title = "#"+record.data.id+attachment+" <span style='color:gray;'>["+lang('guest')+"]</span> "+record.data.subject;
        }else{
            title = "#"+record.data.id+attachment+" "+record.data.subject;
        }
       
        
        popup = "<b>Title</b>: "+record.data.subject;
        popup += "<br/><b>Submitted By</b>: "+record.data.submittedby;
        popup += "<br/><b>Assigned To</b>: "+record.data.assignedtofull;
        if (record.data.usergroupname!="") {
            popup += "<br/><b>Group</b>: "+record.data.usergroupname;
        }
        popup = popup.replace(/'/g,"&apos;");
        if(record.data.usergroupcolor==""){
			if (filter == "") {
				subject = String.format("<a qtip='{3}' href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID={1}' {2}>{0}</a>",title,record.data.id,colorstyle,popup);
			} else {
				subject = String.format("<a qtip='{3}' href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID={1}&{3}' {2}>{0}</a>",title,record.data.id,colorstyle,filter,popup);
			}
        }else{
            subject = String.format("<span class='customergroupstyle'><a qtip='{5}' style='background:{4} !important;' href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID={1}&{3}' {2}>{0}</a></span>",title,record.data.id,colorstyle,filter,record.data.usergroupcolor,popup);
        }

        return subject;
    }
	
    var gridbb = new Ext.PagingToolbar({
        id : 'ticketgridpagingbar',
        store: gridstore,
        pageSize: gridsavedstate.displaysize,
        emptyMsg: "",
        listeners:{
         'change': function(bb,data){
                var addBy = 0;
                if (data.total != 0) {
                    addBy = 1;
                }
                from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
                to = from+ bb.pageSize - 1;
                if(to>data.total) to = data.total;
				document.getElementById('ticketgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				document.getElementById('ticketlistlabel').innerHTML =  String.format(lang('Displaying tickets') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
          }
        }
    });

    new Ext.ToolTip({
        target: 'ticketsearchinput',
        anchor: 'top',
        autoHide: true,
        dismissDelay:3500,
        anchorOffset: 1, // center the anchor on the tooltip
        html: lang('Search tickets by subject and messages.  Four character minimum')
    });

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

    var expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
           'expand': function(re,response,body,index){
               Ext.Ajax.request({
                   url: "index.php?action=getLastXTicketMessages&fuse=support",
                   success: function(xhr) {
                        expanderBody = "";
                        var json = ce.parseAjaxResponse(xhr);                        
                        for ( var i in json.logs )
                        {                           
                            
                            entry = json.logs[i];
                            if (typeof(entry) != "object") continue;
                            
                            userText = entry.name;
                            privateText = "";
                            
                            if (entry.skip) {
                                expanderBody += "<center><span style='color:#888;font-weight:bold;'>"+entry.msg+"</span></center>";
                            } else { 
                                if (entry.isprivate == "1") privateText = " <span style='float:right;color:red;font-weight:bold;'>private</span>";
                                if (entry.isadmin) userText = "<span style='color:green;'>"+entry.name+"</span>";
                                expanderBody += "<div class='ext-expanderframe'>";
                                expanderBody += "<div class='ext-expanderframe-details'>";
                                expanderBody += "<b>"+lang("By")+":</b> "+userText+"&nbsp;&nbsp;<b>"+lang("Date")+":</b> "+entry.date+privateText;                                
                                expanderBody += "<div style='padding-top:8px;'>"+entry.msg+"</div>";
                                expanderBody += "</div>";
                                expanderBody += "</div>";
                            }
                        }
                        body.innerHTML = expanderBody;
                   },
                   failure: function() {
                        body.innerHTML = "Failed";
                   },
                   params: { 
                        ticketid: response.data.id
                   }
               });
               
               
            }
        }
    });


    var ticketGrid = new Ext.grid.GridPanel({
        el:'tickets-grid',
        autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,
        columns:[expander,
        sm,
        {
            id: 'method',
            header: lang(".."),
            width: 10,
            renderer: renderMethod,
            dataIndex : "method",
            sortable: true,
            hidden: true,
            align: 'center'
        },
        {
            id: 'subject',
            header: lang("Subject"),
            width: 300,
            renderer: renderSubject,
            dataIndex : "id",
            sortable: true
        },{
            id: 'submittedby',
            header: lang("Submitted By"),
            width: 120,
            align:'center',
            hidden:true,
            dataIndex : "submittedby",
            sortable: false
        },{
            id: 'assignedto',
            header: lang("Assigned To"),
            width: 120,
            align:'center',
            hidden:true,
            renderer: renderAssignedTo,
            dataIndex : "assignedtoname",
            sortable: true
        },
        {
            id: 'messagetype',
            header: lang("Ticket Type"),
            dataIndex : "messagetype",
            renderer: renderTicketType,
            width: 80,
            hidden: false,
            sortable: true,
            align:"center"
        },{
            id: 'timeelapsed',
            header: lang("Time Elapsed"),
            width: 60,
            align:'center',
            renderer: renderTimeElapsed,
            dataIndex : "timeelapsedinminutes",
            sortable: true
        },{
            id: 'datesubmited',
            header: lang("Date"),
            hidden:true,
            align: 'center',
            dataIndex: "datesubmitted",
            width: 100,
            sortable: true,
            renderer: renderDateSubmited
        },
        {
            id: 'status',
            header: lang("Status"),
            dataIndex : "status",
            renderer: renderStatus,
            width: 100,
            hidden: false,
            sortable: true,
            align:"center"
        },{
            id: 'priority',
            header: lang("Priority"),
            dataIndex : "priority",
            renderer: renderPriority,
            width: 40,
            hidden: false,
            sortable: true,
            align:"center"
        }
        
        ],
        stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no tickets to display."),
            scrollOffset:1
        },
        sm: sm,
        plugins: expander,
        // inline buttons
        buttons:[actionbuttons = new Ext.Button({
                     id:'actionbuttons',
                     autoHeight:true, 
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Action'),
                     disabled: true,
                     menu: actionMenu = new Ext.menu.Menu({
                         enableScrolling:false,
                         shadow:false
                     })
                 }),
                 statusbuttons = new Ext.Button({
                    id:'statusbuttons',
                     autoHeight:true, 
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Status'),
                     disabled: true, 
                     menu: statusMenu = new Ext.menu.Menu({
                         enableScrolling:false,
                         shadow:false
                     })
                 }),
                 prioritybuttons = new Ext.Button({
                     id:'prioritybuttons',
                     autoHeight:true, 
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Priority'),
                     disabled: true, 
                     menu: priorityMenu = new Ext.menu.Menu({
                         enableScrolling:false,
                         shadow:false
                     })
                 }),
                 assigntobuttons = new Ext.Button({
                     id:'assigntobuttons',
                     autoHeight:true, 
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Assign To'),
                     disabled: true, 
                     menu: assigntoMenu = new Ext.menu.Menu({
                         enableScrolling:false,
                         shadow:false
                     })
                 })
                ],
        buttonAlign:'left',
        // paging bar on the bottom
        bbar: gridbb,
        listeners:{
           'columnmove': function(oldIndex,newIndex){
               //alert(oldIndex);
               //alert(newIndex);
            },
            'sortchange' : function (grid,sortInfo){
                gridsavedstate.sortinfo.field = sortInfo.field;
                gridsavedstate.sortinfo.dir = sortInfo.direction;
                updateGridSavedState("SupportTicketGridState");
            }
        }
    });

    ticketGrid.restoreState();

    function updateGridSavedState(customfield){
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    //msg('Settings Update Successfully');
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: {gridcustomfield: customfield,
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(columnsavedstate)
                     },
           method:'post'
        });
    }
    
    // render it
    ticketGrid.render();

    //called to standardize the default filters and dropdown filter
    viewtickets.FilterGrid = function(filter,customerid){
        //these are set in the viewusers.tpl
        if(customerid!=null) gridstore.setBaseParam('customerid', customerid);
        if(filter!=null) gridstore.setBaseParam('filter', filter);
        gridstore.load({params:{start:0}});
    }

    //check to see if my template file has set some additional search variables
    //from the post of the advanced search.  If so then add to the params so the
    //action can filter using these properties.
    if (typeof(searchcustomerid) != "undefined") {
        //searchfilter is set in tpl from view if search filter is passed in url
        viewtickets.FilterGrid(viewtickets.searchfilter,searchcustomerid);
    }
      
    function PopulateCustomQueryNoticeBox(text,isprivate,id){
        //customquerynoticebox
        Ext.get("customquerynoticebox").setStyle("display","");
        Ext.get("deletecustomfilter").setStyle("display","inline");
        viewtickets.searchfilter = id; //used by update and delete custom query buttons
        document.getElementById("filtername").value = text;
        document.getElementById("filterprivate").checked = (isprivate==0) ? false : true;
    }

    new Ext.form.ComboBox({
        transform: 'searchtype',
        id:'searchtype',
        typeAhead: true,
        triggerAction: 'all',
        width:100,
        editable: false,
        forceSelection:true,
        listeners: {
            'select' : function (cb, record) {
        
            }
        }
    })

    //create the combo for refresh intervals
    new Ext.form.ComboBox({
        transform: 'refreshgridrate',
        typeAhead: true,
        triggerAction: 'all',
        width:135,
        editable: false,
        forceSelection:true,
        listeners: {
            'select' : function (cb, record) {
                intervalRate = parseInt(cb.getValue());
                if (intervalid!=0)  {
                    //cancel interval
                    clearInterval(intervalid);
                    intervalid = 0
                }

                if (intervalRate> 0) {
                    intervalRate = intervalRate * 60000;
                    intervalid = setInterval("gridstore.reload()",intervalRate);
                }
            }
        }
    });

    // create the count combo instance
    var combo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value: gridsavedstate.displaysize,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: [
                'myId',
                'displayText',
                'type'
            ],
            data: [[10, '10'], [25, '25'], [50, '50'], [150,'150'],[300,'300']]
        }),
        valueField: 'myId',
        width: 50,
        displayField: 'displayText',
        applyTo: 'displayticketscount-with-qtip',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                    gridstore.setBaseParam('limit', record.data.myId);
                    gridbb.pageSize = record.data.myId;
                    gridstore.load({params:{start:0}});
                    gridsavedstate.displaysize = record.data.myId;
                    updateGridSavedState("SupportTicketGridState");
             }
        }

    });

    // option button code
    function toggleButtons() {
        
        if (sm.getCount()>0) {
            //halt refreshes until we unclick all checkboxes
            if (intervalid!=0) {
                clearInterval(intervalid);
            }
            actionbuttons.setDisabled(false);
            if (Ext.getCmp('addroutingfilter')) Ext.getCmp('addroutingfilter').setDisabled(false);
            statusbuttons.setDisabled(false);
            prioritybuttons.setDisabled(false);
            assigntobuttons.setDisabled(false);
        } else {
            //reset halted refreshes
            if (intervalid!=0){
                clearInterval(intervalid);
                intervalid = setInterval("gridstore.reload()",intervalRate);
            }
            actionbuttons.setDisabled(true);
            if (Ext.getCmp('addroutingfilter')) Ext.getCmp('addroutingfilter').setDisabled(true);
            statusbuttons.setDisabled(true);
            prioritybuttons.setDisabled(true);
            assigntobuttons.setDisabled(true);
        }
        
        //we need to not show the action buttons for spam for non guest emails
        rows = sm.getSelections();
        for(x=0;x<rows.length;x++) {
            if (!rows[x].data.isguest) {
                Ext.getCmp('addroutingfilter').setDisabled(true);
                break;
            }
        }
        
    }

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

	var btnButtonActionHandler = function(button, event){
        // Disable the grid
        ticketGrid.disable();
        
        alertText = false;
        gridMsg = false;
        //Switch the type
        switch(button.type){
           case "action":
               if(button.id=="delete"){
                       alertText = "Are you sure you want to delete the selected ticket(s)?";
                   requesturl = "index.php?fuse=support&action=DeleteTickets";
               }else if(button.id=="merge"){
                       alertText = "Are you sure you want to merge the selected ticket(s)?";
                   requesturl = "index.php?fuse=support&action=MergeTickets";
               }else if(button.id=="unsubscribe"){
                   alertText = "Are you sure you want to unsubscribe from the selected ticket(s)?";
                   requesturl = "index.php?fuse=support&action=UnsubscribeTickets";
               }else if (button.id=="addroutingfilter") {
                   gridMsg = lang("Marking tickets as spam...");
                   alertText = "Are you sure you want to prevent tickets from being created from the selected ticket(s) email addresses?";
                   requesturl = "index.php?fuse=support&action=AddEmailAsSpam";
               }
               break;
           case "status":
                   alertText = "Are you sure you want to change the status of the selected ticket(s) to '" + button.text + "'?";
               requesturl = "index.php?fuse=support&action=UpdateTicketStatus";
               break;
           case "priority":
                   alertText = "Are you sure you want to change the priority of the selected ticket(s) to '" + button.text + "'?";
               requesturl = "index.php?fuse=support&action=UpdateTicketPriority";
               break;
           case "assignto":
                   alertText = "Are you sure you want to reassign the selected ticket(s)?";
               requesturl = "index.php?fuse=support&action=UpdateTicketAssignment";
               break;
           default:
               return false;
        }

        // Show alert message
        if(alertText != false) {
            Ext.Msg.show({
                title:    "Confirm Ticket Action",
                msg:      alertText,
                buttons:  Ext.Msg.YESNO,
                disabled: true,
                fn:       function(btn, text){
                    // We chose Yes so do the cal
                    if(btn == 'yes'){
                        if (gridMsg) ce.msg(gridMsg,true);
                        callTicketAction(requesturl, button);
                        callTicketSummaries();
                    } else {
                     //sm.clearSelections();
                     ticketGrid.enable();
                    }
                },
                icon:     Ext.MessageBox.QUESTION
            });
        } else {
            // No message so go straight to the call
            callTicketAction(requesturl, button);
			callTicketSummaries();
        }
        return true;
    }

    function callTicketAction(requesturl, button) {
	    Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                gridstore.load({params:{start:0}});
                var data = ce.parseAjaxResponse(xhr);
                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 if(data.message){
                    msg(data.message);
                }else{
                    msg(lang("Ticket(s) have been updated"));
                }

                // Clear any selected check boxes (including the header check box using the overriden fucntion)
                sm.clearSelections();
                ticketGrid.enable();
           },
           failure: function() {
                //ticketGrid.enable()
                //Ext.Msg.alert("Fail");
           },
           params: {ids: Ext.util.JSON.encode(GetSelectedRowIds()),
                     item: button.id,
                     type: button.type
            }
        });

        
	    
    }
            
    function updateButtonsWithContent(data){
        if(data.type == "filter" || 
           data.type == "customfilter" || 
           data.type == "departmentfilter")
        {

            if(data.private == undefined){
                data.private = 0;
            }
            //check to see if we passed a filter
            //if grab the full name so that we can set the drop down
            //to it after it finishes loading.  We can also change the
            //style here later.
            if(viewtickets.searchfilter==data.id){
                if(data.type == "customfilter"){
                    PopulateCustomQueryNoticeBox(data.name, data.private, data.id);
                    label = "<a href='' qtip='Click to edit custom filter' >"+data.name+"</a>";
                } else {
                    Ext.get("customquerynoticebox").setStyle("display","none");
                    label = data.name;
                }
                document.getElementById('ticketlisttablelabel').innerHTML = lang("Viewing") + "&nbsp;" + label;
            }

        } else {
            var comboitem = new Ext.menu.Item({type: data.type, id: data.id, text: data.name});
            comboitem.addListener("click",btnButtonActionHandler);
            switch(data.type){
                case "action":
                    actionMenu.addMenuItem(comboitem);
                break;
                case "priority":
                    priorityMenu.addMenuItem(comboitem);
                break;
                case "assignto":
                    id = comboitem.id.split("_");
                    if(id.length == 2){
                        comboitem.menu = new Ext.menu.Menu({id:"menu_"+data.id,enableScrolling:false});
                        comboitem.menu.add({text:'<b class="menu-title">Choose a Staff Member</b>'});
                        assigntoMenu.add(comboitem);
                    } else{
                        menu = Ext.getCmp("menu_"+id[0]+"_"+id[1]);
                        menu.add(comboitem);
                    }
                break;
                case "status":
                    statusMenu.addMenuItem(comboitem);
                break;
            }
        }
        
    }

    Ext.Ajax.request({
       url: 'index.php?fuse=support&action=getTicketListDropDownOptions',
       success: function(xhr) {
            var data = ce.parseAjaxResponse(xhr);
            //data.options.forEach(updateButtonsWithContent);
            for ( var i in data.options )
            {
                updateButtonsWithContent( data.options[i] );
            }
       },
       failure: function() {
            //Ext.Msg.alert("Fail");
       },
       params: {filter: gridstore.baseParams['filter']}
    });

    viewtickets.PopulateTicketFilters = function(){
        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=getTicketFilters',
           success: function(xhr) {
                //go through our options and add to the UI
                var data = ce.parseAjaxResponse(xhr);
                for ( var i in data.options )
                {
                    updateButtonsWithContent( data.options[i] );
                }
           },
           failure: function() {
                //Ext.Msg.alert("Fail");
           }
        });
    }
    
    function DeleteCustomFilter(){
        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=DeleteTicketFilter',
           success: function(xhr) {
                var data = ce.parseAjaxResponse(xhr);
                if(!data.error){
                    window.location = "index.php?fuse=support&view=ViewTickets&refreshTicketList";
                    //we do not need to repopulate the filters if there was a validation error
                    //searchfilter = "open";
                    //Ext.get("customquerynoticebox").setStyle("display","none");
                    //FilterGrid(searchfilter,0);
                } else {
                    msg(data.message);
                }
            },
           failure: function() {
                //we should standardize json.error
                msg("Error Deleting Filter"); 
           },
           params: {idfilter: viewtickets.searchfilter}
        });
    }
         
    function UpdateCustomFilter(){        
        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=SaveTicketFilter',
           success: function(xhr) {
                callTicketSummaries();
                var data = ce.parseAjaxResponse(xhr);
                if(!data.error){
                    //we do not need to repopulate the filters if there was a validation error
                    Ext.get("deletecustomfilter").setStyle("display","inline");
                } else {
                    msg(data.message);
                }
            },
           failure: function() {
                //we should standardize json.error
                msg("Error Saving Filter"); 
           },
           params: {filtername: document.getElementById("filtername").value,
                     idfilter: viewtickets.searchfilter,
                     private: document.getElementById("filterprivate").checked}
        });
    }     
                   
    Ext.get('updatecustomfilter').on('click', function() {UpdateCustomFilter();});
    Ext.get('deletecustomfilter').on('click', function() {DeleteCustomFilter();});  

    ViewTicketsInvoked = true;
    viewtickets.PopulateTicketFilters();

}