var Wick = window.Wick || {};

Wick.ClearInput = {
  el: {
    $btnClear: $('[data-clearable] .btn--clear'),
    formRow: '.form-row',
    formTag: 'form',
    $clearableInput: $('[data-clearable]'),
  },
  clearInputField () {
    let $formTag = $(this).closest(Wick.ClearInput.el.formTag)
    let $formRow = $(this).closest(Wick.ClearInput.el.formRow);
    let $inputField = $formRow.length > 0 ? $formRow.find('input') : $formTag.find('input');

    $inputField.val('').focus();
    Wick.ClearInput.checkVisibilityOfClearButton(this, $inputField);
    $(document).trigger('clearInput', [$formTag]);
  },
  checkVisibilityOfClearButton (currentBtnClear, el) {
    $(currentBtnClear).toggleClass('d-block', el > 0);
  },
  init () {
    Wick.ClearInput.el.$btnClear.on('click', Wick.ClearInput.clearInputField);
  }
}

$(document).ready(function () {
  if (!Wick.ClearInput.el.$clearableInput.length) {
    return;
  }

  Wick.ClearInput.init();
});
