function loadReview() {
  $('#review').load('index.php?route=product/product/review&product_id=' + $('#product').data('product-id'));
}
loadReview();

//============================== PhotoSwipe zoom ===============================
var elementImages = document.querySelectorAll('.ftr-scroller > img');

function openPhotoSwipe(index) {
  var pswpElement = document.querySelectorAll('.pswp')[0];
  var items = [];

  for (var i = 0; i < elementImages.length; i++) {
    if (elementImages[i].getAttribute('data-video')) {
      items[i] = {
        html: elementImages[i].getAttribute('data-video'),
      };
    } else {
      items[i] = {
        src: elementImages[i].getAttribute('data-zoom-image'),
        w: parseInt(elementImages[i].getAttribute('data-w'), 10),
        h: parseInt(elementImages[i].getAttribute('data-h'), 10),
      };
    }
  }

  var options = {
    history: false,
    focus: false,
    shareEl: false,
    fullscreenEl: false,
    showAnimationDuration: 0,
    hideAnimationDuration: 0,
    index: index,
  };

  var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
  gallery.init();
}

for (var i = 0; i < elementImages.length; i++) {
  elementImages[i].onclick = function(e) {
    e.preventDefault();
    openPhotoSwipe(parseInt(this.getAttribute('data-index'), 10));
  };
}
//=========================== FIM - PhotoSwipe zoom ============================

window.getUrl = function($this) {
  if (document.getElementById('product').getAttribute('data-selected') == '') return '';

  var selecteds = JSON.parse(document.getElementById('product').getAttribute('data-selected')),
    caracteristicaClicadaId = $this.getAttribute('data-id'),
    caracteristica = $this.getAttribute('data-caracteristica');

  if (caracteristica) {
    selecteds[caracteristica] = caracteristicaClicadaId;
  }

  var selectedsURL = '';
  for (var key in selecteds) {
    selectedsURL += '&' + key + '=' + selecteds[key];
  }

  return {
    selecteds: selecteds,
    selectedsURL: selectedsURL,
  };
};

if (document.getElementById('ftr-add-to-cart') != null) {
  buttonAddToCart = document.getElementById('ftr-add-to-cart');
  buttonAddToCart.onclick = function(e) {
    e.preventDefault();
    var data = {};
    data = getUrl(this).selecteds;
    data['quantity'] = buttonAddToCart.getAttribute('data-fator-multiplicador');
    addToCart(data);
  };
}

var futuragrade_status = document.getElementById('product').getAttribute('data-grade');

if (futuragrade_status) {
  function loadContent(html) {
    var element = document.getElementById('review');
    if (element) {
      document.getElementById('review').innerHTML = html;
    }
  }

  executaChamadaAjax(
    'index.php?route=product/product/review&product_id=' +
      document.getElementById('product').getAttribute('data-product-id'),
    loadContent
  );

  var selectsProperties = document.querySelectorAll(
    '.ftr-js-option-color-grid, .ftr-js-option-size-grid, .ftr-js-option-specification-grid'
  );

  for (var key in selectsProperties) {
    selectsProperties[key].onclick = function() {
      var selectedsURL = getUrl(this).selectedsURL;
      // sobrescreve a url anterior no historico quanod uma caracteristicas do produto com grade é alterada, evitando varias urls de um mesmo produto (cor, tamanho, especificação)
      window.setCookie('overwrite', true, 1);
      executaChamadaAjax('index.php?route=product/product/getProductGridLink', goUrl, selectedsURL);
    };
  }
}

$('.ftr-rating-change .ftr-rating-change__input').on('change', function() {
  $('.ftr-rating-change .ftr-rating-change__label')
    .removeClass()
    .addClass('material-icons ftr-rating-change__label ftr-active-star' + $(this).val());
});
$('#toogle-review').on('click', function() {
  $('#review, #form-review').toggleClass('ftr-hidden');
  var text_button = $(this)
    .text()
    .trim();
  var text_language = language.getText('product', 'text_write').trim();
  if (text_button == text_language) {
    $(this).text(language.getText('product', 'view_comments'));
  } else {
    $(this).text(text_language);
  }
});

$('#form-review').validate({
  onkeyup: function(element) {
    if ($(element).valid()) {
      $(element)
        .closest('div[class|=ftr], label[class|=ftr]')
        .removeClass('error');
      $(element)
        .siblings('.ftr-field__error')
        .remove();
    }
  },
  onsubmit: true,
  showErrors: function(errorMap, errorList) {
    $.each(errorList, function() {
      $($(this)[0].element)
        .closest('div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]')
        .addClass('error')
        .find('.ftr-field__error')
        .remove();
      $($(this)[0].element)
        .closest('div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]')
        .append(
          $('<span>')
            .addClass('ftr-field__error')
            .text($(this)[0].message)
        );
    });
  },
  rules: {
    email: {
      customemail: true,
    },
  },
});

$('#form-review').on('submit', function(e) {
  e.preventDefault();
  var $this = $(this);
  $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    dataType: 'json',
    data: $(this).serialize(),
    beforeSend: function() {
      $(this)
        .find('button[type=submit]')
        .prop('disabled', true);
      $('.ftr-loading-bar').removeClass('ftr-none');
    },
    complete: function(json) {
      $(this)
        .find('button[type=submit]')
        .prop('disabled', false);
      $('.ftr-loading-bar').addClass('ftr-none');
    },
    success: function(data) {
      if (data['error']) {
        displayErrors(data['error'], '#form-review');
      }

      if (data['success']) {
        $this[0].reset();
        contentSwipeDisplayNone();
        $('#captcha-image-review').attr('src', 'index.php?route=product/product/captcha');
        loadReview();

        $('#toogle-review').trigger('click');
        notificationMsg(data['success'], 'success');

        $this
          .find('.ftr-rating-change label')
          .removeClass()
          .addClass('material-icons ftr-rating-change__label');
      }
    },
  });
});

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

  var $data = {},
    $element = $('#postcode');

  $data['postcode'] = encodeURIComponent($element.val());
  $data['zone_id'] = typeof $element.data('zone-id') != 'undefined' ? $element.data('zone-id') : '';
  $data['freteproduto_id'] = $element.data('product-id');

  $.ajax({
    url: $(this).prop('action'),
    type: $(this).prop('method'),
    data: $data,
    dataType: 'json',
    beforeSend: function() {
      $('#btn-postcode').prop('disabled', true);
      $('.ftr-loading-bar, .ftr-js-frete-loading').removeClass('ftr-none');
    },
    complete: function(json) {
      $('#btn-postcode').prop('disabled', false);
      $('.ftr-loading-bar, .ftr-js-frete-loading').addClass('ftr-none');
    },
    success: function(json) {
      clearNotification();
      if (json['error']) {
        $('.ftr-field__error').remove();
        if (json['error']['warning']) {
          notificationMsg(json['error']['warning'], 'warning');
        }

        if (json['error']['zone']) {
          if ($('.ftr-error').length == 0) {
            $('select[name="zone_id"]')
              .closest('div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]')
              .append(
                $('<span>')
                  .addClass('ftr-textfield__error')
                  .text(json['error']['zone'])
              );
          }
        }

        if (json['error']['postcode']) {
          if ($('.ftr-error').length == 0) {
            $('input[name=postcode]')
              .closest('div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]')
              .append(
                $('<span>')
                  .addClass('ftr-field__error')
                  .text(json['error']['postcode'])
              );
          }
        }
      }

      if (json['shipping_method']) {
        /* INICIO - Mensagens e borda de erro */
        if ($('.zone_id').hasClass('field-entry-error')) {
          $('.zone_id').removeClass('field-entry-error');
        }
        if ($('.js-zone-id-error').length > 0) {
          $('.js-zone-id-error').remove();
        }
        if ($('#postcode').hasClass('field-entry-error')) {
          $('#postcode').removeClass('field-entry-error');
        }
        if ($('.js-postcode-error').length > 0) {
          $('.js-postcode-error').remove();
        }
        /* FINAL - Mensagens e borda de erro */

        htmlPostcodeResult = '';
        htmlPostcodeResult = '<hr class="ftr-out-space--v-m">';
        htmlPostcodeResult += '<div>';
        htmlPostcodeResult +=
          '<span class="ftr-text--m"><b>' + language.getText('product', 'text_shipping_method') + '</b></span>';

        htmlPostcodeResult +=
          '<form action="' + language.getText('product', 'action') + '" method="post" enctype="multipart/form-data">';
        for (i in json['shipping_method']) {
          htmlPostcodeResult +=
            '<span class="ftr-text--grey ftr-block ftr-out-space--t-m"><b>' +
            json['shipping_method'][i]['title'] +
            '</b></span>';

          if (!json['shipping_method'][i]['error']) {
            for (j in json['shipping_method'][i]['quote']) {
              htmlPostcodeResult +=
                '<label class="ftr-block ftr-out-space--t-n" for="' +
                json['shipping_method'][i]['quote'][j]['code'] +
                '">';
              htmlPostcodeResult +=
                '<span>' +
                json['shipping_method'][i]['quote'][j]['title'] +
                ' - ' +
                json['shipping_method'][i]['quote'][j]['text'] +
                '</span>';
              htmlPostcodeResult += '</label>';
            }
          } else {
            htmlPostcodeResult += '<span class="">' + json['shipping_method'][i]['error'] + '</span>';
          }
        }

        htmlPostcodeResult += '<input type="hidden" name="next" value="shipping">';

        htmlPostcodeResult += '</form>';
        htmlPostcodeResult += '</div>';

        $('#shipping-options').html(htmlPostcodeResult);

        $('input[name=shipping_method]').on('change', function() {
          $('#button-shipping').prop('disabled', false);
        });
      }

      $('#btn-postcode').prop('disabled', false);
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    },
  });
});
