var gridstore;

function SearchTroubleTickets() {
    if(document.getElementById("includeclosed").checked){
        gridstore.setBaseParam('filter', 'searchclosed');
    }else{
        gridstore.setBaseParam('filter', 'searchopen');
    }
    gridstore.setBaseParam('query', Ext.get('ticketsearchinput').getValue());
    gridstore.load({params:{start:0}});
}

Ext.onReady(function(){

    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(){
             //what to do on load
         }
        }
    });
    //gridstore.setDefaultSort(gridsavedstate.sortinfo.field, gridsavedstate.sortinfo.dir);
    gridstore.setBaseParam('limit', 10);
    gridstore.setBaseParam('filter', 'searchopen');

    // 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){

        var searchquery = Ext.get('ticketsearchinput').getValue();

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

        return subject;
    }

    var gridbb = new Ext.PagingToolbar({
        id : 'ticketgridpagingbar',
        store: gridstore,
        pageSize: 10,
        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 grid = new Ext.grid.GridPanel({
        el:'tickets-grid',
        autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,
        // grid columns
        columns:[
        {
            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',
            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',
            hidden:true,
            renderer: renderTimeElapsed,
	    dataIndex : "datesubmitted",
            sortable: true
        },{
            id: 'datesubmited',
            header: lang("Date"),
            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: true,
            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
        },
        // paging bar on the bottom
        bbar: gridbb,
        listeners:{
           'columnmove': function(oldIndex,newIndex){
               //alert(oldIndex);
               //alert(newIndex);
            },
            'sortchange' : function (grid,sortInfo){
                //alert('todo');
            }
        }
    });
    grid.render();
    gridstore.load({params:{start:0}});

}); //end onReady