$('.js-cor').bind('click', function () {
  var obj = $(this)
  var value_cor = obj.hasClass('selected_filtro_img') ? 0 : obj.attr('value')

  $('.js-cor').each(function () {
    $(this).removeClass('selected_filtro_img')
  })
  $('.corimg').each(function () {
    $(this).removeClass('corimg_selected')
  })
  window.opcoes.cor = [value_cor] // TODO: IMPLEMENTAR MAIS DE UMA COR
  if (value_cor > 0) {
    $('._js-cor_' + value_cor).each(function () {
      $(this).addClass('selected_filtro_img')
    })
    $('#i_' + value_cor).addClass('corimg_selected')
  }
  $('[name="cor_id"]').val(value_cor)

  runFiltro()
})

//MOBILE SELECT COR
$('select.select_cor').bind('change', function () {
  var obj = $(this).find('option:selected')
  var id_cor = obj.attr('value')

  $('[name="cor_id"]').val(id_cor)
  var timout = ''

  runFiltro()

  return false
})

$('.js-filtro-ordenar').bind('change', function () {
  var value = $('.js-filtro-ordenar option:selected').val()
  $('[name="filtro_ordenar"]').val(value)
  window.opcoes.ordem = value
  runFiltro()
  return false
})

function ordernarMobile(obj) {
  value = $(obj).data('value')
  $('[name="filtro_ordenar"]').val(value)
  runFiltro()
  Swal.close()
  boxfilter.apply()
  return false
}

$('.js-filtro-preco').bind('change', function () {
  var obj = $('.js-filtro-preco option:selected').val()

  $('[name="filtro_preco"]').val(obj)

  runFiltro()

  return false
})

$('.js-filtro-itens').bind('change', function () {
  var obj = $('.js-filtro-itens option:selected').val()

  $('[name="filtro_itens"]').val(obj)

  runFiltro()

  return false
})

function rebind_img_js_detalhe(){
  $('img.js-detalhe').hover(
      function(){
          var obj = $(this);

          if (!obj.data('original-src')) {
              obj.data('original-src', obj.attr('src'));
          }

          if (obj.data('src1')) {
              var indice = Number(obj.data('indice'));
              var src = 'src' + indice;
              var newImg = new Image();

              if (!obj.data(src)) {
                  src = 'src1';
                  indice = 1;
              } else {
                  indice++;
              }

              obj.data('indice', indice);

              obj.animate({opacity: .9}, 100);

              if (!obj.data('load')) {
                  newImg.onload = function() {
                      obj.data('load', 1);
                      obj.attr('src', this.src);
                      obj.animate({opacity: 1}, 100);
                  };

                  newImg.src = obj.data(src);
              } else {
                  obj.attr('src', obj.data(src));
                  obj.animate({opacity: 1}, 100);
              }
          }
      },
      function(){
          var obj = $(this);
          if (obj.data('original-src')) {
              obj.attr('src', obj.data('original-src'));
              obj.animate({opacity: 1}, 100);
          }
      }
  );
}

$(document).ready(function() {
  rebind_img_js_detalhe();
});

// Carregamento por demanda do Marcos Khoriati
var offset = 24 // offset mantido pelo javascript
var footerHeight

window.loading = false

var footerHeight = $('#footer-site').height() + $('#categoria_destaque_footer').height();

const carregarProdutos = (force = false) => {
  if (
      window.opcoes.categoria +
      window.opcoes.subcategoria +
      window.opcoes.busca != ''
  )
    return $.ajax({
      url: index + 'maisProdutos',
      type: 'post',
      data: window.opcoes,
    })
      .done((result) => {
        if (force) $('.div-produtos').html(result)
        else $('.div-produtos').append(result)
        window.opcoes.offset += offset
        if (result.length > 0) setTimeout(() => (window.loading = false), 500)
        else window.loading = true
        rebind_img_js_detalhe();
      })
      .fail((error) => {
        // mantem o status de loading em caso de erro
        console.log(error)
      })
      .always(() => {
        $('#offsetNumber').val(offset)
      })
  else return Promise.resolve
}

$(document).ready(function () {

  $(window).scroll((e) => {
    let hintPoint =
    document.getElementsByTagName('body')[0].clientHeight - $(window).height()
    let targeted = $(window).scrollTop() >= hintPoint - 600
    if (!window.loading && targeted) {
      window.loading = true
      // rebind_img_js_detalhe()
      carregarProdutos()
    }
  })
})

// aplicacao para o getmoreprodutos no siteapp.class.php
// const loading = new IntersectionObserver(entries => {
//     entries.forEach(e => {
//         //if (e.isIntersecting) {
//             loading.unobserve(e.target)
//             console.log(`last item: ${e.target.querySelector('.ref_produto').innerText}`)
//             maisProdutos(e.target)
//         //}
//     })
// })

// const iObserver = new IntersectionObserver(entries => { console.log('entrada', entries); maisProdutos(); })

// const element = document.querySelector('.footer')

// iObserver.observe(element)

// function maisProdutos(old_item) {
//     var limit = true;
//     var carregando = true;
//     var pagina = 1;

//     $("#load_data_circle").show();
//     if (limit) {
//         if (carregando) {
//             carregando = false;
//             $.ajax({
//                 url: index + "getMoreProdutos/"
//                 , success: function (out) {
//                     if (out != "0" && out != 0) {
//                         $("#produtos_lista").append(out);
//                         pagina++;
//                         rebind_img_js_detalhe();
//                         timeout = setTimeout(initOwlCarousel(), 500);

//                         new_item = document.querySelector('#produtos_lista .row:last-child .div-produto:last-of-type')

//                         //if (new_item != old_item) {
//                             console.log(`new item: ${new_item.querySelector('.ref_produto').innerText}`)
//                             //loading.observe(new_item)
//                         //}
//                     } else {
//                         limit = true;
//                     }
//                     carregando = true;
//                 }
//             });
//         }
//     }
//     $('#load_data_circle').hide();
// }

$(document).ready(function () {
  $('.lazy').lazyload()
  // if (document.querySelector('#produtos_lista .row:last-child>*').childElementCount >= 6) {
  //     loading.observe(document.querySelector('#produtos_lista .row:last-child .div-produto:last-of-type'))
  // }
  // Filtro de preco
  $('.nstSlider').nstSlider({
    crossable_handles: false,
    left_grip_selector: '.leftGrip',
    right_grip_selector: '.rightGrip',
    value_bar_selector: '.bar',
    value_changed_callback: function (cause, leftValue, rightValue) {
      $(this)
        .parent()
        .find('.leftLabel')
        .text('R$ ' + leftValue)
      $(this)
        .parent()
        .find('.rightLabel')
        .text('R$ ' + rightValue)
    },
    user_mouseup_callback: function (vmin, vmax, left_grip_moved) {
      $('[name="faixa_preco[de]"]').val(vmin)
      $('[name="faixa_preco[ate]"]').val(vmax)
      runFiltro()
    },
  })

  /**banner categoria slide */
  var bannerCategoria = new Swiper('#banner_categoria', {
    speed: 400,
    spaceBetween: 1,
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
      renderBullet: function (index, className) {
        return ''
      },
    },
  })
})

function runFiltro() {
  window.opcoes.offset = 0
  carregarProdutos(true).then(() => {})
  $('html, body').animate(
    {
      scrollTop: $('#_conteudo_listagem').offset().top,
    },
    1000,
  )

  // var opts = {
  //     url: index + 'filtrar'
  //     , data: $('.js-filtro *').serialize()
  //     , beforeSend: function () {
  //         $(' #produtos_lista').animate({ opacity: .7 }, 100)
  //     }
  //     , success: function (out) {
  //         $(' #produtos_lista').hide().html(out).delay(300).slideDown().delay(100).animate({ opacity: 1 }, 100)
  //         setTimeout(function () { $("#qtd_produtos_list").html($(".part_produto").size()); }, 200);

  //         $('html, body').animate({
  //             scrollTop: $("#_conteudo_listagem").offset().top
  //         }, 1000);

  //         rebind_img_js_detalhe();
  //         setTimeout(function () { initOwlCarousel(); }, 500);
  //     }
  // };

  // $.ajax(opts);
}

/** */
let swiperfiltro

/**
 * FILTRO BOX
 * Abre e fecha filtro de cor e ordenação */
const boxfilter = {
  boxAtual: '',
  showBox: function (box, elem) {
    this.hideBox()
    if (this.boxAtual != box) {
      this.boxAtual = box
      $('#' + box).slideDown()
      $(elem).addClass('yellow-bg')
    } else this.boxAtual = ''
  },
  hideBox: function () {
    $('._filter_box').slideUp('fast')
    $('._bt_box_filtro').removeClass('yellow-bg')
  },
  clear: function () {
    this.hideBox()
    this.boxAtual = ''
    $('.js-cor').each(function () {
      $(this).removeClass('selected_filtro_img')
    })
    $('[name="cor_id"]').val(0)
    runFiltro()
  },
  apply: function () {
    this.hideBox()
    this.boxAtual = ''
  },
}
/** *** *** */

function mobFiltroPreco(obj) {
  $('._preco_checked').remove()
  data = (el = $(obj)).data()
  $('[name="faixa_preco[de]"]').val(data.de)
  $('[name="faixa_preco[ate]"]').val(data.ate)
  el.prepend(
    '<span class="_preco_checked"><i class="fa fa-check" aria-hidden="true"></i>&nbsp;&nbsp;</span>',
  )
  swiperfiltro.slideNext(1500)
}

function mobFiltroCor(obj) {
  $('.filter_cor_mob').each(function () {
    $(this).removeClass('filter_li_selected')
  })
  data = (el = $(obj)).data()
  el.addClass('filter_li_selected')
}

function mobFiltroLimpa() {
  $('[name="faixa_preco[de]"]').val('')
  $('[name="faixa_preco[ate]"]').val('')
  $('[name="cor_id"]').val('')
  runFiltro()
  Swal.close()
}

function mobFiltrar() {
  runFiltro()
  Swal.close()
}

// rebind_img_js_detalhe()

function show_filter(name) {
  ele = $('#action_filter_' + name)

  switch (name) {
    case 'categoria':
      $('#subcategorias').slideToggle()
      if (ele.hasClass('plus-img')) {
        ele.removeClass('plus-img')
        ele.addClass('minus-img')
        ele.attr('src', '../img/icons/minus-icon.png?a=1')
      } else {
        ele.removeClass('minus-img')
        ele.addClass('plus-img')
        ele.attr('src', '../img/icons/plus-icon.png?a=1')
      }
      break

    case 'cores':
      $('#subcores').slideToggle()
      if (ele.hasClass('plus-img')) {
        ele.removeClass('plus-img')
        ele.addClass('minus-img')
        ele.attr('src', '../img/icons/minus-icon.png?a=1')
      } else {
        ele.removeClass('minus-img')
        ele.addClass('plus-img')
        ele.attr('src', '../img/icons/plus-icon.png?a=1')
      }
      break

    case 'maisvendidos':
      $('#maisvendidos').slideToggle()
      if (ele.hasClass('plus-img')) {
        ele.removeClass('plus-img')
        ele.addClass('minus-img')
        ele.attr('src', '../img/icons/minus-icon.png?a=1')
      } else {
        ele.removeClass('minus-img')
        ele.addClass('plus-img')
        ele.attr('src', '../img/icons/plus-icon.png?a=1')
      }
  }
}
