var dataPublicKey = document.querySelector('[data-public-key]').getAttribute('data-public-key');

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

$('#creditcard_ccno').blur(function(e) {
  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/wirecard/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) {
  e.preventDefault();
  if (!$('#wirecard-credit_card').prop('checked')) {
    return;
  }

  var $this = $(this).find('.ftr-steps__button'),
    $form = $('#form-wirecard'),
    mesAno = $('#expire')
      .val()
      .split('/'),
    data = $form.serializeObject(),
    mes = mesAno[0],
    ano = mesAno[1],
    cardType = $.payment.cardType($('#creditcard_ccno').val()),
    cc = new Moip.CreditCard({
      number: $('input[name=creditcard_ccno]').val(),
      cvc: $('input[name=creditcard_cccvd]').val(),
      expMonth: mes,
      expYear: ano,
      pubKey: dataPublicKey,
    }),
    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>');
      return false;
    }
  }

  if (cc.isValid()) {
    data['encrypted_value'] = cc.hash();
  }

  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/wirecard/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');
        });

        return;
      }

      if (json['redirect']) {
        location.href = json['redirect'];
      }
    },
  });
});
