jQuery(document).ready(function ($) {
    /**
     * Ajax search product request
     * @type {*|jQuery|HTMLElement}
     */
    var _nonce = $('input[name="_dejst_nonce"]').val();
    var ajaxResult = $('.dejst-product-title-wrapper .dejst-ajax-result');
    var searchInput = $('.dejst-product-title-wrapper input[type=text]');
    var loader = $('.dejst-product-title-wrapper .dejst-loader');
    var $continue = true;
    searchInput.on('input', function () {
        var $this = $(this);
        var searchTerm = $this.val();
        if (searchTerm.length < 2) {
            $continue = false;
            ajaxResult.fadeOut();
            loader.fadeOut();
            return false;
        } else {
            $continue = true;
        }

        loader.fadeIn();

        $.ajax({
            url: dejst_data.ajax_url,
            type: 'post',
            dataType: 'json',
            timeout: 20000,
            data: {
                action: 'dejst_search',
                searchTerm: searchTerm,
                _dejst_nonce: _nonce
            },
            success: function (response) {
                if (response._result !== '' && $continue) {
                    ajaxResult.html(response._result).fadeIn();
                } else {
                    ajaxResult.empty().hide();
                }
                loader.fadeOut();
            },
            error: function () {
                ajaxResult.fadeOut();
                loader.fadeOut();
            }
        });
    });

    /**
     * Show product title in input
     */
    $(document).on('click', '.dejst-ajax-result li', function (e) {
        e.stopPropagation();
        var $this = $(this);
        var productID = parseInt($this.data('id'));
        var productTitle = $this.text();

        $('#product-id').val(productID);
        searchInput.val(productTitle);
        ajaxResult.fadeOut();
    });
    $('body').click(function () {
        setTimeout(function () {
            ajaxResult.empty().hide();
            loader.fadeOut();
        }, 500);
    });

    /**
     * Show file name when file select form input[type="file"]
     */
    $('#ticket-file').change(function () {
        var $this = $(this);
        var file = $this[0].files[0];
        $this.next('label').text(file['name']);
    });
});