
function compareArrays(arr1, arr2) {
  return $(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0;
}

window.setCookie = function(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = 'expires=' + d.toUTCString();
  document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
};

window.getCookie = function(cname) {
  var name = cname + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
};

window.waitEvent('scripts_window', function() {
  /* Função responsável pelo efeito de grid e list nas listagem de produtos */

  var btnChangeView = document.getElementById('change-view'),
    productView = document.querySelector('.products-view');

  if (btnChangeView) {
    if (getCookie('display')) handleChangeView();
    btnChangeView.onclick = handleChangeView.bind(btnChangeView);
  }

  var productGridElements = document.querySelectorAll(
    '.js-check-compare, .js-btn-quick-view, .js-btn-cart, .js-btn-qtd'
  );
  for (var i = 0; i < productGridElements.length; i++) {
    productGridElements[i].removeAttribute('disabled');
  }

  function handleChangeView() {
    if (this.tagName == 'BUTTON' && productView.classList.contains('list')) {
      setGridView();
    } else if (this.tagName == 'BUTTON' && productView.classList.contains('grid')) {
      setListView();
    } else if (getCookie('display') == 'grid_view') {
      setGridView();
    } else {
      setListView();
    }
  }

  function setGridView() {
    if (productView.classList.contains('list')) productView.classList.remove('list');
    btnChangeView.classList.add('btn-outline');
    productView.classList.add('grid');
    document.cookie = 'display=grid_view';
  }

  function setListView() {
    if (productView.classList.contains('grid')) productView.classList.remove('grid');
    if (btnChangeView.classList.contains('btn-outline')) btnChangeView.classList.remove('btn-outline');
    productView.classList.add('list');
    document.cookie = 'display=list_view';
  }

  function initQtdAtacado(context) {
    context = context || $('body');
    context.find('.js-btn-qtd').on('click', function() {
      var $inputqty = $(this)
          .parent()
          .find('.js-quantity'),
        $fator =
          $(this)
            .parent('[data-fator]')
            .data('fator') != 0
            ? $(this)
                .parent('[data-fator]')
                .data('fator')
            : 1,
        qty = $inputqty.val() == '' ? 0 : parseInt($inputqty.val(), 10),
        compare = $(this)
          .closest('[data-list-product-color-status]')
          .data('list-product-color-status')
          ? 0
          : 1;

      if ($(this).hasClass('js-up')) {
        qty = parseInt($inputqty.val()) + $fator;
      } else if ($(this).hasClass('js-down') && qty > 0) {
        qty = parseInt($inputqty.val()) - $fator;
        if (qty < compare) qty = $fator;
      }

      $inputqty.val(qty);
      $inputqty.trigger('input');
    });
  }

  function initAddToCart(context) {
    context = context || $('body');
    context.find('.js-btn-cart').click(function(e) {
      e.preventDefault();

      var product_id = $(this).data('product-id'),
        layout_id = $(this).data('layout-id'),
        quantity = $(this)
          .parent()
          .find('input')
          .val(),
        grid = $(this).data('grid'),
        grid_status = $(this).data('grid-status'),
        grid_id = $(this).data('grid-id'),
        list_grid = $(this).data('list-grid'),
        kit = $(this).hasClass('js-add-kit');

      /*Final de versão - Precisa arrumar esse monte de variavel de grid*/

      quantity = typeof quantity !== 'undefined' ? quantity : 1;
      grid = typeof grid !== 'undefined' ? grid : '';
      grid_status = typeof grid_status !== 'undefined' ? grid_status : '';

      addToCart(product_id, quantity, layout_id, grid, grid_status, grid_id, list_grid, kit);
    });
  }

  function initAddToCompare(context) {
    context = context || $('body');
    context.find('.js-btn-compare').click(function(e) {
      e.preventDefault();
      addToCompare($(this).data('product-id'), false, $(this));
    });
    context.find('.js-check-compare').change(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if ($(this).prop('checked')) {
        addToCompare($(this).data('product-id'), true, $(this));
      } else {
        removeToCompare($(this).data('product-id'), true);
      }
    });
  }

  function initAddToWishList(context) {
    context = context || $('body');
    context.find('.js-btn-wishlist').on('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      if ($(this).closest('.itembox-image-link').length || $(this).closest('.js-toggle-wishlist').length) {
        toggleToWishList($(this).data('product-id'), $(this));
      } else {
        addToWishList($(this).data('product-id'));
      }
    });
  }

  function initAddToGiftsList(context) {
    context = context || $('body');
    context.find('.js-check-gift').on('change', function(event) {
      event.preventDefault();
      event.stopPropagation();
      if ($(this).attr('checked')) {
        addToGiftsList($(this).data('product-id'), 1, 'index.php?route=listapresente/listapresente/add');
      } else {
        removeToGiftsList($(this).data('product-id'), 'index.php?route=listapresente/listapresente/remove');
      }
    });
    context.find('.js-btn-gifts-list').on('click', function(event) {
      event.preventDefault();
      event.stopPropagation();

      var btnCart = $(this)
        .closest('.js-product-container-action')
        .find('.js-btn-cart');

      var url = 'index.php?route=listapresente/listapresente/add',
        product_id = btnCart.data('product-id'),
        quantity = 1,
        grid = btnCart.data('grid'),
        grid_status = btnCart.data('grid-status');

      if (grid_status) {
        grid = typeof grid == 'string' ? JSON.parse(grid) : grid;
        grid = objectToParam(grid);
        grid = '&' + grid;
        url = url + grid;
      }

      addToGiftsList(product_id, quantity, url);
      $(this).removeAttr('disabled');
      $(this).removeClass('btn-loading');
    });
  }

  function initAddQuickView(context) {
    context = context || $('body');
    context.find('.js-btn-quick-view').on('click', function(event) {
      event.preventDefault();
      event.stopPropagation();
      var productId = $(this).data('product-id');
      $(this).addClass('btn-loading');

      $.ajax({
        url: 'index.php?route=product/product/quickView',
        type: 'GET',
        dataType: 'html',
        data: { product_id: productId },
      })
        .done(function(html) {
          var $html = $(html);

          initActionProductBox($html);

          $('.js-product-quick-view').remove();
          $('.js-btn-quick-view').removeClass('btn-loading');

          $('body')
            .append($html)
            .append('<div class="overlay overlay-black-3"></div>');
          /* Animação de entrada */
          $('.js-product-quick-view').css({ opacity: 0, top: '60%' });
          $('.js-product-quick-view').animate({ opacity: 1, top: '50%' }, 300);
          $('.overlay').css('display', 'none');
          $('.overlay').fadeIn(300);
          onClickOut($('.overlay'), null, null, removeProductQuickView, false);

          $('.js-product-quick-view-close').on('click', function(event) {
            event.preventDefault();
            removeProductQuickView();
          });
        })
        .fail(function() {
          console.log('error');
        })
        .always(function() {
          // console.log("complete");
        });
    });
  }

  function initAviseme(context) {
    context = context || $('body');

    context.find('.js-btn-aviseme').on('click', function() {
      var data = {},
        $this = $(this);

      data['product_id'] = $this.data('product-id');
      data['product_name'] = $this.data('product-name');

      $.ajax({
        url: 'index.php?route=product/avise_me&display=true',
        dataType: 'html',
        type: 'get',
        data: data,
        beforeSend: function() {
          $this.addClass('btn-loading');
        },
        complete: function() {
          $this.removeClass('btn-loading');
        },
        success: function(html) {
          $('.js-content-aviseme').append(html);
          $('.overlay, .js-aviseme-cancel').on('click', function(event) {
            event.preventDefault();
            $('.js-content-aviseme > *').remove();
          });
        },
      });
    });

    context.on('click', '.js-btn-aviseme-send', function() {
      $('.js-error').remove();
      $('.js-field-entry').removeClass('border-error');

      var data = {},
        $form = $('.js-aviseme-form');
      data['product_id'] = $('.js-btn-aviseme-send').data('product-id');
      data['name'] = $form.find('input[name="name"]').val();
      data['email'] = $form.find('input[name="email"]').val();
      data['captcha'] =
        typeof $('input[type=text][name=captcha]').val() == 'undefined'
          ? false
          : $('input[type=text][name=captcha]').val();
      data['g-recaptcha-response'] = $('.g-recaptcha').length > 0 ? grecaptcha.getResponse() : false;

      $.ajax({
        url: 'index.php?route=product/avise_me/send',
        dataType: 'json',
        type: 'post',
        data: data,
        beforeSend: function() {
          $('.js-btn-aviseme-send').addClass('btn-loading');
        },
        complete: function() {
          $('.js-btn-aviseme-send').removeClass('btn-loading');
        },
        success: function(json) {
          if (json['error']) {
            $.each(json['error'], function(index, value) {
              $('input[name=' + index + ']')
                .addClass('border-error')
                .after(
                  '<span class="text-error text-small visible-block top-margin-small js-error">' + value + '</span>'
                );
            });
            if (json['error']['google_recaptcha']) {
              $('#g-recaptcha').after(
                '<span class="text-error text-small visible-block top-margin-small js-error">' +
                  json['error']['google_recaptcha'] +
                  '</span>'
              );
            }
          }
          if (json['success']) {
            $('.js-aviseme-container').height($('.js-aviseme-container').height());
            $('.js-aviseme-form').animate(
              {
                'margin-top': '-100%',
              },
              300,
              function() {
                $('.js-aviseme-form').remove();
                $('.js-aviseme-container').append(
                  '<div class="row middle-xs full-height text-center"><div class="col-xs-12"><div class="content-box"><i class="fas fa-thumbs-up text-success bigger-text-large visible-block"></i><span class="text-x-large text-gray visible-block vertical-padding-large">' +
                    json['success'] +
                    '</span><button class="btn-default btn-large js-aviseme-continue"><span>Concluir</span></button></div></div></div>'
                );
                $('.js-aviseme-continue, .js-aviseme-cancel').on('click', function(event) {
                  event.preventDefault();
                  $('.js-content-aviseme > *').remove();
                });
              }
            );
          }
        },
      });
    });
  }

  function initHandleChangeGrid(context) {
    context = context || $('body');

    context.find('#color, #size, #specification').on('change', function() {
      var caracteristicaClicadaId = $(this).val(),
        caracteristica = $(this).attr('name'),
        data = {},
        grid = $(this)
          .closest('.js-product-quick-view')
          .find('.js-btn-cart')
          .data('grid');

      data['product_id'] = $(this)
        .closest('.js-product-quick-view')
        .find('.js-btn-cart')
        .data('product-id');
      data = $.extend(data, grid);

      data[caracteristica] = caracteristicaClicadaId;

      data = $.param(data);
      data = '&' + data;

      $('.js-product-quick-view').append(
        '<div class="center-middle-absolute full-width full-height overlay-white-6"><img src="assets/img/loading-black.svg" width="64" height="64" class="center-middle-absolute"></div>'
      );

      $.ajax({
        url: 'index.php?route=product/product/getProductGridLink',
        type: 'GET',
        dataType: 'html',
        data: data + '&quick_view=true',
      })
        .done(function(html) {
          var $html = $(html);
          $('.js-product-quick-view').remove();

          initActionProductBox($html);

          $('body').append($html);
        })
        .fail(function() {
          console.log('error');
        })
        .always(function() {
          // console.log("complete");
        });
    });
  }

  window.initActionProductBox = function(context) {
    context = context && context.tagName ? $(context) : context;
    initAddToCart(context);
    initAddToWishList(context);
    initAddToCompare(context);
    initQtdAtacado(context);
    initAddQuickView(context);
    initAviseme(context);
    initAddToGiftsList(context);
    initHandleChangeGrid(context);

    if (context) {
      var imagens = context.find('.load-image');
      imagens.each(function() {
        var $this = $(this);

        $this.attr('src', $this.data('src')).removeClass('load-image');
        $this[0].onload = function() {
          $this.closest('.image-loading-in-background').removeClass('image-loading-in-background');
        };
        $this[0].onerror = function() {
          $this.closest('.image-loading-in-background').removeClass('image-loading-in-background');
        };
      });
    }
  };

  initActionProductBox();

  window.initActionProductBoxCartList = function(context) {
    context = context && context.tagName ? $(context) : context;
    initQtdAtacado(context);
  };
});

$('.btn-close').live('click', function() {
  var $thisMsg = $(this).closest('div');

  clearTimeout($thisMsg.data('displayTime'));
  $thisMsg.stop(true, true);
  $thisMsg.fadeOut('slow', function() {
    $thisMsg.remove();
  });
});

function addToCart(product_id, quantity, layout_id, grid, grid_status, grid_id, list_grid, kit) {
  var url = 'index.php?route=checkout/cart/add',
    data = {},
    btnCart = '';

  if (grid_id) {
    if (!list_grid) {
      btnCart = $(
        '.js-btn-cart[data-grid-id=' +
          grid_id +
          '][data-product-id=' +
          product_id +
          '], .js-btn-quick-view[data-grid-id=' +
          grid_id +
          '][data-product-id=' +
          product_id +
          ']'
      );
    } else {
      btnCart = $('.js-btn-cart[data-grid-id=' + grid_id + '], .js-btn-quick-view[data-grid-id=' + grid_id + ']');
    }
  } else {
    btnCart = $(
      '.js-btn-cart[data-product-id=' + product_id + '], .js-btn-quick-view[data-product-id=' + product_id + ']'
    );
  }

  var btnCartNotification = btnCart.siblings('.js-btn-cart-notification');

  data['product_id'] = product_id;
  data['quantity'] = typeof quantity != 'undefined' ? quantity : 1;
  data['layout_id'] = typeof layout_id != 'undefined' ? layout_id : false;

  if (grid_status) {
    grid = typeof grid == 'string' ? JSON.parse(grid) : grid;
    grid = objectToParam(grid);
    grid = '&' + grid;
    url = url + grid;
  }

  $.ajax({
    url: url,
    type: 'post',
    data: data,
    dataType: 'json',
    error: function() {
      alert('Desculpe! Não conseguimos adicionar o produto ao carrinho.');
    },
    success: function(json) {
      if (json['google_analytics']) {
        const googleAnalyticsCodes = JSON.parse(json['google_analytics']);
        const eventName = 'add_to_cart';
        const params = {
          currency: 'BRL',
          items: [
            {
              item_id: data['product_id'],
              item_name: json.product_info.name,
              item_brand: json.product_info.manufacturer_name,
              price: json.product_info.price,
              currency: 'BRL',
              quantity: data['quantity'],
            },
          ],
        };

        if (googleAnalyticsCodes.find(ga => ga === 'gtag')) {
          window.googleAnalytics(eventName, params);
        }

        if (googleAnalyticsCodes.find(ga => ga === 'gtm')) {
          window.googleTagManager(eventName, params);
        }

      }

      if (kit) {
        window.location.reload();
        return;
      }
      $('.success, .warning, .attention, .information, .error').remove();

      if (json['redirect']) {
        location = json['redirect'];
        return false;
      }

      if (json['error']) {
        $.each(json['error'], function(index, value) {
          notificationMsg(value, 'warning');
        });
        return false;
      }

      if (json['success']) {
        if (json['redirect']) {
          location = json['redirect'];
        } else {
          notificationMsg(json['success'], 'success');

          if (btnCartNotification.length > 0) {
            btnCartNotification.addClass('have-in-cart');
          }

          $('.js-header__cart-total').html(json['total_qtd']);
        }
      }
    },
  });
}

function toggleToWishList(product_id, element) {
  $.ajax({
    url: 'index.php?route=account/wishlist/toggle',
    type: 'post',
    data: 'product_id=' + product_id,
    dataType: 'json',
    success: function(json) {
      if (typeof json['toggle'] != 'undefined' && json['toggle']) {
        var icon = element[0].querySelector('i');
        if (icon.classList.contains('fas')) {
          icon.classList.remove('fas');
          icon.classList.add('far');
          icon.title = 'Colocar na lista de desejos';
        } else {
          icon.classList.remove('far');
          icon.classList.add('fas');
          icon.title = 'Remover da lista de desejos';
        }

        if (json['success']) {
          notificationMsg(json['success'], 'success');
        }
      } else {
        var messages = document.querySelectorAll('.success, .warning, .attention, .information');
        for (var i = 0; i < messages.length; i++) {
          messages[i].parentNode.removeChild();
        }

        if (json['success']) {
          notificationMsg(json['success'], 'warning');
        }
      }

      if (json['success']) {
        var wishlistDisplays = document.querySelectorAll('.js-total-wish-list');
        for (var i = 0; i < wishlistDisplays.length; i++) {
          wishlistDisplays[i].textContent = wishlistDisplays[i].textContent.replace(/[0-9]+/, json['total_qtd']);
        }
      }
    },
  });
}

function addToWishList(product_id) {
  $.ajax({
    url: 'index.php?route=account/wishlist/add',
    type: 'post',
    data: 'product_id=' + product_id,
    dataType: 'json',
    success: function(json) {
      $('.success, .warning, .attention, .information').remove();

      if (json['success']) {
        notificationMsg(json['success'], 'success');

        /* Valida a resolução para exibir o  */
        var tam = $(window).width();

        if (tam > 980) {
          $('#wishlist-total').html(json['total']);
          $('#menu-wishlist-total').html(json['total_qtd']);
        }
      }
    },
  });
}

function addToCompare(product_id, noMessage, $this) {
  $.ajax({
    url: 'index.php?route=product/compare/add',
    type: 'post',
    data: 'product_id=' + product_id,
    dataType: 'json',
    success: function(json) {
      $('.success, .warning, .attention, .information').remove();

      if (json['error']) {
        $this.attr('checked', false);
        notificationMsg(json['error'], 'warning');
      }

      if (json['success']) {
        if (!noMessage) {
          notificationMsg(json['success'], 'success');
        }

        var totalComparationList = document.querySelectorAll('.js-total-comparation-list');
        for (var i = 0; i < totalComparationList.length; i++) {
          totalComparationList[i].textContent = totalComparationList[i].textContent.replace(/[0-9]+/, json['total']);
        }
      }
    },
  });
}

function removeToCompare(product_id, noMessage) {
  $.ajax({
    url: 'index.php?route=product/compare/remove',
    type: 'post',
    data: 'remove=' + product_id,
    dataType: 'json',
    success: function(json) {
      $('.success, .warning, .attention, .information').remove();

      if (json['success']) {
        if (!noMessage) {
          notificationMsg(json['success'], 'success');
        }

        var totalComparationList = document.querySelectorAll('.js-total-comparation-list');
        for (var i = 0; i < totalComparationList.length; i++) {
          totalComparationList[i].textContent = totalComparationList[i].textContent.replace(/[0-9]+/, json['total']);
        }
      }
    },
  });
}

function addToGiftsList(product_id, quantity, url) {
  var data = {};
  data['product_id'] = product_id;
  data['quantity'] = quantity;

  $.ajax({
    url: url,
    type: 'post',
    data: data,
    dataType: 'json',
    error: function(json) {
      alert('Desculpe! Não conseguimos adicionar o produto na lista de presentes.');
    },
    success: function(json) {
      $('.success, .warning, .attention, information, .error').remove();

      if (json['error']) {
        if (typeof json['error'] === 'object') {
          $.each(json['error'], function(index, value) {
            notificationMsg(value, 'warning');
          });
        } else {
          notificationMsg(json['error'], 'warning');
        }
        return false;
      }

      if (json['success']) {
        notificationMsg(json['success'], 'success');
        $('.js-header__cart-total').html(json['total_qtd']);
      }
    },
  });
}

function removeProductQuickView() {
  $('.overlay').fadeOut('300', function() {
    $('.overlay').remove();
  });
  $('.js-product-quick-view').animate({ opacity: 0, top: '60%' }, 300, function() {
    $('.js-product-quick-view').remove();
  });
}

/*
Essa função retorna os parametros passado por GET na URL a fim de restaurar
essas informações quando trocar de produto. ByMatheus
*/
function getGetToJson() {
  var query = location.search.slice(1);
  var partes = query.split('&');
  var data = [];
  for (var i = 0; i < partes.length; i++) {
    var chaveValor = partes[i].split('=');
    var chave = chaveValor[0];
    var valor = chaveValor[1];
    data[i] = chaveValor;
  }

  return data;
}

function getGetToJsonObject() {
  var query = location.search.slice(1);
  var partes = query.split('&');
  var data = {};
  for (var i = 0; i < partes.length; i++) {
    var chaveValor = partes[i].split('=');
    data[chaveValor[0]] = chaveValor[1];
  }

  return data;
}

function getURLVar(key) {
  var value = [];

  var query = String(document.location).split('?');

  if (query[1]) {
    var part = query[1].split('&');

    for (i = 0; i < part.length; i++) {
      var data = part[i].split('=');

      if (data[0] && data[1]) {
        value[data[0]] = data[1];
      }
    }

    if (value[key]) {
      return value[key];
    } else {
      return '';
    }
  }
}

$('.js-toggle-product-description').on('click', function(event) {
  event.preventDefault();
  let productDescription = event.currentTarget.parentElement;
  productDescription.querySelector('.js-product-description-container').classList.toggle('hidden');
  productDescription.querySelector('.js-product-description-plus').classList.toggle('hidden');
  productDescription.querySelector('.js-product-description-minus').classList.toggle('hidden');
});