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

$('#cielo_api_creditcard_ccno').payment('formatCardNumber');
$('#cielo_api_creditcard_cccvd').payment('formatCardCVC');

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

if (dataInfo.tipo_posterior) {
  $('#checkout-confirm').on('submit', function(e) {
    e.preventDefault();
    var $this = $(this).find('.ftr-steps__button');
    $.ajax({
      type: 'POST',
      url: 'index.php?route=payment/cielo_api_credito/pagarPosteriormente&order_id=' + dataInfo.idorder,
      dataType : 'json',
      beforeSend: function() {
        $this.attr('disabled', true);
        $('.ftr-loading-bar').removeClass('ftr-none');
      },
      complete: function() {
        $this.attr('disabled', false);
        $('.ftr-loading-bar').addClass('ftr-none');
      },
      success: function(json) {
        location = dataInfo.continue;
      },
      error: function(json) {
        console.log(json);
      }
    });
  });
}

if (dataInfo.tipo_checkout) {
  $('#cielo_api_creditcard_ccno').blur(function(e) {
    var cardType = $.payment.cardType($(this).val());

    if (cardType) {
      if (cardType == 'mastercard') {
        cardType = 'master';
      }

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

      if ($(this).val().length == 19) {
        $.ajax({
          url: 'index.php?route=payment/cielo_api_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) {
            $('#cielo_api_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 = $('#cielo_api_creditcard_container'),
      mesAno = $('#cielo_api_expire')
        .val()
        .split('/'),
      data = $('#cielo_api_creditcard_container').find('select, textarea, input').serializeObject(),
      mes = mesAno[0],
      ano = mesAno[1],
      cardType = $.payment.cardType($('#cielo_api_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/cielo_api_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);
      },
    });
  });

}
