{% block scripts_before %}{% endblock %}

<form id="form-{{ paymentName }}">

  {{ payment_address }}

</form>

<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>
    var paymentName = '{{ paymentName }}',
      paymentRoute = '{{ paymentRoute }}';

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

      $('#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);

        if (typeof aditionalData !== 'undefined') {
          // aditionalData é definida em outro template que extende esse
          // por herança do twig
          Object.assign(data, aditionalData);
        }

        data['cidade'] = $form.find('#codigo_municipio option:selected').text();
        console.log(paymentRoute);
        $.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']) {
              $.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) {
            console.log(request.responseText);
          }
        });

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