window.pageProductJsInit = function () {
  window.addthis = null;
  window.$LAB
    .setOptions({ AllowDuplicates: true })
    .script('//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5b71e2e8854c3636');

  var dataInfo = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));

  var Type_TipoZoom = {
    Tp_Fancybox: '0',
    Tp_Cloudzoom: '1',
    Tp_ElevateZoom: '2',
    Tp_PhotoSwipe: '3',
  };

  function openPhotoSwipe() {

    var pswpElement = document.querySelectorAll('.pswp')[0],
      mainImage = document.getElementById('main-image'),
      items = [];

    items[0] = {
      src: mainImage.getAttribute('data-zoom-image'),
      w: parseInt(mainImage.getAttribute('data-w'), 10),
      h: parseInt(mainImage.getAttribute('data-h'), 10),
    };

    var thumbs = document.querySelectorAll('.js-thumbnail');

    for (var i = 0; i < thumbs.length; i++) {
      if ($(thumbs[i]).data('type') == 'video') {
        items[i] = {
          html: '<div class="flex full-height middle-xs">' + $(thumbs[i]).attr('href') + '</div>',
        };
      } else {
        items[i] = {
          src: thumbs[i].getAttribute('href'),
          w: parseInt(mainImage.getAttribute('data-w'), 10),
          h: parseInt(mainImage.getAttribute('data-h'), 10),
        };
      }
    }
    var options = {
      history: false,
      focus: false,
      shareEl: false,
      showAnimationDuration: 0,
      hideAnimationDuration: 0,
      index: parseInt(mainImage.getAttribute('data-index'), 10),
    };

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

  function initElevateZoom() {
    if (window.matchMedia('(pointer: coarse)').matches) {
      $('.js-thumbnail').on('click', function (e) {
        e.preventDefault();
        $('#main-image').attr('data-index', $(this).index());
        openPhotoSwipe();
      });
      return;
    }


    if ($.fn.elevateZoom) {
      $('#main-image').elevateZoom({
        gallery: 'thumbnails',
        cursor: 'crosshair',
        galleryActiveClass: 'border-gray',
        containLensZoom: true,
        zoomType: dataInfo.typeZoom == Type_TipoZoom.Tp_ElevateZoom ? 'inner' : 'window',
      });
    } else {
      setTimeout(function () {
        initElevateZoom();
      }, 20);
    }
  }

  if (parseInt(dataInfo.facebook, 10)) {
    window.fbq('track', 'ViewContent', {
      content_type: 'product',
      content_ids: [dataInfo.productId],
      value: dataInfo.value,
      currency: 'BRL',
    });
  }

  $('.js-control-form-review').on('mousedown', function () {
    $('#form-review').toggleClass('hidden');
  });

  $('#form-review').on('mousedown', function (event) {
    if (event.target.classList.contains('overlay')) {
      $(this).addClass('hidden');
    }
  });

  $('#button-review').on('click', function (event) {
    event.preventDefault();

    var entry = {
      name: $('input[name=name]'),
      message: $('textarea[name=text]'),
      rating: $('input[name=rating]:checked'),
      captcha: $('input[name=captcha]'),
    };

    var recaptchaResponse = typeof grecaptcha !== 'undefined' ? grecaptcha.getResponse() : '';


    if (entry.rating.length === 0) {
      $('#field-rating .js-error').remove();
      $('#field-rating').append(
        '<span class="text-small text-error js-error">Não esqueça de fazer sua avaliação.</span>'
      );
      return;
    }

    var data =
      'name=' +
      encodeURIComponent(entry.name.val()) +
      '&text=' +
      encodeURIComponent(entry.message.val()) +
      '&rating=' +
      encodeURIComponent(entry.rating.val()) +
      '&captcha=' +
      encodeURIComponent(entry.captcha.val()) +
      '&g-recaptcha-response=' + encodeURIComponent(recaptchaResponse);


    $('#form-rating .js-message').remove();

    $(this)
      .addClass('btn-loading')
      .prop('disabled', true);

    $.ajax({
      url: 'index.php?route=product/product/write&product_id=' + dataInfo.productId,
      type: 'post',
      dataType: 'json',
      data: data,
      complete: function () {
        $('#button-review')
          .removeClass('btn-loading')
          .removeAttr('disabled');

        $('.js-error').remove();
      },
      success: function (data) {
        function Message(message, type) {
          var html = '';
          html += '<div class="flex nowrap-xs top-xs background-' + type + ' bottom-margin-medium js-message">';
          html += '<span class="visible-block text-medium text-' + type + ' padding-medium">' + message + '</span>';
          html += '<i class="fas fa-times text-' + type + ' padding-medium cursor-pointer js-close"></i>';
          html += '</div>';

          $('#form-rating').on('click', '.js-close', function () {
            $(this)
              .closest('.js-message')
              .remove();
          });

          $('#form-rating').prepend(html);
        }

        if (data['error']) {
          var msg = '';
          if (typeof data['error'] === 'string') {
            msg = data['error'];
          } else {
            var key = Object.keys(data['error'])[0];
            msg = data['error'][key];
          }
          Message(msg, 'warning');
        }

        if (data['success']) {
          Message(data['success'], 'success');

          entry.name.val('');
          entry.message.val('');
          entry.rating.removeAttr('checked');
          entry.captcha.val('');

          $('label.far.fa-star').attr('class', 'far fa-star text-x-large horizontal-padding-x-small');
        }
      },
    });
  });

  $('.button-review-scroll').on('click', function() {
    document.querySelector('.scroll-end').scrollIntoView({ behavior: 'smooth' });
  });

  window.initQuoteShipping($('#btn-postcode'), $('#postcode').mask('00000-000'), 'text', $('#qty'));

  if (window.top !== window.self) {
    $('.load-image').each(function () {
      $(this).attr('src', $(this).attr('data-src'));
    });
  }

  $('.star-new-rating').on('change', function () {
    $('label.fa-star')
      .removeClass()
      .addClass('far fa-star text-x-large horizontal-padding-x-small active_star' + $(this).val());
  });

  if (dataInfo.typeZoom == Type_TipoZoom.Tp_Fancybox) {
    $('#main-image').on('click', function () {
      $($('.js-thumbnail')[0]).trigger('click');
    });

    $('.js-thumbnail').fancybox({
      prevEffect: 'elastic',
      nextEffect: 'elastic',
      closeBtn: true,
      nextClick: true,
      type: 'image',
      beforeLoad: function () {
        if (this.element[0].dataset.type == 'video') {
          this.type = 'iframe';
        }
      },
    });
  }

  if (dataInfo.typeZoom == Type_TipoZoom.Tp_PhotoSwipe) {
    $('#main-image').on('click', function () {
      $(this).attr('data-index', 0);
      openPhotoSwipe();
    });
    $('.js-thumbnail').on('click', function (e) {
      e.preventDefault();
      $('#main-image').attr('data-index', $(this).index());
      openPhotoSwipe();
    });
  }

  if (dataInfo.typeZoom == Type_TipoZoom.Tp_Cloudzoom || dataInfo.typeZoom == Type_TipoZoom.Tp_ElevateZoom) {
    initElevateZoom();

    $('#main-image').on('click', openPhotoSwipe);

    $($('.js-thumbnail')[0]).addClass('border-gray');

    $('.js-thumbnail').on('click', function () {
      $('iframe')
        .closest('div')
        .remove();
      $('.zoomWindowContainer').css('visibility', 'visible');
      $('.zoomLens').css('visibility', 'visible');
      $('#main-image').removeAttr('style');
      if ($(this).data('type') == 'video') {
        $('#main-image')
          .closest('.flex.center-xs')
          .prepend($(this).attr('href'));
        $('iframe')
          .closest('div')
          .css('height', $('#main-image').height());
        $('#main-image').css('display', 'none');
        $('.zoomWindowContainer').css('visibility', 'hidden');
        $('.zoomLens').css('visibility', 'hidden');
      }
      $('#main-image').attr('data-index', $(this).index());
    });
  }
};

window.waitEvent('scripts_document', window.pageProductJsInit);
