var environment = document.querySelector('#checkout-confirm [data-environment]').getAttribute('data-environment');

var dataEnvironment = '';
if (environment) {
  dataEnvironment = JSON.parse(environment);
}

$('#expire').mask('99/9999');
$('#creditcard_ccno').payment('formatCardNumber');
$('#creditcard_cccvd').payment('formatCardCVC');

$('#creditcard_ccno').blur(function() {
  var cardType = $.payment.cardType($(this).val());

  $('#creditcard_ccno')
    .closest('.ftr-field')
    .removeClass('error');
  $('#creditcard_ccno')
    .closest('.ftr-field')
    .find('.ftr-field__error')
    .remove();

  if (cardType) {
    var data = {};
    data['bandeira'] = cardType;

    if ($('.ftr-js-flag-card[value=' + cardType + ']').length == 0) {
      $('#creditcard_ccno')
        .closest('.ftr-field')
        .addClass('error');
      $('#creditcard_ccno + .ftr-field__text').after(
        '<span class="ftr-field__error">Não trabalhamos com cartões da bandeira ' + cardType + '</span>'
      );
      return;
    }

    if ($(this).val().length == 19) {
      $('.ftr-js-flag-card[value=' + cardType + ']').prop('disabled', false);

      if (cardType == 'amex') {
        $('#creditcard_cccvd').attr('maxlength', 4);
      } else {
        if ($('#creditcard_cccvd').val().length == 4) {
          $('#creditcard_cccvd').val('');
        }
        $('#creditcard_cccvd').attr('maxlength', 3);
      }
    }

    if ($(this).val().length == 19) {
      $.ajax({
        url: 'index.php?route=payment/pagseguro_api/parcelamento',
        type: 'GET',
        cache: false,
        dataType: 'html',
        data: data,
        beforeSend: function() {
          $('.ftr-loading-bar').removeClass('ftr-none');
        },
        complete: function() {
          $('.ftr-loading-bar').addClass('ftr-none');
        },
        success: function(data) {
          $('#parcelas').html(data);
        },
      });
    }
  } else {
    $('.ftr-js-flag-card:not(:disabled)').prop('disabled', true);
  }
});

$('#checkout-confirm').on('submit', function(e) {
  if (!$('#pagseguro_api-credit_card').prop('checked')) {
    return;
  }

  e.preventDefault();

  var $this = $(this).find('.ftr-steps__button'),
    $form = $('#form-pagseguro_api'),
    mesAno = $('#expire')
      .val()
      .split('/'),
    data = $form.serializeObject(),
    mes = mesAno[0],
    ano = mesAno[1],
    cardType = $.payment.cardType($('#creditcard_ccno').val()),
    validation = [
      {
        name: 'creditcard_ccno',
        function: 'validateCardNumber',
        param: [data['creditcard_ccno']],
        error: 'Número de Cartão Inválido',
      },
      {
        name: 'creditcard_cccvd',
        function: 'validateCardCVC',
        param: [data['creditcard_cccvd'], cardType],
        error: 'CSV Inválido',
      },
      {
        name: 'expire',
        function: 'validateCardExpiry',
        param: [mes, ano],
        error: 'Data de Vencimento Inválida',
      },
    ];

  var $formerror = $form.find('span.form-error');

  if ($formerror.length > 0) {
    $(window).scrollTop(
      $($formerror[0])
        .parent('label')
        .offset().top
    );
    return false;
  }

  for (var i = 0; i < validation.length; i++) {
    var validate = validation[i];
    $('#' + validate.name).removeClass('form-error');
    if (!$.payment[validate.function].apply($.payment, validate.param)) {
      $('#' + validate.name).after('<span class="form-error">' + validate.error + '</span>');
      notificationMsg(validate.error, 'error');
      return false;
    }
  }

  data['qtd_parcela'] = $('input[name=formaPagamento]').val();
  data['cidade'] = $form.find('#codigo_municipio').val();

  let card = PagSeguro.encryptCard({
    publicKey: atob(data['creditcard_public_key']),
    holder: data['creditcard_name'],
    number: data['creditcard_ccno'].replace(/\s/g, ''),
    expMonth: data['expire'].substring(0, 2),
    expYear: data['expire'].substring(3, 7),
    securityCode: data['creditcard_cccvd']
  });

  data['encryptedCard'] = card.encryptedCard;

  $('span.form-error').remove();

  $.ajax({
    type: 'POST',
    url: 'index.php?route=payment/pagseguro_api/pay_credit_card',
    data: data,
    dataType: 'json',
    beforeSend: function() {
      $this.prop('disabled', true);
      $('.ftr-loading-bar').removeClass('ftr-none');
    },
    complete: function() {
      $this.prop('disabled', false);
      $('.ftr-loading-bar').addClass('ftr-none');
    },
    success: function(json) {
      if (json['error']) {
        $('.ftr-field').removeClass('error');
        $('.ftr-field__error').remove();

        $.each(json['error'], function(index, value) {
          $('input[name=' + index + ']')
            .closest('.ftr-field')
            .addClass('error');
          $('input[name=' + index + ']  + .ftr-field__text').after(
            '<span class="ftr-field__error">' + value + '</span>'
          );
          notificationMsg(value, 'error');
          if (index == 't_e_limiter_ip' || index == 't_e_limiter'){
            setTimeout(function (e){
              location.href = ('index.php?route=account/logout');
            },5000)
          }
        });

        return;
      }

      if (json['redirect']) {
        location.href = json['redirect'];
      }
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(xhr.responseText);
    },
  });
});
