<div class="page-title">
    <h1>
        <?php echo $this->user->lang("Tickets");?>
     </h1>
</div>

<div class="search-filter">
    <form action="javascript:void(0);" class="d-flex align-items-center justify-content-between gap-2">
        <div class="d-flex align-items-center gap-2">
            <div class="keyword-search">
                <input type="text" class="form-control" placeholder="Keyword Search" id="inputTicketSearch">
            </div>

            <select name="selectSearchType" id="selectSearchType" class="listSelect2 form-select">
                <option value="0" selected="selected"><?php echo $this->user->lang('All Words'); ?></option>
                <option value="1"><?php echo $this->user->lang('Exact'); ?></option>
            </select>

            <label class="d-flex align-items-center gap-1 mb-0 w-30">
                <input type="checkbox" id="inputIncludeClosed">
                <span><?php echo $this->user->lang('Include Closed Tickets'); ?></span>
            </label>
        </div>
    </form>
</div>

<div class="cm-holder dt-info">
    <div class="head padding-bottom">
        <div class="dt-header">
            <div class="dt-header-left">
                <div class="dt-filters">
                    <div class="filter-group">
                        <label id="spanTicketListTableLabel"></label>
                    </div>
                </div>
            </div>

            <div class="dt-header-right">
                <div class="filter-group dt-length"></div>
            </div>
        </div>
    </div>
    <div class="dt-wrapper pull-top">
        <div class="table-responsive">
            <table id="tickets-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th></th>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th class="width4"><?php echo $this->user->lang('Subject'); ?></th>
                        <th class="width3"><?php echo $this->user->lang('Assigned To'); ?></th>
                        <th class="width2"><?php echo $this->user->lang('Last Reply'); ?></th>
                        <th class=""><?php echo $this->user->lang('Status'); ?></th>
                        <th class=""><?php echo $this->user->lang('Type'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <div class="dropdown" id="ticketActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="ticketActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-ticket-alt"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

                <div
                    class="menu"
                    id="ticketActionsMenu"
                    role="menu"
                    aria-labelledby="ticketActions"
                >
                    <?php if ($this->user->hasPermission('support_close_tickets')) { ?>
                        <button
                            class="menu-item"
                            role="menuitem"
                            type="button"
                            id="tkt-close"
                        >
                            <i class="fas fa-check-circle mi-icon"></i>
                            <?php echo $this->user->lang('Close'); ?>
                        </button>

                        <button
                            class="menu-item"
                            role="menuitem"
                            type="button"
                            id="tkt-re-open"
                        >
                            <i class="fas fa-undo mi-icon"></i>
                            <?php echo $this->user->lang('Re-Open'); ?>
                        </button>

                        <div class="menu-sep" role="separator"></div>
                    <?php } ?>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="tkt-markspam"
                    >
                        <i class="fas fa-exclamation-triangle mi-icon"></i>
                        <?php echo $this->user->lang('Mark as Spam'); ?>
                    </button>

                    <button
                        class="menu-item danger"
                        role="menuitem"
                        type="button"
                        id="tkt-delete"
                    >
                        <i class="fas fa-trash mi-icon"></i>
                        <?php echo $this->user->lang('Delete'); ?>
                    </button>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="tkt-merge"
                    >
                        <i class="fas fa-object-group mi-icon"></i>
                        <?php echo $this->user->lang('Merge'); ?>
                    </button>
                </div>
            </div>
        </div>

    </div>
</div>

<div id="ticketlist-custom-filter" style='display:none;'>
    <div class="mb-3">
        <label for="filtername" class="form-label fw-semibold">
            <?php echo $this->user->lang("Filter Name"); ?>
        </label>
        <input
            type="text"
            id="filtername"
            name="filtername"
            class="form-control required"
            value="Unsaved Filter"
        >
    </div>

    <div class="form-check mb-3">
        <input
            class="form-check-input"
            type="checkbox"
            id="filterprivate"
            name="filterprivate"
        >
        <label class="form-check-label" for="filterprivate">
            <?php echo $this->user->lang("Select if this filter is private to you"); ?>
        </label>
    </div>

    <input type="hidden" id="idfilter" name="idfilter" value="">

</div>

<script data-cfasync="false">
    var tickets = tickets || {};

    tickets.viewing_from_customer_profile = false;
    tickets.back_to_profile = <?php echo $this->back_to_profile;?>;
    tickets.searchfilter = "<?php echo $this->searchfilter; ?>";
    tickets.searchcustomerid = "<?php echo $this->searchcustomerid; ?>";
    tickets.searchquery = "<?php echo $this->searchquery; ?>";
    tickets.searchtype = "<?php echo $this->searchtype; ?>";
    tickets.creationStart = <?php echo ($this->startDate? ("'".$this->startDate."'") : 'null') ?>;
    tickets.creationEnd = <?php echo ($this->endDate? ("'".$this->endDate."'") : 'null') ?>;
    tickets.nameSearch = <?php echo ($this->nameSearch? ("'".$this->nameSearch."'") : 'null') ?>;
    tickets.assignee = <?php echo ($this->assignee? ("'".$this->assignee."'") : 'null') ?>;
    tickets.iscustom = "<?php echo $this->iscustomsearchquery; ?>";
    tickets.defaultFilterName = "<?php echo $this->defaultfiltername; ?>";
    tickets.autorefresh = "<?php echo $this->autorefresh; ?>";
    tickets.ticketState = {
        sort: 'lastReply',
        dir: 'desc'
    };
    tickets.disableOrdering = tickets.searchfilter === 'lastseen';

    tickets.loadCustomFilterWindow = function(id) {

        $.ajax({
            url: "index.php?fuse=support&action=getticketfilters",
            dataType: 'json',
            data: {
                customId: id
            },
            success: function(json) {

                for ( var i in json.options )
                {
                    if (json.options[i].type == "customfilter" && json.options[i].id == id) {
                        $('#filtername').attr('value',json.options[i].name);
                        if (json.options[i].private!=0) $("#filterprivate").attr("checked", true);
                        else $("#filterprivate").attr("checked", false);
                    }
                }
                $('#idfilter').val(id);

                tickets.window = new RichHTML.window({
                    el: 'ticketlist-custom-filter',
                    actionUrl: 'index.php?fuse=support&controller=ticketfilter&action=save',
                    deleteUrl: 'index.php?fuse=support&controller=ticketfilter&action=delete',
                    showSubmit: true,
                    showDelete: true,
                    onSubmit: function(data,params) {
                        json = clientexec.parseResponse(data);
                        if (json.error) {
                            return;
                        }
                        RichHTML.mask();
                        window.location.href= "index.php?fuse=support&view=viewtickets&controller=ticket&searchfilter=custom_"+json.id;
                    },
                    onDelete: function(data) {
                        json = clientexec.parseResponse(data);
                        if (json.error) {
                            return;
                        }
                        RichHTML.mask();
                        window.location.href= "index.php?fuse=support&view=viewtickets&controller=ticket&searchfilter=open";
                    },
                    title: clientexec.lang("Ticket Filter")
                });
                tickets.window.show();
            }
        });

    };

    tickets.searchTroubleTickets = function() {
        var state = {
            search_filter_query: clientexec.htmlentities($.trim($('#inputTicketSearch').val())),
            search_filter_searchType: $('#selectSearchType').val()
        };

        var url;
        var includeClosed = $('#inputIncludeClosed').prop('checked');

        if (state.search_filter_query == '') {
            state.search_filter = "open";
            state.search_filter_name =  (includeClosed ? clientexec.lang('All') : clientexec.lang('Open')) + ' ' +clientexec.lang('Tickets');
            $('#spanTicketListTableLabel').html(state.search_filter_name);
            $('.favorite-filter').show();
            $('.favorite-filter').attr('data-filter-id',state.search_filter);
            url = "index.php?fuse=support&view=viewtickets&controller=ticket&searchfilter="+state.search_filter;
        } else {
            if (includeClosed) { state.search_filter = 'searchclosed'; } else { state.search_filter = 'searchopen'; }
            state.search_filter_name = clientexec.lang('Viewing') + ' ' + (includeClosed ? clientexec.lang('all') : clientexec.lang('open')) + ' '+clientexec.lang('tickets with keyword(s)') + ' ' + '<span class="bold">' + state.search_filter_query+ '</span>';
            $('#spanTicketListTableLabel').html(state.search_filter_name);
            $('.favorite-filter').hide();
            $('.favorite-filter').attr('data-filter-id',0);
            url = "index.php?fuse=support&view=viewtickets&controller=ticket&filter="+state.search_filter+"&query="+state.search_filter_query+"&searchtype="+state.search_filter_searchType;
        }

        if (tickets.creationStart) {
            state.search_filter_creationStart = tickets.creationStart;
            url += "&creationStart="+encodeURIComponent(tickets.creationStart);
        }
        if (tickets.creationEnd) {
            state.search_filter_creationEnd = tickets.creationEnd;
            url += "&creationEnd="+encodeURIComponent(tickets.creationEnd);
        }

        if (tickets.creationStart && tickets.creationEnd) {
            state.search_filter_name += ' ' + clientexec.lang('from % to %', tickets.creationStart, tickets.creationEnd);
        } else if (tickets.creationStart) {
            state.search_filter_name += ' ' + clientexec.lang('from %', tickets.creationStart);
        } else if (tickets.creationEnd) {
            state.search_filter_name += ' ' + clientexec.lang('to %', tickets.creationEnd);
        }

        if (tickets.nameSearch) {
            state.search_filter_name += ' ' + clientexec.lang('for client %', tickets.nameSearch);
            state.search_filter_nameSearch = tickets.nameSearch;
            url += "&nameSearch="+encodeURIComponent(tickets.nameSearch);
        }

        if (tickets.assignee) {
            var assigneeLabel = $('select[name=ticket-assignee] option[value=' + tickets.assignee + ']').text();
            state.search_filter_name += ' ' + clientexec.lang('for assignee %', assigneeLabel);
            state.search_filter_assignee = tickets.assignee;
            url += "&assignee="+encodeURIComponent(tickets.assignee);
        }

        History.pushState(state, clientexec.original_title, url);

    };

    tickets.populateTicketFilters = function(name, custom, render, updatehistory) {
        var history_url = "";
        var searchfilter = "";
        var customerid = 0;

        if (typeof(render) === "undefined") {
            render = false;
        }
        if (typeof(updatehistory) === "undefined") {
            updatehistory = false;
        }

        //check to see if we are supposed to be filtering by customerid
        if (typeof(tickets.searchcustomerid) != "undefined") {
            tickets.ticketState.customerid = tickets.searchcustomerid;
            customerid = tickets.searchcustomerid;
        } else {
            tickets.ticketState.customerid = 0;
        }

        if ( typeof tickets.viewingFromProfile === 'undefined' ) {
            history_url = "index.php?fuse=support&view=viewtickets&controller=ticket";
            searchfilter = "open";
        } else {
            history_url = "index.php?fuse=clients&controller=userprofile&view=profiletickets";
        }

        if (tickets.searchfilter==="") {
            tickets.ticketState.filter = "open";
        } else if (tickets.searchquery ==="") {
            //lets clear out search query so refreshes will not search it
            $('#inputTicketSearch').val('');

            tickets.ticketState.filter = tickets.searchfilter;
            if (customerid == 0) {
                if ( typeof tickets.viewingFromProfile === 'undefined' ) {
                    history_url = "index.php?fuse=support&view=viewtickets&controller=ticket&searchfilter="+tickets.searchfilter;
                    searchfilter = tickets.searchtype;
                } else {
                   history_url = "index.php?fuse=clients&controller=userprofile&view=profiletickets";
                }
            } else {
                if ( typeof tickets.viewingFromProfile === 'undefined' ) {
                    history_url = "index.php?fuse=support&view=viewtickets&controller=ticket&filter="+tickets.searchfilter+"&customerid="+customerid;
                    searchfilter = tickets.searchtype;
                } else {
                    history_url = "index.php?fuse=clients&controller=userprofile&view=profiletickets";
                }
            }
        } else if (tickets.searchquery!="") {
            tickets.ticketState.query = tickets.searchquery;
            tickets.ticketState.filter = tickets.searchfilter;
            tickets.ticketState.searchtype = tickets.searchtype;
            if ( typeof tickets.viewingFromProfile === 'undefined' ) {
                history_url = "index.php?fuse=support&view=viewtickets&controller=ticket&filter="+tickets.searchfilter+"&query="+tickets.searchquery+"&searchtype="+tickets.searchtype;
                searchfilter = tickets.searchtype;
            } else {
                history_url = "index.php?fuse=clients&controller=userprofile&view=profiletickets";
            }
        }

        if (tickets.creationStart != '') {
            tickets.ticketState.creationStart = tickets.creationStart;
            history_url += '&creationStart='+encodeURIComponent(tickets.creationStart);
        }
        if (tickets.creationEnd != '') {
            tickets.ticketState.creationEnd = tickets.creationEnd;
            history_url += '&creationEnd='+encodeURIComponent(tickets.creationEnd);
        }
        if (tickets.nameSearch != '') {
            tickets.ticketState.nameSearch = tickets.nameSearch;
            history_url += '&nameSearch='+encodeURIComponent(tickets.nameSearch);
        }

        if (tickets.assignee) {
            tickets.ticketState.assignee = tickets.assignee;
            history_url += '&assignee='+encodeURIComponent(tickets.assignee);
        }

        if (typeof(custom) === "undefined") custom = false;
        if(custom) {
            label = "<a href='javascript:tickets.loadCustomFilterWindow(\""+tickets.searchfilter+"\");' id='ticketlist-editcustom-filter' title='Click to edit custom filter'>"+name+"</a>";
        } else {
            label = name;
        }
        tickets.searchfiltername = label;
        tickets.searchfiltername.replace(/'/g, "\\'");
        $('#spanTicketListTableLabel').html(clientexec.lang("Viewing") + " " + tickets.searchfiltername);
        if (render) {
            table.ajax.reload();
        }
    }

    var table;
    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=support&action=gettickets&controller=tickets&limit=0&filter='+tickets.searchfilter;
        table = $('#tickets-list').DataTable({
            columnDefs: [
                {
                targets: 1,
                orderable: false,
                className: 'select-checkbox',
                checkboxes: {
                    selectRow: true
                },
                width: '5%'
            }],

            select: {
                style: 'multi',
                selector: 'td:nth-child(2)'
            },

            processing: true,
            serverSide: true,
            ordering: !tickets.disableOrdering,
            "searching": false,
            "ajax": {
                url: ajaxUrl,
                data: function(d) {
                    $.extend(d, tickets.ticketState);
                }
            },
            "columns": [
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                { data: null, defaultContent: '', orderable: false, },
                {
                    "data": "id",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            var colorstyle = "", priorityclass = "", attachment = "", rowId = 0, title = "";

                            //we want to check if we just came from a query
                            //so we can pass it to ticket to highlight the word
                            if (row.query != "") {
                                filter = "&expand=1&query=" + row.query;
                            } else {
                                filter="";
                            }

                            if ( row.subject == '' ) {
                                row.subject = 'No Subject';
                            }

                            if (row.hasAttachment) {
                                attachment = "<i class='icon-paper-clip' style='padding-left:4px;'></i>";
                            }

                            rowId = row.id;

                            if (row.isguest) {
                                customerName = "<span style='color:gray;'>("+$.trim(clientexec.htmlspecialchars(row.submittedby))+")</span>";
                            } else {
                                if (row.usergroupcolor != "") {
                                    customerName = String.format("<span class='customergroupstyle' style='border-radius: 4px;padding:1px;background:{1};color:#ffffff'>&nbsp;&nbsp;{0}&nbsp;&nbsp;</span>",clientexec.htmlspecialchars(row.submittedby),row.usergroupcolor);
                                } else {
                                    customerName = String.format("{0}",clientexec.htmlspecialchars(row.submittedby));
                                }
                            }

                            if (tickets.viewing_from_customer_profile) {
                                subject = "<a href='index.php?fuse=support&id="+row.id+"&view=ticket&controller=ticket&userprofile=1' "+colorstyle+">"+row.subject+"</a>";
                            } else {
                                subject = "<a href='index.php?fuse=support&view=ticket&controller=ticket&id="+row.id+"' "+colorstyle+">"+row.subject+"</a>";
                            }

                            date = row.datesubmittedwithformat;

                            if (row.priority == 1) {
                                priorityclass = "tickets-priority-1";
                            } else if (row.priority == 2) {
                                priorityclass = "tickets-priority-2";
                            } else {
                                priorityclass = "tickets-priority-3";
                            }

                            if (row.method == 0) {
                                icon = '<i title="' + row.method_tooltip + '" class="fas fa-list-alt""></i>';
                            } else if (row.method == 1) {
                                icon = '<i title="' + row.method_tooltip + '" class="fas fa-bolt" style="color:orangered;"></i>';
                            } else if (row.method == 2) {
                                icon = '<i title="' + row.method_tooltip + '" class="fas fa-envelope"></i>';
                            } else {
                                icon = "<img title='" + row.method_tooltip + "' src='"+relativePath+"templates/admin/images/ticket/method-"+row.method+".png' width='10' height='10' />";
                            }

                            title = "<span class='"+priorityclass+"'></span><span style='color:#999;'>#"+rowId+attachment+"</span>&nbsp;&nbsp;"+ subject;
                            title += "<div style='padding-top:2px;'>"+icon+" from "+customerName+" posted on "+date+"</div>";

                            return title;
                        }

                        return data;
                    }
                },
                {
                    "data": "assignedtoname",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            var html = "", ratingLabel = "";
                            html =  row.assignedtofull;

                            if (row.statussystem == -1 && row.rate > 0) {
                                switch (row.rate) {
                                    case "1":
                                        ratingLabel = "Outstanding";
                                        break;
                                    case "2":
                                        ratingLabel = "Good";
                                        break;
                                    case "3":
                                        ratingLabel = "Ok";
                                        break;
                                    case "4":
                                        ratingLabel = "Poor";
                                        break;
                                }

                                if ($.trim(row.feedback) != "") {
                                    ratingLabel = "<span style='top: 0px;cursor:pointer;border-bottom: 1px solid #DFDFDF;' title='"+row.feedback+"'>"+ratingLabel+"</span>";
                                }

                                html += " (" + ratingLabel + ")";
                            }

                            return html;
                        }

                        return data;
                    }
                },
                { "data": "lastReply" },
                {
                    "data": "status",
                    className: 'text-center',
                    render: function (data, type, row) {
                        if (type === 'display') {
                            return "<span class='status-btn " + row.statusClass + "'>" + row.statusname + "</span>";
                        }

                        return data;
                    }
                },
                {
                    "data": "messagetype",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            return row.messagetypename;
                        }

                        return data;
                    }
                }
            ],
            "order": [[2, 'asc']]
        });

        $('#checkAll').on('click', function () {
            if (this.checked) {
                table.rows({page: 'current'}).select();
            } else {
                table.rows().deselect();
            }
        });

        $("[id^='tkt-']").click(function () {
            if ($(this).attr('disabled')) {
                return;
            }

            var id = $(this).attr('id');
            id = id.replace('tkt-', '');
            tickets.disableButtons();

            action = id;
            if (action == 'markspam') {
                action = 'mark as spam';
            }

            RichHTML.msgBox(
                clientexec.lang('Are you sure you want to % these tickets?', action),
                {
                    type: "yesno"
                },
                function (result) {
                    if (result.btn === clientexec.lang('Cancel') || result.btn === clientexec.lang('No')) {
                        tickets.enableButtons();
                        return;
                    }

                    tickets.performaction(id)
                }
            );
        });

        tickets.performaction = function (id) {
            var rowIds = table.getSelectedRows();

            switch (id) {
                case 'close':
                    var data = {
                        ids:       rowIds,
                        newstatus: -1
                    };

                    var url = 'index.php?fuse=support&controller=ticket&action=updateticketstatus';

                    break;
                case 're-open':
                    var data = {
                        ids:       rowIds,
                        newstatus: 1
                    };

                    var url = 'index.php?fuse=support&controller=ticket&action=updateticketstatus';

                    break;
                case 'markspam':
                    var data = {
                        ids: rowIds
                    };

                    var url = 'index.php?fuse=support&action=addemailasspam';

                    break;
                case 'delete':
                    var data = {
                        ids: rowIds
                    };

                    var url = 'index.php?fuse=support&controller=ticket&action=delete';

                    break;
                case 'merge':
                    var data = {
                        ids: rowIds
                    };

                    var url = 'index.php?fuse=support&controller=tickets&action=merge';

                    break;
            }

            $.ajax({
                url: url,
                type: 'POST',
                data:  data,
                success:  function (xhr) {
                    clientexec.parseResponse(xhr);
                    table.ajax.url(ajaxUrl);
                    table.ajax.reload();

                    if (typeof profile !== "undefined") {
                        setTimeout(function () {
                            profile.get_counts();
                        },1000);
                    }
                }
            });
        };

        table.on('select.dt deselect.dt', function() {
            tickets.disableButtons();

            var selectedRows = table.rows({ selected: true }).count();

            if (selectedRows > 0) {
                tickets.enableButtons();
            }
        });

        tickets.enableButtons = function () {
            const $dd = $('#ticketActions');
            const $actions = $dd.closest('.table-actions');
            const $pill = $actions.find('.pill');

            // Show all available actions
            $actions.find('.menu-item').removeClass('d-none');

            // Enable dropdown trigger
            clientexec.tableActions.setEnabled($pill, true);

            // Close if open to avoid stale UI
            clientexec.tableActions.closeDropdown($dd);
        };

        tickets.disableButtons = function () {
            const $dd = $('#ticketActions');
            const $actions = $dd.closest('.table-actions');
            const $pill = $actions.find('.pill');

            // Disable dropdown trigger
            clientexec.tableActions.setEnabled($pill, false);

            // Hide all actions
            $actions.find('.menu-item').addClass('d-none');

            // Close if open
            clientexec.tableActions.closeDropdown($dd);
        };
        tickets.disableButtons();

        $('#tickets-list tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                fetchRowDetails(row.data()).then(function (json) {
                    var expanderBody = "";
                    for (var i in json.logs) {
                        entry = json.logs[i];
                        if (typeof(entry) != "object") continue;

                        userText = entry.name;
                        privateText = "";
                        entry.msg = $("<div/>").html(entry.msg).text();
                        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>";
                            expanderBody += "<div>";
                            expanderBody += "<b>"+clientexec.lang("By")+":</b> "+userText+"&nbsp;&nbsp;<b>"+clientexec.lang("Date")+":</b> "+entry.date+privateText;
                            expanderBody += "<div style='padding-top:8px;'>"+entry.msg+"</div>";
                            expanderBody += "</div>";
                            expanderBody += "</div>";
                        }
                    }
                    row.child(expanderBody).show();
                    tr.addClass('shown');
                });
            }
        });

        function fetchRowDetails(row) {
            return new Promise((resolve, reject) => {
                $.get("index.php?action=getlastxticketmessages&fuse=support", { ticketid:row.id }, function(data) {})
                .done(resolve)
                .fail(reject);
            });
        }

        if (tickets.autorefresh > 0) {
            delay = tickets.autorefresh * 1000;
            setInterval(function() {
                table.ajax.reload();
            }, delay);
        }

        $('#inputTicketSearch').on('keyup', function(e){
            e.preventDefault();
            if (e.which == 13) {
                tickets.searchTroubleTickets();
            }
        });

        $('#inputIncludeClosed').on('change', function() {
            tickets.searchTroubleTickets();
        });
        $('#selectSearchType').on('change', function() {
            tickets.searchTroubleTickets();
        });


        $('#createNewFilter').on('click', function(e) {
            e.preventDefault();
            customFilterWin = new RichHTML.window({
                url: 'index.php?fuse=support&controller=ticketfilter&view=viewadd',
                actionUrl: 'index.php?fuse=support&action=create&controller=ticketfilter',
                title: clientexec.lang('Ticket Search'),
                showSubmit: true,
                size: 'modal-lg',
                onSubmit: function(response) {
                    var filterName = 'custom_' + response.filterID;
                    if (response.error == false) {
                        window.location.href = "index.php?fuse=support&view=viewtickets&controller=ticket&searchfilter="+filterName;
                    }
                }
            });
            customFilterWin.show();
        });

        $('.richwindow').on('shown.bs.modal', function() {
            RichHTML.window.resetSelect2Instances();
        });

        History.Adapter.bind(window,'statechange',function() {

            if (gView == "profiletickets") { return; }

            var State = History.getState();

            if (typeof(State.data.ticket_id) == "undefined") State.data.ticket_id = false;
            if (typeof(State.data.search_filter) == "undefined") State.data.search_filter = tickets.searchfilter;
            if (typeof(State.data.search_filter_name) == "undefined") State.data.search_filter_name = tickets.searchfiltername;
            if (typeof(State.data.search_customerid) == "undefined") State.data.search_customerid = tickets.searchcustomerid;
            if (typeof(State.data.search_filter_query) == "undefined") State.data.search_filter_query = "";
            if (typeof(State.data.search_filter_creationStart) == "undefined") State.data.search_filter_creationStart = "";
            if (typeof(State.data.search_filter_creationEnd) == "undefined") State.data.search_filter_creationEnd = "";
            if (typeof(State.data.search_filter_nameSearch) == "undefined") State.data.search_filter_nameSearch = "";
            if (typeof(State.data.search_filter_assignee) == "undefined") State.data.search_filter_assignee = "";

            if (State.data.search_filter_query != "" || State.data.search_filter_creationStart != '' || State.data.search_filter_creationEnd != '' ||
                    State.data.search_filter_nameSearch != '' || State.data.search_filter_assignee != '') {

                tickets.ticketState.customerid = 0;
                $.extend(tickets.ticketState, {
                    start:      0,
                    filter:     State.data.search_filter,
                    query:      State.data.search_filter_query,
                    searchtype: State.data.search_filter_searchType,
                    creationStart: State.data.search_filter_creationStart,
                    creationEnd: State.data.search_filter_creationEnd,
                    nameSearch: State.data.search_filter_nameSearch,
                    assignee: State.data.search_filter_assignee
                });
                $('#spanTicketListTableLabel').html(State.data.search_filter_name);
                table.ajax.reload(null, false);
            }
        });

        if (!tickets.back_to_profile) {
            tickets.populateTicketFilters(tickets.defaultFilterName, tickets.iscustom, true);
        }

    });
</script>