/**
 * frontend.js
 *
 * @author Your Inspiration Themes
 * @package YITH WooCommerce Ajax Search
 * @version 1.1.1
 */

jQuery(document).ready(function ($) {
    "use strict";

    var el = $('.yith-s'),
        search_button = $('#yith-searchsubmit'),
        min_chars = el.data('min-chars');

    search_button.on('click', function(){
        var form = $(this).closest('form');
        if( form.find('.yith-s').val()==''){
            return false;
        }
        return true;
    });

    if( el.length == 0 ) el = $('#yith-s');

    el.each(function () {
        var $t = $(this),
            append_to = ( typeof  $t.data('append-to') == 'undefined') ? $t.closest('.yith-ajaxsearchform-container') : $t.data('append-to');

        $t.yithautocomplete({
            minChars        : min_chars,
            appendTo        : append_to,
            triggerSelectOnValidInput: false,
            serviceUrl      : shrk.ajax.ajaxurl + '?action=yith_ajax_search_products',
            onSearchStart   : function () {
                $t.closest('form').addClass('loading');
            },
            onSelect        : function (suggestion) {
                if (suggestion.id != -1) {
                    window.location.href = suggestion.url;
                }
            },
            onSearchComplete: function () {
                $t.closest('form').removeClass('loading');
            }
        });
    });
});


