$("#rede_expire").mask("99/9999");

$('#rede_creditcard_ccno').payment('formatCardNumber');
$('#rede_creditcard_cccvd').payment('formatCardCVC');

var dataInfo = $('#rede_creditcard_container').data('info');

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

    if (cardType) {

      if ($(this).val().length == 19) {
        $('.ftr-js-flag-card[value=' + cardType + ']').prop('disabled', false);
        if (cardType == 'amex') {
          $('#rede_creditcard_cccvd').attr("maxlength",4);
        } else {
          if ($("#rede_creditcard_cccvd").val().length == 4) {
            $("#rede_creditcard_cccvd").val("");
          }
          $('#rede_creditcard_cccvd').attr("maxlength",3);
        }
      }

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

  $('#checkout-confirm').on('submit', function(e) {

    e.preventDefault();

    var $this = $(this).find('.ftr-steps__button'),
      $form = $('#rede_creditcard_container'),
      mesAno = $('#rede_expire')
        .val()
        .split('/'),
      data = $('#rede_creditcard_container').find('select, textarea, input').serializeObject(),
      mes = mesAno[0],
      ano = mesAno[1],
      cardType = $.payment.cardType($('#rede_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();

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

    $.ajax({
      type: 'POST',
      url: 'index.php?route=payment/rede_credito/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);
      },
    });
  });
