$('.ftr-steps__step').each(function(index, el) {
  var p = $('<p>'),
    button = $('<button>'),
    container = $('<div>');

  p.text('Etapa ' + (index + 1) + ' de ' + $('.ftr-steps__step').length);
  p.addClass('ftr-text--grey ftr-text--xs ftr-text--center ftr-in-space--m');
  button.attr('type', 'button');
  button.addClass('ftr-steps__button ftr-btn ftr-background--primary ftr-js-ripple-effect ftr-h--full');
  button.text('Próxima etapa');
  container.append(p, button);

  if ($(this).attr('id') == 'checkout-confirm' || $(this).attr('id') == 'checkout') {
    $(this)
      .find('.ftr-steps__inner')
      .css({
        'padding-bottom': '112px',
        'margin-bottom': '-112px',
      });
    container.css({
      padding: '16px 8px',
    });
  }

  $(this)
    .find('.ftr-steps__content')
    .append(container);
});

$('.ftr-steps__step')
  .filter(':last')
  .find('.ftr-steps__button')
  .text('Finalizar');

$('.ftr-steps__button').on('click', function() {
  $(this)
    .closest('form')
    .submit();
});

window.displayStep = function($step) {
  $step
    .siblings('.ftr-steps__step')
    .find('.ftr-btn--fab')
    .css({ display: 'none' });
  $step.find('.ftr-btn--fab').css({ display: 'block' });

  $('.ftr-steps').css({ left: '-' + $step.prevAll('.ftr-steps__step').length * 100 + 'vw' });

  $('.ftr-loading-bar').addClass('ftr-none');
  $step.find('.ftr-steps__button').prop('disabled', false);
  $step.find('#new-address').prop('disabled', false);

  $('#using-address').val('existing');
  $('#payment-existing').show();
  $('#payment-new').hide();
};

function getForm($formG) {
  $.ajax({
    timeout: 20000,
    url: $formG.attr('action'),
    dataType: 'html',
    success: function(html) {
      var endLength =
        window.location.href.indexOf('#') != -1 ? window.location.href.indexOf('#') : window.location.href.length;
      if (window.location.href.indexOf('#') > -1) {
        history.pushState({}, document.title, window.location.href.substr(0, endLength) + '#' + $formG.attr('id'));
      } else {
        history.replaceState({}, document.title, window.location.href.substr(0, endLength) + '#' + $formG.attr('id'));
      }

      $formG.find('.ftr-steps__inner').html(html);

      $formG.find('.ftr-btn--fab').on('click', function() {
        history.pushState(
          {},
          document.title,
          window.location.href.substr(0, endLength) + '#' + $formG.attr('id') + '-new'
        );
      });
      displayStep($formG);
    },
    error: function(xhr, ajaxOptions, thrownError) {
      $('.ftr-loading-bar').addClass('ftr-none');
      $('.ftr-steps__button').prop('disabled', false);
      $('#new-address').prop('disabled', false);

      if (xhr.statusText === 'timeout') {
        alert('Tempo esgotado!');
      } else {
        alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      }
    },
  });
}

getForm($('#shipping-address'));
// getForm($('#payment-address'));

$('form')
  .not('#checkout-confirm')
  .on('submit', function(e) {
    e.preventDefault();
    e.stopPropagation();

    $this = $(this);
    var $data = $this.serializeObject();

    if (typeof $("#payment-method input[type='radio']:checked").data('code-type') != 'undefined') {
      $data['payment_method_type'] = $("#payment-method input[type='radio']:checked").data('code-type');
    }

    var $form = $this.next('form');
    var validate = $this.attr('id') == 'checkout-confirm' ? '' : '/validate/';
    $.ajax({
      timeout: 20000,
      url: $this.attr('action') + validate,
      type: $this.attr('method'),
      data: $.param($data),
      dataType: 'json',
      beforeSend: function() {
        $('.ftr-loading-bar').removeClass('ftr-none');
        $this.find('.ftr-steps__button').prop('disabled', true);
        $('#new-address').prop('disabled', true);
      },
      success: function(json) {
        if ($this.attr('id') == 'shipping-address' && typeof json.shipping_address_id != 'undefined') {

          let url = (typeof PAGE_CHECKOUT !=='undefined') ? PAGE_CHECKOUT : 'checkout';
          $.ajax({
            timeout: 20000,
            url: 'index.php?route=' + url + '/payment_address/validate',
            type: 'post',
            data: {
              payment_address: 'existing',
              address_id: json.shipping_address_id,
            },
          });
        }
        $('.warning, .error').remove();
        if (json['redirect']) {
          location = json['redirect'];
        } else if (json['error']) {
          if (json['error']['warning']) {
            notificationMsg(json['error']['warning'], 'warning');
          }
          if ($this.attr('id') == 'shipping-address') {
            displayErrors(json['error'], '#shipping-address', true);
          } else {
            displayErrors(json['error']);
          }
          $('.ftr-loading-bar').addClass('ftr-none');
          $('.ftr-steps__button').prop('disabled', false);
        } else {
          getForm($form);
        }
      },
      error: function(xhr, ajaxOptions, thrownError) {
        $('.ftr-loading-bar').addClass('ftr-none');
        $('.ftr-steps__button').prop('disabled', false);
        $('#new-address').prop('disabled', false);

        if (xhr.statusText === 'timeout') {
          alert('Tempo esgotado!');
        } else {
          alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
        }
      },
    });
  });


$('.ftr-main').on('submit', '#form-register', function(e) {
  e.preventDefault();
  e.stopPropagation();

  $this = $(this);

  var formData = $('#form-register').serializeObject();

  if ($('.g-recaptcha').length > 0) {
    formData['g-recaptcha-response'] = grecaptcha.getResponse();
  }

  $.ajax({
    timeout: 20000,
    url: 'index.php?route=account/register_content/validate&checkout=true',
    method: 'post',
    data: formData,
    dataType: 'json',
    beforeSend: function() {
      $('.ftr-loading-bar').removeClass('ftr-none');
      $this.find('.ftr-steps__button[type=submit]').prop('disabled', true);
      $('#new-address').prop('disabled', true);
    },
    success: function(json){
      if (typeof json['error'] != 'undefined') {
        if (json['error']['warning']) {
          notificationMsg(json['error']['warning'], 'error');
        }
        for (var key in json['error']) {
          if (json['error'].hasOwnProperty(key)) {
            $('input[name="' + key + '"]')
              .closest('div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]')
              .append('<span class="ftr-field__error">' + json['error'][key] + '</span>');
          }
        }
        if ($('#form-register .ftr-field__error').length > 0) {
          var varLeft =
            $('#form-register .ftr-field__error')
              .closest('.ftr-steps__step')
              .offset().left - $('#form-register').offset().left;
          $('#form-register').css({ left: '-' + varLeft + 'px' });
        }
      } else if (typeof json['redirect'] != 'undefined') {
        window.location.href = json['redirect'];
      }
    },
    error: function(xhr, ajaxOptions, thrownError) {
      $('.ftr-loading-bar').addClass('ftr-none');
      $('.ftr-steps__button').prop('disabled', false);
      $('#new-address').prop('disabled', false);
      if (xhr.statusText === 'timeout') {
        alert('Tempo esgotado!');
      } else {
        alert(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      }
    },
  });
});
