if (document.readyState === 'complete') {
  init();
} else {
  document.addEventListener('DOMContentLoaded', function() {
    init();
  });
}

function init() {
  var BtnSaveUser = document.querySelector('.js-userInfo-save'),
    BtnCancelUser = document.querySelector('.js-userInfo-cancel');

  BtnSaveUser.addEventListener('click', function() {
    saveCheck(usercheck.Tp_Confirmed, this);
  });

  BtnCancelUser.addEventListener('click', function() {
    saveCheck(usercheck.Tp_NotDisplay, this);
  });
}

function saveCheck(confirmed, $element) {
  $element.classList.add('btn-loading');

  var warning = document.querySelector('.warning'),
    container = document.getElementById('ConfirmUserInfo'),
    input = container.querySelector('[name=email]'),
    error = container.querySelector('.error'),
    dados = new FormData();

  dados.append('confirmed', confirmed);
  dados.append('email', input.value);
  input.classList.remove('border-error');

  if (error !== null) {
    error.remove();
  }

  if (warning !== null) {
    warning.remove();
  }

  $.ajax({
    url: 'index.php?route=common/user/save&token=' + document.body.getAttribute('data-token'),
    type: 'POST',
    data: dados,
    processData: false,
    contentType: false,
  })
    .done(function(json) {
      if (json['warning']) {
        container.insertAdjacentHTML('beforebegin', '<div class="warning">' + json['warning'] + '</div>');
      }

      if (json['email']) {
        input.classList.add('border-error');
        input.insertAdjacentHTML('afterend', '<span class="error">' + json['email'] + '</span>');
      }

      $element.classList.remove('btn-loading');

      if (json['reload']) {
        location.reload();
      }

      if (json['success']) {
        var $success = '<div class="js-adm-modal-container padding-x-large text-center">';
        $success += '<i class="fas fa-envelope-square text-success bigger-text-x-large visible-block"></i>';
        $success +=
          '<span class="text-dark text-medium visible-block top-margin-small"><b>Seu email foi <br>salvo com sucesso!</b></span>';
        $success +=
          '<button class="btn-default btn-medium btn-success top-margin-large horizontal-margin-x-large js-adm-modal-close" type="button">';
        $success += '<span>Concluir</span>';
        $success += '</button>';
        $success += '</div>';
        $(this).modalFutura({
          dataModalId: 'check-info-user',
          appendModal: $success,
        });
      }
    })
    .fail(function() {
      console.log('error');
    })
    .always(function() {
      // console.log("complete");
    });
}
