/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

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');
  })
});

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

var ViewTicketsInvoked = false;

function ViewTickets() {

    // Prevent this from being called
    if ($('tickets-grid') == null
      || ViewTicketsInvoked){
        return;
    }

    Ext.QuickTips.init();
    var gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'tickets',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
        fields: [
                'id','usergroupcolor','submittedby','timeelapsedinminutes','assignedtofull','isguest','priority','tag', 'subject','messagetype','messagetypename','datesubmitted','datesubmittedclean','status','statusname','userid','assignedtoid','assignedtodeptid','userstatus','assignedtoname','timeelapsed'
        ],
        // 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){
        return "<span>"+record.data.timeelapsed+"</span>"
    }

    function renderSubject(value, p, record){

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

        if(record.data.isguest){
            colorstyle = "";
            title = "#"+record.data.id+" <span style='color:gray;'>["+lang('guest')+"]</span> "+record.data.subject;
        }else{
            title = "#"+record.data.id+" "+record.data.subject;
        }

        if(record.data.usergroupcolor==""){
            subject = String.format("<a href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID={1}&frmClientID={3}' {2}>{0}</a>",title,record.data.id,colorstyle,record.data.userid);
        }else{
            subject = String.format("<span class='customergroupstyle'><a style='background:{4} !important;' href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID={1}&frmClientID={3}' {2}>{0}</a></span>",title,record.data.id,colorstyle,record.data.userid,record.data.usergroupcolor);
        }

        return subject;
    }

    var gridbb = new Ext.PagingToolbar({
        id : 'ticketgridpagingbar',
        store: gridstore,
        pageSize: gridsavedstate.displaysize,
        emptyMsg: "",
        listeners:{
         'change': function(bb,data){

                    if(data.total == 0) { var addBy = 0;} else { var addBy = 1;}
                    from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
                    to = from+ bb.pageSize - 1;
                    if(to>data.total) to = data.total;

				$('ticketgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				$('ticketlistlabel').innerHTML =  String.format(lang('Displaying tickets') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
          }
        }
    });

    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:'tickets-grid',
	autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,
        // grid columns
        columns:[
        sm,
        {
            id: 'id',
            header: lang("ID"),
            width: 20,
            hidden:true,
	    dataIndex : "id",
            sortable: true
        },
        {
            id: 'subject',
            header: lang("Subject"),
            width: 300,
            renderer: renderSubject,
	    dataIndex : "id",
            sortable: true
        },{
            id: 'submittedby',
            header: lang("Submitted By"),
            width: 120,
            align:'left',
            hidden:true,
            dataIndex : "submittedby",
            sortable: true
        },{
            id: 'assignedto',
            header: lang("Assigned To"),
            width: 120,
            align:'left',
            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: 120,
            align:'center',
            renderer: renderTimeElapsed,
	    dataIndex : "datesubmitted",
            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:"right"
        },{
	    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 available at this time"),
	    scrollOffset:1
        },
        sm: sm,
        // 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");
            }
        }
    });



    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)
                     },
           method:'post'
        });
    }

    // render it
    grid.render();

    //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
        FilterGrid(searchfilter,searchcustomerid);
    }

    //called to standardize the default filters and dropdown filter
    function FilterGrid(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}});
    }

    function PopulateCustomQueryNoticeBox(text,isprivate,id){
        //customquerynoticebox
        Ext.get("customquerynoticebox").setStyle("display","");
        Ext.get("deletecustomfilter").setStyle("display","inline");
        searchfilter = id; //used by update and delete custom query buttons
        document.getElementById("filtername").value = text;
        document.getElementById("filterprivate").checked = (isprivate==0) ? false : true;
    }

    // create the count combo instance
    var combo = new Ext.form.ComboBox({
        tpl: '<tpl for="."><div ext:qtip="Display {displayText} items" class="x-combo-list-item">{displayText}</div></tpl>',
        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");

             }
        }

    });

    //create the type filter combo instance
    //record constructor so that we can create these on the fly .. we define
    //the same items that the store has in fields
    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var tickettypecombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:defaultfiltername,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'private'
            ]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        applyTo: 'tickettype',
        // all of your config options
        listeners:{
             'select': function(cb,record){

                $('ticketlisttablelabel').innerHTML = defaultfiltername;

                if(record.data.myId == "div1" || record.data.myId == "div2"){
                    return false;
                }else{
                    $('ticketlisttablelabel').innerHTML = record.data.displayText;
                    if(record.data.type == "customfilter"){
                        //show and populate all the fields in the custom query box
                        PopulateCustomQueryNoticeBox(record.data.displayText, record.data.private, record.data.myId);
                    }else{
                        Ext.get("customquerynoticebox").setStyle("display","none");
                    }
                    if(Ext.get("searchquerynoticebox")!=null)
                    {
                        Ext.get("searchquerynoticebox").setStyle("display","none");
                    }
                    FilterGrid(record.data.myId,0);
                }
             }
        }

    });

    //$('ticketlisttablelabel').innerHTML = defaultfiltername;

    // option button code
    function toggleButtons(count){
        if(sm.getCount()>0){
            actionbuttons.setDisabled(false);
            statusbuttons.setDisabled(false);
            prioritybuttons.setDisabled(false);
            assigntobuttons.setDisabled(false);
        }else{
            actionbuttons.setDisabled(true);
            statusbuttons.setDisabled(true);
            prioritybuttons.setDisabled(true);
            assigntobuttons.setDisabled(true);
        }
    }

    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
	    grid.disable();
	    alertText = 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";
	           }
	           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'){
                            callTicketAction(requesturl, button);
                        } else {
                         //sm.clearSelections();
                         grid.enable();
                        }
                    },
                    icon:     Ext.MessageBox.QUESTION
                });
            } else {
                // No message so go straight to the call
                callTicketAction(requesturl, button);
            }
        }

        function callTicketAction(requesturl, button) {

	    Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                        //refreshgrid

                        gridstore.load({params:{start:0}});

                        var data = Ext.util.JSON.decode(xhr.responseText);
                        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"),"");
                        }


                    },
           failure: function() {
                //grid.enable()
                Ext.Msg.alert("Fail");
           },
           params: { ids: Ext.util.JSON.encode(GetSelectedRowIds()),
                     item: button.id,
                     type: button.type
            }
        });

        // Clear any selected check boxes (including the header check box using the overriden fucntion)
            sm.clearSelections();
            grid.enable();

    }

    function updateButtonsWithContent(data){

        if(data.type == "filter" ||
           data.type == "customfilter" ||
           data.type == "departmentfilter" ||
           data.type == "dividerfilter")
        {
            if(data.private == undefined){
                data.private = 0;
            }

            var comboitem = new storeItem({myId:data.id,displayText:data.name,type:data.type, private:data.private});
            //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(searchfilter==data.id){
                tickettypecombo.setValue(data.name);
                $('ticketlisttablelabel').innerHTML = data.name;
                if(data.type == "customfilter"){
                    PopulateCustomQueryNoticeBox(data.name, data.private, data.id);
                }
            }

            tickettypecombo.getStore().insert(
                tickettypecombo.getStore().getCount(),
                comboitem
            );
        }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 = Ext.util.JSON.decode(xhr.responseText);
                    //data.options.forEach(updateButtonsWithContent);
                    for ( var i in data.options )
                    {
                        updateButtonsWithContent( data.options[i] );
                    }
                },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: { foo: 'bar' }
    });

    function PopulateTicketFilters(){
        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=GetTicketFilters',
           success: function(xhr) {
                        //clear the items from our combobox
                        tickettypecombo.getStore().removeAll();
                        //go through our options and add to the UI
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        //data.options.forEach(updateButtonsWithContent);

                        for ( var i in data.options )
                        {
                            updateButtonsWithContent( data.options[i] );
                        }

                    },
           failure: function() {
                Ext.Msg.alert("Fail");
           },
           params: { foo: 'bar' }
        });
    }
    //End option dropdown population
    function DeleteCustomFilter(){
        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=DeleteTicketFilter',
           success: function(xhr) {
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        if(!data.error){
                            //we do not need to repopulate the filters if there was a validation error
                            searchfilter = "open";
                            Ext.get("customquerynoticebox").setStyle("display","none");
                            PopulateTicketFilters();
                            FilterGrid(searchfilter,0);
                        }
                        msg(data.message,"");
                    },
           failure: function() {
                //we should standardize json.error
                msg("Error Deleting Filter","");
           },
           params: { idfilter: searchfilter }
        });
    }

    function UpdateCustomFilter(){
        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=SaveTicketFilter',
           success: function(xhr) {
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        if(!data.error){
                            //we do not need to repopulate the filters if there was a validation error
                            PopulateTicketFilters();
                        }
                        msg(data.message,"");
                    },
           failure: function() {
                //we should standardize json.error
                msg("Error Saving Filter","");
           },
           params: { filtername: document.getElementById("filtername").value,
                     idfilter: searchfilter,
                     private: document.getElementById("filterprivate").checked }
        });
    }

    Ext.get('updatecustomfilter').on('click', function() {UpdateCustomFilter();});
    Ext.get('deletecustomfilter').on('click', function() {DeleteCustomFilter();});

    PopulateTicketFilters();
    ViewTicketsInvoked = true;

};