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

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

$('#expire').mask('99/9999');
$('#card_ccno').payment('formatCardNumber');
$('#card_cccvd').payment('formatCardCVC');

$('#card_ccno').blur(function() {

  var cardType = $.payment.cardType($(this).val());

  $('#card_ccno')
    .closest('.ftr-field')
    .removeClass('error');
  $('#card_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) {
      console.log('erros');
      $('#card_ccno')
        .closest('.ftr-field')
        .addClass('error');
      $('#card_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') {
        $('#card_cccvd').attr('maxlength', 4);
      } else {
        if ($('#card_cccvd').val().length == 4) {
          $('#card_cccvd').val('');
        }
        $('#card_cccvd').attr('maxlength', 3);
      }
    }

  } else {
    $('.ftr-js-flag-card:not(:disabled)').prop('disabled', true);
  }
});

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

  var $this = $(this).find('.ftr-steps__button'),
    $form = $('#form-getnet'),
    mesAno = $('#expire')
      .val()
      .split('/'),
    data = $form.serializeObject(),
    mes = mesAno[0],
    ano = mesAno[1],
    cardType = $.payment.cardType($('#card_ccno').val()),
    validation = [
      {
        name: 'card_ccno',
        function: 'validateCardNumber',
        param: [data['card_ccno']],
        error: 'Número de Cartão Inválido',
      },
      {
        name: 'card_cccvd',
        function: 'validateCardCVC',
        param: [data['card_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();

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

  $.ajax({
    type: 'POST',
    url: 'index.php?route=payment/getnet/pay_debit',
    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) {
      console.log(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']) {
        console.log( json['redirect']);
        location.href = json['redirect'];
      }
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(xhr.responseText);
    },
  });
});
