{% block scripts_before %}{% endblock %}


{% if tipo_posterior is defined and tipo_posterior %}
  <div class="column-12">
    <div class="buttons column-12">
      <button id="button-confirm-posterior"  class="btn-default btn-large" data-loading-text="{{text_processando}}">
        <span>{{button_pagamentopos}}</span>
      </button>
    </div>
  </div>
{% else %}

{% block initForm %}
  <form id="form-{{ paymentName }}">
{% endblock %}

	<div class="additional-info padding-large">

    <span class="visible-block text-large text-bold text-dark">Informações do cartão </span>

    <label class="field field-medium top-margin-medium">
      <span class="field-label">Número do cartão</span>
      <input type="text" class="field-entry" name="card_ccno" id="card_ccno" placeholder="Ex.: 1234 5678 9101" required>
    </label>

    <label class="field field-medium top-margin-medium">
      <span class="field-label">Nome</span>
      <input type="text" class="field-entry" name="card_name" id="card_name" placeholder="Ex.: João da Silva" required>
    </label>

    <div class="flex background-gray padding-small top-margin-medium">
      {% for key, debit_card in debit_cards %}
        <label>
          <input type="radio" class="radioimg-input card_cctype" name="card_cctype" id="card_cctype" value="{{ debit_card.descricao|lower }}" disabled="disabled">
          <img class="radioimg-img radioimg_creditcard_cctype visible-block" src="image/cielo/{{ debit_card.descricao|lower|replace({' ' : '-'}) }}.jpg">
        </label>
      {% endfor %}
    </div>

    <div class="flex nowrap-xs top-margin-large">
      <label class="field field-medium right-margin-x-small">
        <span class="field-label">Código de Segurança</span>
        <img class="field-icon field-icon-right vertical-padding-small right-margin-small" src="catalog/view/theme/vista/image/cvd.png" alt="Código de Segurança">
        <input type="text" class="field-entry" name="card_cccvd" id="card_cccvd" placeholder="Ex: 123" required>
      </label>
      <label class="field field-medium left-margin-x-small">
        <span class="field-label">Vencimento</span>
        <input type="text" class="field-entry mask-date-card" name="expire" id="expire" placeholder="__/____" required>
      </label>
    </div>

    {% if captcha_tpl %}
    <div class="flex nowrap-xs top-margin-large">
      {{captcha_tpl}}
    </div>
    {% endif %}

    <button id="button-confirm" type="button" class="btn-default btn-large btn-full top-margin-large" data-loading-text="Aguarde Processando...">
      <span>Efetuar Pagamento</span>
    </button>
  </div>

</form>
{% endif %}

<div class="load load-block">
  <div class="load load-block-image">
    <img src="assets/img/loading-black.svg" alt="loading">
  </div>
</div>

{% block scripts %}
  <script type="text/javascript" src="catalog/view/javascript/jquery.payment/jquery.payment.js"></script>
  <script>
  var paymentName = '{{ paymentName }}',
    paymentRoute = '{{ paymentRoute }}';

    window.waitEvent('scripts_document', function () {

      $.fn.toggleInputError = function (erred) {
        $(this).closest('.form-group').toggleClass('has-error', erred);
        return this;
      };

      $('#card_ccno').payment('formatCardNumber');
      $('#card_cccvd').payment('formatCardCVC');

      {% if not ambiente_teste %}
        blockCopyPaste('card_ccno');
        blockCopyPaste('card_name');
        blockCopyPaste('card_cccvd');
      {% endif %}

      function blockCopyPaste(field) {
        $('#'+field).bind("cut copy paste", function(e) {
          e.preventDefault();
          $('#'+field).bind("contextmenu", function(e) {
            e.preventDefault();
          });
        });
      }

      function parcelas($THIS, event) {
          $('#parcelas').html('');
          $('.error').remove();

          var cardType = event.type == 'blur' ? $.payment.cardType($THIS.val()) : $THIS.closest('label').find('.card_cctype').val();
            if (( $("#form-cielo_api_credito").length )&&(cardType == 'mastercard')){
              cardType = 'master';
            }

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

            var radioimgSelect = '".radioimg-input[value="' + cardType + '"]"';

            if ($(radioimgSelect).length > 0) {

                $('#card_ccno').removeClass('form-error');
                $(radioimgSelect).prop('checked', true);
                $(radioimgSelect).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);
                }

                var
                  data = {};

                data['bandeira'] = cardType;

              $('#button-confirm')
                .removeAttr('disabled')
                .removeClass('btn-loading');

            } else if (typeof cardType === 'string') {

                $('#card_ccno')
                  .removeClass('form-success')
                  .addClass('form-error')
                  .after('<span class="form-error error">Não trabalhamos com cartões da bandeira ' + cardType + '</span>');
            }
      }

      $('#card_ccno').on('blur', function (event) {
          parcelas($(this), event);
      });

      // $('.radioimg-img').on('click', function(event){
      //     parcelas($(this), event);
      // });

      $('#button-confirm').on('click', function () {


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

        var $form = $(this).closest('form');

        $form.submit(function (e) {
          e.preventDefault();
        });
        $form.trigger('submit');

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

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


        var data = $form.serializeObject(true);
        cardType = $.payment.cardType(data['card_ccno']);
        if (( $("#form-cielo_api_credito").length )&&(cardType == 'mastercard')){
          cardType = 'master';
        }
        var  mesAno = data['expire'].split('/'),
          mes = mesAno[0],
          ano = mesAno[1],
          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 radioimgSelect = '".radioimg-input[value="' + cardType + '"]"';

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

        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;
          }
        }

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

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

        if ($(radioimgSelect).length >= 0) {

          {% block script_before_send %}{% endblock %}

          data['qtd_parcela'] = $('select[name=formaPagamento] option:selected').data('qtd-parcela');
          data['cidade'] = $form.find('#codigo_municipio option:selected').text();

          $.ajax({
            type: 'POST',
            url: 'index.php?route=payment/' + paymentRoute,
            data: data,
            dataType: 'json',
            beforeSend: function () {
              $('#button-confirm').attr('disabled', true);
              $('.load').css('display', 'block');
            },
            complete: function () {
              $('#button-confirm').attr('disabled', false);
              $('.load').css('display', 'none');
            },
            success: function (json) {

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

              if (json['error']) {

                if (json['error']['retorno_api']){

                  notificationMsg(json['error']['retorno_api']['mensagem'],'warning');

                }

                $.each(json['error'], function (index, value) {
                  $('input[name=' + index + ']').after('<span class="form-error text-small">' + value + '</span>');
                  $('select[name=' + index + ']').after('<span class="form-error text-small">' + value + '</span>');
                  if (index == 'g-recaptcha'){
                    $('#' + index).parent().after('<span class="text-small text-error visible-block text-margin-x-small form-error">' + value + '</span>');
                  }

                  if (index == 't_e_limiter_ip' || index == 't_e_limiter' ){
                    notificationMsg(value, 'error');
                    location.reload();
                  }

                });
              }

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

            },
            error: function (request, status, error) {


              let json = JSON.parse(request.responseText);

              if (json['error']) {

                if (json['error']['retorno_api']){
                  notificationMsg(json['error']['retorno_api']['mensagem'],'warning');

                }

                $.each(json['error'], function (index, value) {
                  $('input[name=' + index + ']').after('<span class="form-error text-small">' + value + '</span>');
                  $('select[name=' + index + ']').after('<span class="form-error text-small">' + value + '</span>');
                  if (index == 'g-recaptcha'){
                    $('#' + index).parent().after('<span class="text-small text-error visible-block text-margin-x-small form-error">' + value + '</span>');
                  }

                  if (index == 't_e_limiter_ip' || index == 't_e_limiter' ){
                    notificationMsg(value, 'error');
                    location.reload();
                  }

                });
              }
              console.log(JSON.parse(request.responseText));
            }
          });
        } else {
          $('#card_ccno').after(
            '<span class="error">Não trabalhamos com cartões da bandeira ' + cardType + '</span>'
          );
        }
      });

      $('#button-confirm-posterior').on('click', function() {

          $.ajax({
              type: 'POST',
              url: 'index.php?route=payment/'+paymentName+'/pagarPosteriormente&order_id={{idorder}}',
              dataType : 'json',

              beforeSend: function() {
                  $('#button-confirm-posterior').attr('disabled', true);
                  $('.load').css("display","block");

              },
              complete: function() {
                  $('#button-confirm-posterior').attr('disabled', false);
                  $('.load').css("display","none");
              },
              success: function(json) {
                location.href = json['redirect'];
              },
              error: function (request, status, error) {
                console.log('Erro ao confirmar pagamento posterior');
                console.log(request.responseText);
              }
          });
      });

    });
  </script>
{% endblock %}