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

/*
DO NOT CREATE VARIABLES OR FUNCTIONS WITH THE FOLLOWING NAMES, IN ORDER TO AVOID CONFLICTS:
    pendingMask
    showPendingItems
    PluginPendingItems
    showMask
    hideMask
    cleanjsfiles
    removejscssfile
*/

var ViewSupportTicketsInvoked = false;
var waitingMask;

function ViewSupportTickets(){
    // Prevent this from being called twice
    if($('supporttickets') == null || ViewSupportTicketsInvoked){
        return;
    }
    
    Ext.QuickTips.init();
    var gridstore = new Ext.data.JsonStore({
        id:             "gridstore",
        root:           'tickets',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        fields:         [
            'id',
            'submittedby',
            'subject',
            'statusname',
            'status',
            'datesubmitted',
            'assignedtoname',
            'timeelapsed',
            'assignedtofull',
            'method',
            'method_tooltip'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:	'index.php?fuse=support&action=GetTicketList&filter=awaitingreply'
        })
    });
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        id:         'po-sm',
        width:      30,
        listeners:  {
            'rowdeselect':    function(model, rowIndex, record){
                toggleButtons();
            },
            'rowselect':      function(model, rowIndex, record){
                toggleButtons();
            }
        }
    });
    
    function renderSubject(value,p,record){
        return String.format('<a href="index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID={2}"><span qtip="{0}">{1}</span></a>', record.data.subject, record.data.subject, record.data.id);
    }
	
    function renderTimeElapsed(value,p,record){
        return "<span>"+record.data.timeelapsed+"</span>"
    }
	
    function renderAssignedTo(value,p,record){
        return "<span ext:qtip='"+record.data.assignedtofull+"'>"+record.data.assignedtoname+"</span>"
    }
    function renderStatus(value, p, record){
        return String.format("{0}",record.data.statusname);
    }
    
    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;
    }
    
    var grid = new Ext.grid.GridPanel({
        el:               'supporttickets',
        autoHeight:       true,
        store:            gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,   
        // grid columns
        columns:          [
            sm,
            {
                id:         'id',
                header:     "id",
                width:      75,
                dataIndex:	"id",
                sortable:   true
            },
            {
                id:         'subject',
                header:     "Subject",
                width:      150,
                dataIndex:  "subject",
                renderer:	renderSubject,
                sortable:   true
            },
            {
                id:         'assigned', 
                header:     "Assigned",
                width:      170,
                dataIndex:  "assignedtoname",
                renderer: renderAssignedTo,
                sortable:   true,
                align:      "center"
            },
            {
                id:         'time', 
                header:     "Time Elapsed",
                width:      150,
                dataIndex:  "datesubmitted",
                renderer: renderTimeElapsed,
                sortable:   true,
                align:      "center"
            },
            {
                id:         'status', 
                header:     "Status",
                width:      150,
                dataIndex:  "status",
                renderer: renderStatus,
                sortable:   true,
                align:      "center"
            },
            {
            id: 'method',
            header: lang(".."),
            width: 20,
            renderer: renderMethod,
            dataIndex : "method",
            sortable: true,
            align: 'center'
        }
        ],
        stripeRows:       true,
        // customize view config
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:         lang("There are currently no support tickets"),
            scrollOffset:   1
        },
        sm:               sm,
        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'
    });
    
    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
        
        for(x = 0; x < rows.length; x++){
           arrayofids[x] = rows[x].data.id;
        }
        
        return arrayofids;
    }
    
    function showWaitingMask(){
        if(!waitingMask){
            waitingMask = new Ext.LoadMask('supporttickets', {msg:"Please wait..."});
        }
        
        waitingMask.show();
    }
    
    function hideWaitingMask(){
        waitingMask.hide();
    }
    
	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);
							callTicketSummaries();
                        } else {
                         //sm.clearSelections();
                         grid.enable();
                        }
                    },
                    icon:     Ext.MessageBox.QUESTION
                });
            } else {
                // No message so go straight to the call
                callTicketAction(requesturl, button);
				callTicketSummaries();
            }
        }

        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' }
    });
    
    // render it
    grid.render();
    
    // trigger the data store load
    gridstore.load({params:{start:0, limit:0}});
    
    ViewSupportTicketsInvoked = true;
}

function removeObjects(){
    // Set to NULL all the GLOBAL variables
    ViewSupportTicketsInvoked = null;
    waitingMask = null;
}