function updateCartApp(quantity) {
  var jsonQuantity = '{"qtdProduto": ' + quantity + '}';

  var isFlutter = typeof FlutterCallback != 'undefined';
  if (isFlutter) {
    FlutterCallback.postMessage(jsonQuantity);
  }

  var isAndroid = typeof Android != 'undefined';
  if (isAndroid) {
    Android.updateQtdProduto(jsonQuantity);
  }

  var isIOS = typeof window.webkit != 'undefined';
  if (isIOS) {
    window.webkit.messageHandlers.updateQtdProduto.postMessage(jsonQuantity);
  }
}
var quantityCartApp = $('.ftr-main').data('quantity');
updateCartApp(quantityCartApp);

/**
 * [Marca os erros nos inputs]
 * @param  {[json]} error           [json com os erros]
 * @param  {[string]} formOrContainer [#id-do-formulario]
 */
function displayErrors(error, formOrContainer, noNotification) {
  if (typeof formOrContainer != 'undefined') {
    formOrContainer = formOrContainer + ' ';
  } else {
    formOrContainer = '';
  }
  for (var key in error) {
    if (!noNotification) {
      var msgError = Array.isArray(error[key]) ? error[key][0] : error[key];

      notificationMsg(msgError, 'error');
    }
    $(formOrContainer + 'input[name="' + key + '"]')
      .closest('div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]')
      .addClass('error')
      .append('<span class="ftr-field__error">' + msgError + '</span>');
  }
}

function camelCase(string) {
  return string.replace(/[_-]([a-z])/g, function($1) {
    return $1.replace(/[_-]/g, '').toUpperCase();
  });
}

function getGetToJson() {
  var query = location.search.slice(1),
    partes = query.split('&'),
    data = [];

  for (var i = 0; i < partes.length; i++) {
    var chaveValor = partes[i].split('='),
      chave = chaveValor[0],
      valor = chaveValor[1];
    data[i] = chaveValor;
  }
  return data;
}
function goUrl(url) {
  window.location.href = url;
}
//======================== Adicionar a lista de desejos ========================

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']) {
        if (json['success']) {
          notificationMsg(json['success'], 'success');
        }
      } else {
        if (json['success']) {
          notificationMsg(json['success'], 'warning');
        }
      }
      if (json['toggle']) {
        if (element.hasClass('in')) {
          element.html('&#xE87E;').removeClass('in');
        } else {
          element.html('&#xE87D;').addClass('in');
        }
      }
    },
  });
}

$('.ftr-wishlist-icon').on('click', function() {
  toggleToWishList($(this).data('product-id'), $(this));
});

function initProductBoxAction(context) {
  context.find('.ftr-wishlist-icon').on('click', function() {
    toggleToWishList($(this).data('product-id'), $(this));
  });
  context.find('.ftr-js-image-load__image').imageLoad({ desconto: 500 });
}
//===================== FIM - Adicionar a lista de desejos =====================
//============================ Adicionar ao carrinho ===========================
function addToCartReturn(json) {
  if (json != undefined) {
    json = JSON.parse(json);

    var url = window.location.href;
    if (json['redirect'] && url != json['redirect']) {
      location = json['redirect'];
      return false;
    }

    if (json['error']) {
      for (var key in json['error']) {
        if (key == 'option') {
          for (i in json['error'][key]) {
            notificationMsg(json['error'][key][i], 'warning');
          }
        } else {
          notificationMsg(json['error'][key], 'warning');
        }
        contentSwipeDisplayNone();
      }
    }

    if (json['success']) {
      notificationHaveInCart(json.product_id);
      updateCartApp(json.total_qtd);
      notificationMsg(json['success'], 'success');
      contentSwipeDisplayNone();
    }
  }
}

function notificationHaveInCart(product_id) {
  console.log(product_id);
  console.log($('.ftr-quantity-wholesale__button[data-product-id=' + product_id + ']'));

  $('.ftr-quantity-wholesale__button[data-product-id=' + product_id + ']')
    .siblings('.ftr-js-quantity-wholesale__notification')
    .addClass('ftr-quantity-wholesale__notification--have-in-cart');
}

function executaChamadaAjax(url, returnFunction, parametros, method) {
  parametros = parametros == undefined ? '' : parametros;
  var parametrosURL = parametros != '' ? '&' + parametros : '';
  method = method == undefined ? 'GET' : method;

  var ajax;
  try {
    ajax = new XMLHttpRequest();
  } catch (err) {
    // versões antigas do Internet Explorer não tem a classe XMLHttpRequest, precisa usar esse componente ActiveX
    ajax = new ActiveXObject('Microsoft.XMLHTTP');
  }
  ajax.open(method, url + parametrosURL, true);
  ajax.timeout = 10000;
  ajax.ontimeout = function() {
    console.log('Erro! Tempo excedido;');
  };
  if (method == 'GET') {
    ajax.send();
  } else {
    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.send(parametros);
  }
  ajax.onreadystatechange = function() {
    if (ajax.readyState == 4 && ajax.status == 200) {
      if (ajax.response != '') {
        returnFunction(ajax.response);
      }
    }
  };
}

function addToCart(options) {
  var parametros = {},
    optionsDefault = {
      product_id: null,
      quantity: 1,
      size_id: null,
      specification_id: null,
      color_id: null,
      layout_id: null,
    };

  for (var property in optionsDefault) {
    if (optionsDefault.hasOwnProperty(property)) {
      if (options[property]) {
        parametros[property] = options[property];
      } else if (optionsDefault[property]) {
        parametros[property] = optionsDefault[property];
      }
    }
  }

  executaChamadaAjax('index.php?route=checkout/cart/add', addToCartReturn, $.param(parametros), 'POST');
}
//========================= FIM - Adicionar ao carrinho ========================
//======================= Remover do Comprar Mais Tarde ========================
function removeBuyLaterReturn(json, product_id) {
  if (json != undefined) {
    json = JSON.parse(json);

    var url = window.location.href;
    if (json['redirect'] && url != json['redirect']) {
      location = json['redirect'];
      return false;
    }

    if (json['error']) {
      for (var key in json['error']) {
        if (key == 'option') {
          for (i in json['error'][key]) {
            notificationMsg(json['error'][key][i], 'warning');
          }
        } else {
          notificationMsg(json['error'][key], 'warning');
        }
        contentSwipeDisplayNone();
      }
    }

    if (json['success']) {
      let btnBuyLater = $('.ftr-buy-later-remove[data-product-id='+ product_id + ']'),
          product = btnBuyLater.closest('.ftr-product-card'),
          container = btnBuyLater.closest('.ftr-buy-later-list'),
          productsCount = container.data('products-count');

      if (productsCount == 1) {
        location.reload();
      } else {
        product.remove();
        container.data('products-count', productsCount - 1);
      }
    }
  }
}
function removeBuyLater(product_id) {
  var parametros = {remove: product_id || null};

  $.ajax({
    url:'index.php?route=module/buy_later/remove',
    data: $.param(parametros),
    type: 'POST',
    success: function (json) {
      removeBuyLaterReturn(json, product_id);
    },
    error: function(res, status, error) {
      console.log(res.responseText);
    },
  });
}
//======================= FIM - Remover do Comprar Mais Tarde ==================
function contentSwipeDisplayNone() {
  $('.ftr-js-swipe-content-overlay').css({ background: 'rgba(0,0,0,0)' });
  setTimeout(function() {
    $('.ftr-js-swipe-content').css({ right: '-100vw' });
    $('.ftr-js-container-btn--fixed').css({ bottom: 0 });
    $('.ftr-js-swipe-content-overlay').remove();
    // $('.ftr-main').css({
    //   position: 'static',
    //   top: 'auto'
    // });
  }, 300);
}

$(document).ready(function() {
  /* Funcionamento dos campos de um formulário */
  $('.ftr-main').on('focusin focusout', '.ftr-js-field__entry', function(e) {
    if (e.type == 'focusout') {
      if ($(this).val() != '') {
        $(this)
          .addClass('on')
          .removeClass('off');
      } else {
        $(this)
          .addClass('off')
          .removeClass('on');
      }
    } else {
      $(this)
        .addClass('on')
        .removeClass('off');
    }
  });

  $('.ftr-js-select').each(function() {
    $(this)
      .find('.ftr-js-select__entry')
      .val(
        $(this)
          .find('[data-selected=true]')
          .text()
      );
  });

  $('.ftr-main').on('change', '.ftr-js-select__value', function() {
    $(this)
      .siblings('.ftr-select__content')
      .find('[data-value="' + $(this).val() + '"]')
      .trigger('changetriggered');
  });

  $('.ftr-main').on('click changetriggered', '.ftr-js-select', function(e) {
    if (!$(this).hasClass('ftr-js-select--disabled') || e.type === 'changetriggered') {
      $(this).toggleClass('on');
      // console.log(e.target);
      // notificationMsg($(this).prop('outerHTML'), 'error');
      if ($(e.target).hasClass('ftr-select__content__item')) {
        var $selectedOption = $(e.target),
          $value = $(this).find('.ftr-js-select__value'),
          $entry = $(this).find('.ftr-js-select__entry');

        $selectedOption.siblings().removeAttr('data-selected');
        $selectedOption.attr('data-selected', true);

        $value.val($selectedOption.data('value'));
        $entry.val($selectedOption.text());

        $(this)
          .addClass('written')
          .removeClass('on');

        if (e.type !== 'changetriggered') {
          $value[0].dispatchEvent(new Event('change'));
        }

        // dispara a validação do js
        $value.trigger('keyup');
      }
      onClickOut($(this), null, removeDropdown, null, true);
    }
  });

  // $('.ftr-js-select__content__item[data-selected]').each(function() {
  //   $(this).closest('.ftr-js-select').addClass('written').find('.ftr-js-select__entry').val($(this).text());
  // });
  $('.ftr-js-select__content__item[data-selected]').trigger('click');

  $('.ftr-main').on('click', '.ftr-js-dropdown__display', function(e) {
    $('.ftr-js-dropdown__content').removeClass('on');
    $(this)
      .next('.ftr-js-dropdown__content')
      .addClass('on');
    onClickOut($('.ftr-js-dropdown__content'), null, removeDropdown, null, true, true);
  });
  $('.ftr-main').on('click', '.ftr-dropdown__content__item', function(e) {
    $(this)
      .closest('.ftr-js-dropdown__content')
      .removeClass('on');
  });
  function removeDropdown() {
    $('.ftr-js-dropdown__content').removeClass('on');
    $('.ftr-js-select').removeClass('on');
  }

  $('.ftr-main').on('click', '.ftr-js-swipe-content-display', function(e) {
    e.preventDefault();

    var swipeContent = '';

    if (
      $(this)
        .next()
        .hasClass('ftr-js-swipe-content')
    ) {
      swipeContent = $(this).next('.ftr-js-swipe-content');
    } else {
      swipeContent = $('#' + $(this).data('swipe-content'));
    }

    $('.ftr-js-swipe-content').css({ right: '-100vw' });
    $('.ftr-js-swipe-content-overlay').remove();
    $('.ftr-main').append('<div class="ftr-swipe-content-overlay ftr-js-swipe-content-overlay"></div>');
    $('.ftr-swipe-content-overlay').css({
      width: 'calc(100% - ' + swipeContent.width() + 'px)',
    });
    $('.ftr-main').one('click', '.ftr-js-swipe-content-overlay', function() {
      contentSwipeDisplayNone();
    });
    $('.ftr-js-container-btn--fixed').css({ bottom: '-70px' });

    swipeContent.css({ right: 0 });
    swipeContent.find('img[id*=captcha][src*=captcha]').each(function() {
      $(this).attr('src', $(this).attr('src'));
    });

    setTimeout(function() {
      $('.ftr-main')
        .find('.ftr-js-swipe-content-overlay')
        .css({ background: 'rgba(0,0,0,.5)' });
    }, 300);
  });

  $('.ftr-main').on('click', '.ftr-js-swipe-content .ftr-js-close', function() {
    contentSwipeDisplayNone();
  });

  $('.ftr-js-swipe-content .ftr-radio').on('change', function() {
    $(this)
      .closest('.ftr-js-swipe-content')
      .prev('.ftr-js-swipe-content-display')
      .find('.ftr-js-swipe-content-display__text')
      .text(
        $(this)
          .next('.ftr-radio-label__text')
          .text()
      );
    contentSwipeDisplayNone();
  });

  var initial = 0;

  //====================== Ajuste da paginação ======================//
  // if ($('.numbers-page').length > 0) {
  //   if ($('.ftr-pagination .first-page').length == 0 || $('.ftr-pagination .last-page').length == 0) {
  //     $('.ftr-pagination .numbers-page').css('width', 'calc(100% - 96px)');
  //   }
  //   // Centraliza a páginação que está selecionada
  //   $('.numbers-page').scrollLeft($('.ftr-pagination .links b').offset().left - $('.ftr-pagination .numbers-page').width() - 10);
  // }

  //====================== Ordenar por ======================//
  if ($('.ftr-js-order').length > 0) {
    $('.ftr-js-order-options').on('click', function() {
      window.location.href = $(this).val();
    });
    if ($('.ftr-js-order-options:checked').length > 0) {
      var textChecked = $('.ftr-js-order-options:checked')
        .next('.ftr-radio-label')
        .find('.ftr-radio-label__text')
        .text();
      $('.ftr-js-order span').html(textChecked);
    }
  }

  $('.ftr-main').on('click', '.ftr-more-information-display', function(e) {
    e.preventDefault();
    if (
      $(this)
        .parent()
        .hasClass('ftr-js-display-more-information')
    ) {
      $(this)
        .addClass('ftr-hidden')
        .siblings('.material-icons')
        .removeClass('ftr-hidden')
        .closest('.ftr-grid__card')
        .find('.ftr-more-information-content')
        .slideDown();
      $('.ftr-more-information-hide').one('click', function(e) {
        e.preventDefault();
        $(this)
          .addClass('ftr-hidden')
          .siblings('.material-icons')
          .removeClass('ftr-hidden')
          .closest('.ftr-grid__card')
          .find('.ftr-more-information-content')
          .slideUp();
      });
    } else {
      $(this)
        .closest('.ftr-grid__card')
        .find('.ftr-more-information-content')
        .slideDown();
      $('.ftr-more-information-hide').one('click', function(e) {
        e.preventDefault();
        $(this)
          .closest('.ftr-more-information-content')
          .slideUp();
      });
    }
  });

  $('.ftr-main').on('click', '.ftr-quantity-wholesale__button', function() {
    var productId = $(this).data('product-id');
    $('#ftr-quantity-wholesale__button-add').prop('disabled', false);
    var $element = $('#ftr-quantity-wholesale__button-add, #aviseme-form.ftr-quantity-wholesale__aviseme');
    $element.data('product-id', productId);
    $element.data('layout-id', $(this).data('layout-id'));
    $('#ftr-quantity-wholesale__quantity')
      .val($(this).data('fator-multiplicador'))
      .data('fator-multiplicador', $(this).data('fator-multiplicador'));

    executaChamadaAjax(
      'index.php?route=product/productPage/getGrade',
      function(data) {
        data = JSON.parse(data);
        var html = '';

        if (data.exibe_product_colors) {
          html += '<div class="ftr-grid-properties">';
          html += '<span class="ftr-text--grey ftr-text--xs">' + data.text_color + '</span>';
          html += '<p class="ftr-text--bold ftr-grid ftr-in-space--n ftr-out-space--b-s ftr-grid--middle">';
          html += '<span>' + data.color_selected + '</span>';
          html += '<i class="material-icons ftr-text--v-middle">&#xE5CC;</i>';
          html += '</p>';
          html += '</div>';
          html += '<div class="ftr-grid-options">';

          html += data.productColors
            .map(function(color) {
              var htmlItem = '';
              htmlItem += '<div class="ftr-flex">';

              htmlItem += '<input type="radio" id="cor_' + color.productcolor_id + '" name="cor"';
              htmlItem += ' class="ftr-radio ftr-js-option-color-grid"';
              htmlItem += color.tem_estoque == 'N' && !data.config_stock_checkout ? 'disabled' : '';
              htmlItem += ' data-id="' + color.productcolor_id + '"';
              htmlItem += ' data-caracteristica="color_id"';
              htmlItem += (data.color_selected == color.description ? 'checked' : '') + '>';

              htmlItem += '<label class="ftr-radio-label ' + (data.tipo_ex_cor ? 'ftr-option-color-grid--image' : '');
              htmlItem += '" for="cor_' + color.productcolor_id + '">';
              htmlItem += '<span class="ftr-radio-label__text">' + color.description + '</span>';
              if (data.tipo_ex_cor) {
                htmlItem += '<img src="' + color.produto_img_princ + '" alt="' + color.description + '">';
              }
              htmlItem += '</label>';

              if (color.primary_color && color.secundary_color) {
                htmlItem += '<div style="width:20px; height: 20px; background: linear-gradient(135deg, ';
                htmlItem += color.primary_color + ' 0%, ' + color.primary_color + ' 50%, ' + color.secundary_color;
                htmlItem += ' 50%, ' + color.secundary_color + ' 100%);box-shadow: 0 0 2px rgba(0,0,0,.5)"></div>';
              } else if (color.primary_color) {
                htmlItem += '<div style="width:20px; height: 20px; background: ' + color.primary_color;
                htmlItem += ';box-shadow: 0 0 2px rgba(0,0,0,.5)"></div>';
              }
              htmlItem += '</div>';
              return htmlItem;
            })
            .join('');
          html += '</div>';
        }

        if (data.exibe_product_sizes) {
          html += '<div class="ftr-grid-properties">';
          html += '<span class="ftr-text--grey ftr-text--xs">' + data.text_size + '</span>';
          html += '<p class="ftr-text--bold ftr-grid ftr-in-space--n ftr-out-space--b-s ftr-grid--middle">';
          html += '<span>' + (data.size_selected ? data.size_selected : 'Escolha o tamanho') + '</span>';
          html += '<i class="material-icons ftr-text--v-middle">&#xE5CC;</i>';
          html += '</p>';
          html += '</div>';
          html += '<div class="ftr-grid-options">';

          html += data.productSizes
            .map(function(size) {
              var htmlItem = '';
              htmlItem += '<div class="ftr-grid ftr-in-space--n">';

              htmlItem += '<input type="radio" id="tamanho_' + size.productsize_id + '" name="tamanho"';
              htmlItem += ' class="ftr-radio ftr-js-option-size-grid" ';
              htmlItem += size.tem_estoque == 'N' && !data.config_stock_checkout ? 'disabled' : '';
              htmlItem += ' data-id="' + size.productsize_id + '" data-caracteristica="size_id" ';
              htmlItem += (data.size_selected == size.description ? 'checked' : '') + '>';

              htmlItem += '<label class="ftr-radio-label" for="tamanho_' + size.productsize_id + '">';
              htmlItem += '<span class="ftr-radio-label__text">' + size.description + '</span>';
              htmlItem += '</label>';
              htmlItem += '</div>';
              return htmlItem;
            })
            .join('');
          html += '</div>';
        }

        if (data.exibe_product_specifications) {
          html += '<div class="ftr-grid-properties">';
          html +=
            '<span class="ftr-text--grey ftr-text--xs">' + data.text_title_specification.replace(':', '') + '</span>';
          html += '<p class="ftr-text--bold ftr-grid ftr-in-space--n ftr-out-space--b-s ftr-grid--middle">';
          html +=
            '<span>' +
            (data.specification_selected ? data.specification_selected : 'Escolha a especificação') +
            '</span>';
          html += '<i class="material-icons ftr-text--v-middle">&#xE5CC;</i>';
          html += '</p>';
          html += '</div>';
          html += '<div class="ftr-grid-options">';

          html += data.productSpecifications
            .map(function(specification) {
              var htmlItem = '';

              htmlItem += '<div class="ftr-grid ftr-in-space--n">';

              htmlItem += '<input type="radio" id="especificacao_' + specification.productspecification_id + '"';
              htmlItem += ' name="especificacao" class="ftr-radio ftr-js-option-specification-grid"';
              htmlItem += specification.tem_estoque == 'N' && !specification.config_stock_checkout ? 'disabled' : '';
              htmlItem += ' data-id="' + specification.productspecification_id + '"';
              htmlItem += ' data-caracteristica="specification_id"';
              htmlItem += specification.specification_selected == specification.description ? 'checked' : '' + '>';

              htmlItem +=
                '<label class="ftr-radio-label" for="especificacao_' + specification.productspecification_id + '">';
              htmlItem += '<span class="ftr-radio-label__text">' + specification.description + '</span>';
              htmlItem += '</label>';
              htmlItem += '</div>';
              return htmlItem;
            })
            .join('');
          html += '<div>';
        }

        $('#ftr-quantity-wholesale__content .grid-options').html(html);
        $('.ftr-grid-properties').on('click', function() {
          $(this)
            .next('.ftr-grid-options')
            .css({ left: '-2px' });
        });
        $('.ftr-grid-options .ftr-radio-label').on('click', function() {
          var container = $(this).closest('.ftr-grid-options'),
            p = container.prev('.ftr-grid-properties').find('p'),
            span = p.find('span');

          span = span.length ? span : $('<span>');
          p.prepend(
            span.text(
              $(this)
                .find('span')
                .text()
            )
          );
          container.css({ left: '110%' });
        });
      },
      'product_id=' + productId,
      'GET'
    );

    var captcha_image = $('<img>').attr({
      id: 'captcha-image',
      src: 'index.php?route=information/contact/captcha',
      alt: 'CAPTCHA',
    });
    $('#ftr-quantity-wholesale__content-aviseme #captcha-container').append(captcha_image);
  });

  $('#ftr-quantity-wholesale__button-add, .ftr-js-quantity-wholesale__button-add').on('click', function() {
    if (route == 'product/product') {
      var data = {};
      data = getUrl(this).selecteds;
      data['quantity'] = $('#ftr-quantity-wholesale__quantity').val();
      $(this).prop('disabled', true);
      addToCart(data);
    } else {
      var container = $(this).closest('.ftr-js-swipe-content'),
        colors = container.find('.ftr-js-option-color-grid'),
        sizes = container.find('.ftr-js-option-size-grid'),
        specifications = container.find('.ftr-js-option-specification-grid'),
        color = colors.filter(':checked'),
        size = sizes.filter(':checked'),
        specification = specifications.filter(':checked');

      if (sizes.length && !size.length) {
        notificationMsg('Selecione o tamanho!', 'error');
        return;
      }

      if (specifications.length && !specification.length) {
        notificationMsg('Selecione a espeficificação!', 'error');
        return;
      }

      $(this).prop('disabled', true);

      addToCart({
        product_id: $(this).data('product-id'),
        color_id: color.data('id'),
        size_id: size.data('id'),
        specification_id: specification.data('id'),
        quantity: $('#ftr-quantity-wholesale__quantity').val(),
        layout_id: $(this).data('layout-id'),
      });
    }
  });

  //== Controles para aumentar ou diminuir a quantidade no QUANTIDADE ATACADO ==
  $('.ftr-js-btn-qtd').on('click', function(e) {
    var $inputqty = $(this)
        .parent()
        .find('.ftr-js-quantity'),
      $fator = $inputqty.data('fator-multiplicador') ? $inputqty.data('fator-multiplicador') : 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('ftr-js-up')) {
      qty = parseInt($inputqty.val()) + $fator;
    } else if ($(this).hasClass('ftr-js-down') && qty > 0) {
      qty = parseInt($inputqty.val()) - $fator;
      if (qty < compare) qty = $fator;
    }
    $inputqty.val(qty);
  });
  $('.ftr-js-product-card-quantity').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
  });

  //========================== MANTER SEMPRE NO FINAL ==========================
  // Carregamento dos CSS específicos da página
  $('[data-styles]').each(function() {
    var hrefStyles = $(this).data('styles');
    if (hrefStyles) {
      // i começa com o valor 1 para não carregar o mainheader.css que já foi carregado no header
      for (var i = 1; i < hrefStyles.length; i++) {
        var link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('href', hrefStyles[i]);
        document.getElementsByTagName('head')[0].appendChild(link);
      }
    }
  });
  $LAB.setGlobalDefaults({ AlwaysPreserveOrder: true });
  var base = document.querySelector('base');
  if (base && base.href) {
    $LAB.setGlobalDefaults({ AlwaysPreserveOrder: true, BasePath: base.href });
  }
  // Carregamento dos scripts específicos da página
  $('[data-scripts]').each(function() {
    var srcScripts = $(this).data('scripts');
    if (srcScripts) {
      // i começa com o valor 1 para não carregar o back-no-repeat.js que já foi carregado no header
      for (var i = 1; i < srcScripts.length; i++) {
        $LAB.script(srcScripts[i]).wait();
      }
    }
  });
});

function loadSpecificSources(json) {
  // Carregamento dos CSS específicos da página
  if (typeof json.styles != 'undefined') {
    var hrefStyles = json.styles;
    if (hrefStyles) {
      for (var i = 0; i < hrefStyles.length; i++) {
        var link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('href', hrefStyles[i]);
        document.getElementsByTagName('head')[0].appendChild(link);
      }
    }
  }

  // Carregamento dos scripts específicos da página
  if (typeof json.scripts != 'undefined') {
    var srcScripts = json.scripts;
    if (srcScripts) {
      for (i = 0; i < srcScripts.length; i++) {
        $LAB
          .setOptions({ AllowDuplicates: true })
          .script(srcScripts[i])
          .wait();
      }
    }
  }
}

$('.ftr-js-product-quantity').on('focus', function(e) {
  e.preventDefault();
});

function initMoveBuyLaterToCart(e, btnToCart) {
  e.preventDefault();
  let product_id = btnToCart.dataset.productId,
    layout_id = btnToCart.dataset.layoutId,
    quantity = btnToCart.dataset.quantity;

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

  addToCart({product_id, quantity, layout_id});
  removeBuyLater(product_id);
};

function initRemoveBuyLater (e, btnRemove) {
  e.preventDefault();
  let product_id = btnRemove.dataset.productId;
  removeBuyLater(product_id);
}
