(function () {
    window.initStagTableFilters = function () {

        const debounce = (func, wait) => {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        };

        var returnedFunction = debounce(function (_elem) {
            let term = $.trim(_elem.val()).toLowerCase(),
                columnIndex = _elem.closest('td, th').index(),
                trs = _elem.closest('table').find('tbody').find('tr');
            trs.removeClass('stag-filter-hide');
            trs.find('.stag-filter-highlight').replaceWith(function() {
                return $(this).text();
            });
            _elem.closest('td, th').siblings().find('input[stag-table-filter]').val('');
            if(!!term) {
                trs.each(function () {
                    let td = $(this).find('td:eq(' + columnIndex + ')'),
                        text = td.text();
                    if (text.toLowerCase().indexOf(term) === -1) {
                        $(this).addClass('stag-filter-hide');
                    }
                    /*else {
                        let re = new RegExp('(' + term + ')', 'ig');
                        text = text.replace(re, '<span class="stag-filter-highlight">$&</span>');
                        td.html(text);
                    }*/
                });
            }
        }, 100);

        function applyFilter(_elem) {
            returnedFunction(_elem);
        }

        $(document)
            .off('input.stag-table-filter').on('input.stag-table-filter', 'input[stag-table-filter]', function() { applyFilter($(this)); })
            .off('change.stag-table-filter').on('change.stag-table-filter', 'input[stag-table-filter]', function() { applyFilter($(this)); })
            .off('paste.stag-table-filter').on('paste.stag-table-filter', 'input[stag-table-filter]', function() { applyFilter($(this)); })

        $(document)
            .off('keyup.stag-table-filter')
            .on('keyup.stag-table-filter', 'input[stag-table-filter]', function(_e) {
                if(_e.which === 27) {
                    if(!isEventConsumed(e)) {
                        if ($(this).val() !== '') {
                            $(this).val('');
                            applyFilter($(this));
                            markEventAsConsumed(_e);
                            return false;
                        }
                    }
                }
            })
    }
    addMCInitializer('stag-table-filter', window.initStagTableFilters);
})();
