wpj.domUtils.initOpeners();

wpj.onReady.push(function() {
   const $form = $('form[data-form="user"]');

   if ($form.length) {
      $form
         .bootstrapValidator({
            feedbackIcons: {
               valid: 'fa fa-check fc fc-check',
               invalid: 'fa fa-remove fc fc-remove',
               validating: 'fa fa-refresh fc fc-refresh'
            }
         })
         .on('submit', function() {
            /* delete all inputs in unchecked openers */
            $form
               .find('[data-opener]')
               .not(':checked')
               .each(function() {
                  $($(this).attr('data-opener'))
                     .find('input')
                     .val('');
               });

            const err = $('.has-error').first();

            if (err.length && !wpj.domUtils.isInView(err)) {
               wpj.domUtils.scrollTo(err);
            }

            return true;
         });

      /* Reset validace u poli ktera jsou skrtyta.
         Defaultne validuji jen viditelne polozky, reset poli
         je hlavne kvuli enablovani submit buttonu. */

      $form.on('change', '[data-opener]', function() {
         const $this = $(this);

         if ($this.prop('checked') === false) {
            const target = $this.attr('data-opener');

            $(target)
               .find('input')
               .each(function() {
                  $form.data('bootstrapValidator').resetField($(this).attr('name'));
               });
         }
      });

      if ($('.alert').length && !wpj.domUtils.isInView($('.alert'))) {
         wpj.domUtils.scrollTo($('.alert'));
      }

      $form.on('click', '.clear-alt-address', function() {
         const target = $(this)
            .siblings('input[type=checkbox]')
            .attr('data-opener');
         $(target)
            .find('input')
            .val('');
      });
   }

   $('body').on('countryChanged', function(e, data) {
      if (data === undefined && e.detail) {
         data = e.detail;
      }

      const $state_field = $('[data-' + data['instance'] + '-state-field]');
      if ($state_field.length) {
         if (data['country'] === 'IT') {
            $state_field.show();
         } else {
            $state_field.hide();
            $state_field.find('input').val('');
         }
      }
   });
});
