/**
 *
 * @type {Element}
 */

var $ = require("jquery");

$(function () {
    window.searchAnchor = $('table tfoot tr td a#searchAnchor');
    window.searchInputs = $('table tfoot tr td input[name]');

    function FilterBuilder() {
        let _this = this;

        this.values = {};
        this.getFilterUrl = function () {

            let isFirst = true;
            let url = location.pathname;

            $.each(this.values, function (col, val) {
                if (isFirst) {
                    isFirst = false;
                    url += "?";
                } else {
                    url += "&";
                }
                url += col + "=*" + val + "*";
            });

            return url;
        };
        $.each(window.searchInputs, function(i, input) {
            if (input.value !== '') {
                console.log(input);
                _this.values[input.name] = input.value;
            }
        });

    }

    window.filterBuilder = new FilterBuilder();

    window.searchInputs.keyup(function () {
        if (this.value === '') {
            delete window.filterBuilder.values[this.name];
        } else {
            window.filterBuilder.values[this.name] = this.value;
        }
        console.log(window.filterBuilder.values);
    });

    window.searchInputs.keypress(function (e) {
        if (e.which === 13) {
            window.searchAnchor.trigger("click");
            return false;    //<---- Add this line
        }
    })

    window.searchAnchor.click(function () {
        //console.log("clicked!");
        let url = window.filterBuilder.getFilterUrl();

        window.location = url;
    });
});