{% 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">

    {{ payment_address }}

    {% if  payment_address%}
      <hr class="vertical-margin-large">
    {% endif %}

    <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="creditcard_ccno" id="creditcard_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="creditcard_name" id="creditcard_name" placeholder="Ex.: João da Silva" required>
    </label>

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

    <div id="parcelas"></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="creditcard_cccvd" id="creditcard_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;
      };

      $('#creditcard_ccno').payment('formatCardNumber');
      $('#creditcard_cccvd').payment('formatCardCVC');

      {% if not ambiente_teste %}
        blockCopyPaste('creditcard_ccno');
        blockCopyPaste('creditcard_name');
        blockCopyPaste('creditcard_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('.creditcard_cctype').val();
            if (( $("#form-cielo_api_credito").length )&&(cardType == 'mastercard')){
              cardType = 'master';
            }
            var radioimgSelect = '".radioimg-input[value="' + cardType + '"]"';

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

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

                var
                  data = {};

                data['bandeira'] = cardType;

                $.ajax({
                    url: 'index.php?route=payment/' + paymentName + '/parcelamento',
                    type: 'GET',
                    cache: false,
                    data: data,
                    dataType: 'html',
                    beforeSend: function () {
                        $('#button-confirm')
                            .prop('disabled', true)
                            .addClass('btn-loading');
                    },
                    complete: function () {
                        $('#button-confirm')
                            .removeAttr('disabled')
                            .removeClass('btn-loading');
                    },
                    success: function (html) {
                        $('#parcelas').html(html);
                    }
                });
            } else if (typeof cardType === 'string') {
                $('#parcelas').html('');
                $('#creditcard_ccno')
                  .removeClass('form-success')
                  .addClass('form-error')
                  .after('<span class="form-error error">Não trabalhamos com cartões da bandeira ' + cardType + '</span>');
            }
      }

      $('#creditcard_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['creditcard_ccno']);
        if (( $("#form-cielo_api_credito").length )&&(cardType == 'mastercard')){
          cardType = 'master';
        }
        var  mesAno = data['expire'].split('/'),
          mes = mesAno[0],
          ano = mesAno[1],
          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 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');
                    setTimeout(() => {
                      location.reload();
                    }, 15000);
                  }

                });
              }

              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');
                    setTimeout(() => {
                      location.reload();
                    }, 15000);
                  }

                });
              }
              console.log(JSON.parse(request.responseText));
            }
          });
        } else {
          $('#creditcard_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 %}