var
  token = $('body').data('token'),
  $form = $('#js-form-account');

$form.validate({
  onfocusout: function (element) {
    $(element).valid();
  },
  onkeyup: function (element) {
    if ($(element).valid()) {
      $(element).removeClass('form-error');
      $(element).siblings('span.form-error').remove();
    }
  },
  onsubmit: true,
  errorElement: 'span',
  errorClass: 'form-error',
  validClass: 'form-success',
  rules: {}
});

$('.js-modal-save').on('click', function (e) {

  if ($form.valid()) {
    $('.warning, .error').remove();
    $('.field-entry').removeClass('border-error');
    apply();
  }

});


function apply() {

  $.ajax({
    url: 'index.php?route=module/skyhub/account/apply&token=' + token,
    dataType: 'json',
    type: 'POST',
    data: $('#js-form-account').serialize(),
    beforeSend: function () {
      $('.js-modal-save').addClass('btn-loading');
      $('.js-modal-save').attr('disabled', true);
      $('#modal-account-b2w').addClass('js-adm-modal-overlay-no-close');
    },
    success: function (json) {

      if (json['error']) {
        $.each(json['error'], function (index, value) {
          $('input[name='+index+']').addClass('border-error');
          $('input[name='+index+']').closest('.flex').append('<span class="error">' + value + '</span>');
        });
        $('.js-modal-save').removeClass('btn-loading');
        $('#modal-account-b2w').removeClass('js-adm-modal-overlay-no-close');
      }

      $('.js-contant-message').html('');

      if(json['warning']){
        $('.js-adm-modal-close').trigger('click');
        $('.js-contant-message').prepend('<div class="text-small text-error background-error padding-medium rounded-x-small full-width">'+json['warning']+'</div>');
      }

      if(json['success']){
        $('.js-adm-modal-close').trigger('click');
        $('.js-contant-message').prepend('<div class="text-small text-success background-success padding-medium rounded-x-small full-width">'+json['success']+'</div>');
      }

    }
  });

}