/home/bdqbpbxa/demo-subdomains/nanobiomedical.goodface.com.ua/frontend/js/script.js
// Check input for the focus

let inputAndTextarea = $('.input-box input, .input-box textarea');

inputAndTextarea.on('focus', function() {
  $(this).closest('.input-box').addClass('-focus');
  removeNotValid($(this));
})

inputAndTextarea.on('blur', function() {
  $(this).closest('.input-box').removeClass('-focus');
})

// Check input for the text

inputAndTextarea.on('change', function() {
  checkInputAboutText($(this));
  removeNotValid($(this));
})

function checkInputAboutText(input) {
  let inputValue = input.val();
  let father = input.closest('.input-box');

  if (inputValue.length > 0) {
    father.addClass('-has-text');
  } else {
    father.removeClass('-has-text');
  }
}

// Add -error class for input

function notValid(input) {
  input.closest('.input-box').addClass('-error')
}

function removeNotValid(input) {
  input.closest('.input-box').removeClass('-error')
}

// Make preloader work

$(window).on('load', preloaderFunction);

function preloaderFunction() {
  $('.preloader').addClass('-finish');
  let postType = $('.preloader').data('post-type');
  if (postType != 'product') {
    unlockScroll();
  }
  console.log(postType);
  window.dispatchEvent(new Event('triggerScrollbarWidthUpdate'));
}

// Adding button "show more text" to spoilers

$(window).on('load resize', addShowButton);

$(window).resize();

function addShowButton() {
  if (!isPc) {
    $('.mobile-hidden-content').each(function () {

        let maxCountOfRow = $(this).data('max-row');
        let buttonText = $(this).data('button-text');
        let hiddenHeight = $(this).find('.mobile-hidden-content__inner').innerHeight();
        let maxHeight = parseFloat($(this).find('.mobile-hidden-content__inner').css('line-height')) * maxCountOfRow;

        if (hiddenHeight > maxHeight) {
          if (!$(this).find('.show-more-text').length) {
            $(this).css('height', maxHeight);
            $(this).append(`<span class="show-more-text mob-text-3">${buttonText}</span>`);
            $(this).removeClass('-active');
          }
        } else {
          if (!$(this).find('.show-more-text').length) {
            return;
          } else {
            $(this).css('height', 'auto');
            $(this).find('.show-more-text').remove();
            $(this).removeClass('-active');
          }
        }
    })
  }
}

// Make work "show more text" button

$(document).on('click', '.show-more-text', function(e) {
  e.preventDefault();
  let container = $(this).closest('.mobile-hidden-content');
  let hiddenTextHeight = container.find('.text').innerHeight();

  container.css('height', hiddenTextHeight);
  container.addClass('-active')

  // transitionEnd(container, "height", function() {
  //   container.css("height", "auto");
  //   container.find('.show-more-text').remove();
  // })
})


function transitionEnd(element, property, callback) {

  $(element).on('transitionend', function(e) {
    let transitionProperty = e.originalEvent.propertyName;

    if (transitionProperty.toLowerCase() === property && $(e.target).is(element)) {
      callback(element);
    }
  });

}

// Resize header on resize

$(window).on('resize', checkHeaderHeight);

function checkHeaderHeight() {
  let header = $('.header');
  let mobileMenuHeight = header.find('.header__mobile-wrapper').innerHeight();
  if (header.hasClass('-active')) {
    let openHeaderHeight = oldHeaderHeight + mobileMenuHeight;
    header.css('height', openHeaderHeight);
  } else {
    oldHeaderHeight = header.innerHeight();
    header.css('height', oldHeaderHeight);
  }
}

// Open/close mobile menu

let oldHeaderHeight;

$(window).on('load', function() {
  let header = $('.header');
  oldHeaderHeight = header.innerHeight();
  header.css('height', oldHeaderHeight);
})

$('.mobile-menu-opener').on('click', function() {
  let header = $(this).closest('.header');
  let mobileMenuHeight = header.find('.header__mobile-wrapper').innerHeight();

  $(this).find('.burger').toggleClass('-active');
  header.toggleClass('-active');
  $('.mobile-menu-background').toggleClass('-active');

  if (!header.hasClass('-active')) {

    header.css('height', oldHeaderHeight);
    header.addClass('-clothing');
    unlockScroll();
  } else {

    let openHeaderHeight = oldHeaderHeight + mobileMenuHeight;

    header.css('height', openHeaderHeight);
    lockScroll();
    transitionEnd(header, 'height', function() {
      header.removeClass('-clothing');
    })
  }

})

$('.mobile-menu-background').on('click',function() {
  $('.mobile-menu-opener').click();
})

// Filled header after scroll

$(document).ready(headerFilledScroll);
$(window).scroll(headerFilledScroll);

function headerFilledScroll() {
  let scrollTop = window.scrollY;
  if (scrollTop > 0) {
    $('.header').addClass('-filled');
  } else {
    if ($('body').hasClass('-scroll-lock')) {
      return
    } else {
      $('.header').removeClass('-filled');
    }
  }
}

$(window).on('load', function () {

  // Init main slider

  if ($('.main__slider').length) {
    const swiper = new Swiper('.main__slider', {
      speed: 400,
      effect: 'fade',
      loop: true,
      slidesPerView: 1,
      slidesPerGroup: 1,
      pagination: {
        el: '.swiper-pagination',
        type: 'bullets',
        clickable: true,
      },
      autoplay: {
        delay: 3000,
      }
    });
  }

  // Init product slider

  if ($('.products-section__slider').length) {
    $('.products-section__slider').each(function (index) {
      let thisElement = $(this);
      let prevButton = thisElement.closest('.products-section').find('.products-section__navigation .prev');
      let nextButton =  thisElement.closest('.products-section').find('.products-section__navigation .next');

      if (window.innerWidth < 1025) {
        $(thisElement).find('.brand-card').remove();
      }

      let productSwiper = new Swiper(thisElement[0], {
        slidesPerView: 'auto',
        slidesPerGroup: 1,
        spaceBetween: 10,
        loop: false,
        autoHeight: true,
        navigation: {
          nextEl: nextButton[0],
          prevEl: prevButton[0],
        },
        breakpoints: {
          769: {
            slidesPerGroup: 1,
            spaceBetween: 30,
            loop: true,
            autoHeight: false,
          }
        },
        on: {
          afterInit: function () {
            addShowButton();
            this.update();
          },
        }
      });
      ``
      let container = $(this).find('.mobile-hidden-content');

      transitionEnd(container, "height", function() {
        productSwiper.updateAutoHeight(400);
      })
    })
  }

  // Init reviews slider

  let reviewSlider = $('.reviews__slider');
  if (reviewSlider.length) {
    let navigationContainer = reviewSlider.closest('.reviews');

    if (isPc || isSmallPc) {
      navigationContainer = reviewSlider.closest('.navigation-wrapper');
    }

    let prevButton = navigationContainer.find('.reviews__navigation .prev');
    let nextButton =  navigationContainer.find('.reviews__navigation .next');

    const reviewsSwiper = new Swiper('.reviews__slider', {
      speed: 400,
      slidesPerView: 'auto',
      slidesPerGroup: 1,
      spaceBetween: 20,
      navigation: {
        nextEl: nextButton[0],
        prevEl: prevButton[0],
      },
      autoHeight: true,
      breakpoints: {
        760: {
          spaceBetween: 40,
        },
        769: {
          autoHeight: false,
        },
        1024: {
          spaceBetween: 80,
        },
      },
      on: {
        afterInit: function () {
          addShowButton();
          this.update();
        },
      }
    });

    let container = reviewSlider.find('.mobile-hidden-content');

    transitionEnd(container, "height", function() {
      reviewsSwiper.updateAutoHeight(400);
    })
  }

  // Init main slider on single page

  if ($('.main-single__slider').length) {
    const swiper = new Swiper('.main-single__slider', {
      speed: 400,
      effect: 'fade',
      loop: true,
      slidesPerView: 1,
      slidesPerGroup: 1,
      pagination: {
        el: '.swiper-pagination',
        type: 'bullets',
        clickable: true,
      },
      autoplay: {
        delay: 3000,
      }
    });
  }

  // Init product description slider

  if ($('.product-info__slider').length) {

    const singleProductSwiper = new Swiper('.product-info__slider', {
      speed: 400,
      slidesPerView: 'auto',
      slidesPerGroup: 1,
    });
  }
})


// Make work products gallery

$(document).on('click', '.product-info__slider .swiper-slide', function() {
  let thisElement = $(this);
  let bigContainer = thisElement.closest('.product-info__gallery').find('.product-info__mobile-img');

  if (thisElement.hasClass('video-slide')) {
    if (isPc) {
      insertYoutubeIframe(thisElement, thisElement);
    } else {
      insertYoutubeIframe(thisElement, bigContainer);
    }
  } else {
    let imgSrc = thisElement.find('img').attr('src');
    let imgAlt = thisElement.find('img').attr('alt');
    bigContainer.html(`<img src="${imgSrc}" alt="${imgAlt}">`);
  }
});

function insertYoutubeIframe(videoContainer, iframePlacedContainer) {
  // videoContainer - where placed data-href
  // iframePlacedContainer - where to insert iframe
  let videoSrc = videoContainer.data('href');
  iframePlacedContainer.html(`<iframe src = "https://www.youtube.com/embed/${videoSrc}?rel=0&showinfo=0&autoplay=1" frameBorder="0" allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen> </iframe>`)
}

function animationLineBlockReady(block) {
  const part = block.find(".animation-line");
  const partWidth = part.outerWidth();
  const windowWidth = window.screen.width;

  let partDublicateCount;
  let partHtml = part[0].outerHTML;
  let appendHtml = "";

  if (partWidth >= windowWidth) {
    partDublicateCount = 1;
  } else {
    partDublicateCount = Math.ceil(windowWidth / partWidth) * 2 - 1;
  }

  for (let i = 0; i < partDublicateCount; i++) {
    appendHtml += partHtml;
  }

  block.append(appendHtml);

  startAnimationLineBlock(block, partWidth);
}

function startAnimationLineBlock(block, partWidth) {
  let speed = 0.5 * (partWidth / 100);
  if (isPc) {
    speed = ((speed / 100) * 20) + speed;
  } else {
    speed = ((speed / 100) * 50) + speed;
  }
  const animationVal = `animation-line ${speed}s linear infinite`;

  block.find(".animation-line").css({
    animation: animationVal,
  });
}

$(document).ready(function () {
  if (!$('.animation-line-block').length) return;

  animationLineBlockReady($('.animation-line-block'));
});

// Instagram slider

$(document).ready(function () {
  const instagramSlider = $('.instagram-section__slider');

  if (!instagramSlider.length) return;

  const section = instagramSlider.closest('.instagram-section');
  const prevButton = section.find('.products-section__navigation .prev');
  const nextButton =  section.find('.products-section__navigation .next');

  let slider = new Swiper(instagramSlider[0], {
    slidesPerView: 1,
    slidesPerGroup: 1,
    spaceBetween: 10,
    loop: false,

    navigation: {
      nextEl: nextButton[0],
      prevEl: prevButton[0],
    },

    breakpoints: {
      600: {
        slidesPerView: 'auto',
        spaceBetween: 30,
      }
    },
  });
});

// Preparing/Open modal window

$(window).on('load', function () {
  const modal = $('.modal-wrapper');

  if (!modal.length) return;

  modal.removeClass('-hide');
});

let clickableZone = '.product-card__img, .product-card .title, .product-card .mobile-hidden-content__inner';

if (isPc || isSmallPc) {
  clickableZone = '.product-card';
}

$(document).on('click', clickableZone, function (e) {
  e.preventDefault();
  let card =  $(this).closest('.product-card');
  let productId = card.data('product-id');

  productAjaxLoader(productId);
  openProductModal();
});

function openProductModal() {
  const modal = $('.modal-product');
  if ( !modal.length ) return;

  lockScroll();
  modal.addClass('-active');
}

$(document).on('click', '.-open-consultation-modal', function () {
  const modal = $('.consultation-modal');

  if ( !modal.length ) return;

  if ( !$('.mobile-menu-opener .burger.-active').length ) {
    if ( !$('.modal-product.-active').length ) lockScroll();
  }

  modal.addClass('-active');
});

// Close modal window

$(document).on('click', '.modal-wrapper .burger', function () {
  const modal = $(this).closest('.modal-wrapper');

  if ( !$('.mobile-menu-opener .burger.-active').length ) {
    if ($(this).closest('.modal-wrapper').hasClass('modal-product')) {
      unlockScroll();
    } else {
      if ( !$('.modal-product.-active').length ) unlockScroll();
    }
  }

  modal.removeClass('-active');
  window.dispatchEvent(new Event('triggerScrollbarWidthUpdate'));
});

$(document).on('click', '.modal-wrapper', function (e) {
  const isModal = $(e.target).is('.modal') || $(e.target).closest('.modal').length

  if (isModal) return;

  if ( !$('.mobile-menu-opener .burger.-active').length ) {
    if ($(this).closest('.modal-wrapper').hasClass('modal-product')) {
      unlockScroll();
    } else {
      if ( !$('.modal-product.-active').length ) unlockScroll();
    }
  }

  $(this).removeClass('-active');
});



// Form validation

function noValidFunction(inputName) {
  let parent = inputName.closest(".input-box");
  parent.addClass("-error");
}

function showThanksWindow(ths) {
  const getContainer = $(ths).closest(".send-form-container");
  getContainer.addClass("-sent");
}

$(document).on("submit", ".form form", function (e) {
  e.preventDefault();

  let isValid = true;

  let name = $(this).find(".name");
  let phone = $(this).find(".phone");

  $(this).find(".input").removeClass("-error");

  if (name.length) {
    if (name.val().length < 1) {
      isValid = false;
      noValidFunction(name);
    }
  }

  if (phone.length) {
    if (!phone.inputmask("isComplete")) {
      isValid = false;
      noValidFunction(phone);
    }
  }

  if (isValid) {
    if ($(this).closest(".send-form-container").length) showThanksWindow(this);
  }
});

// Phone's mask

if ($('.phone-mask').length) {
  $('.phone-mask').inputmask('mask', {
    'mask': '+38 999 999 99 99',
    showMaskOnHover: false,
  });
}

// Anchor links

$(document).on('click', '.anchor-link', function() {
  let id = $(this).attr('href');
  let headerHeight = $('.header').innerHeight();
  let height = $(id).offset().top - headerHeight * 2;
  $('body,html').animate({scrollTop: height}, 1000);
})

// adding/removing dots in brand name in about-us section

$(window).on('load', updateBrandDots);
$(window).on('resize', updateBrandDots);

function updateBrandDots() {
  let offsetTop;
  $('.about-us .text a.-dot-before').removeClass('-dot-before');

  $('.about-us .text a').each(function(index) {
    let thisOffset = $(this).offset().top;

    if (index !== 0) {
      if (offsetTop === thisOffset) {
        $(this).addClass('-dot-before');
      }
    }
    offsetTop = thisOffset;
  })
}

/**/
/*
/*
/*
/* BACKEND SCRIPTS */
/*
/*
/**/

$(window).on('load', checkLoadMoreButton);

function checkLoadMoreButton() {
  const ajaxFilterContent = $(".single-product-section__wrapper");

  let realProductsCount = ajaxFilterContent.find('.product-card').length;
  let maxProductCount = ajaxFilterContent.data('max-count');

  if (realProductsCount >= maxProductCount) {
    $('.load-more').remove();
  }
}


// Brand ajax load more

const brandAjxLoadMoreParmeters = {};
var brandPage = 1;

$('.load-more').click(brandjaxFilter);

function brandjaxFilter() {
  const ajaxFilterContent = $(".single-product-section__wrapper");
  const ajaxUrl = ajaxFilterContent.data("ajax-url");
  if (!ajaxFilterContent.length) {
    return;
  }

  ajaxFilterContent.addClass("-loading");
  brandPage++;

  brandAjxLoadMoreParmeters.category = ajaxFilterContent.data("brand-slug");
  brandAjxLoadMoreParmeters.page = brandPage;

  $.ajax({
    type: "POST",
    url: ajaxUrl,
    data: {
      action: "brand_load_more_post",
      isStatic: false,
      page: brandAjxLoadMoreParmeters.page,
      category: brandAjxLoadMoreParmeters.category,
    },
    success(html) {
      ajaxFilterContent.append(html);

      checkLoadMoreButton();

      ajaxFilterContent.removeClass("-loading");
    },
    error(e) {
      alert(e);
    },
  });
}



// Open modal product ajax

function productAjaxLoader(productId) {
  const ajaxFilterContent = $(".modal-product");
  const ajaxUrl = ajaxFilterContent.data("ajax-url");

  if (!ajaxFilterContent.length) {
    return;
  }
  ajaxFilterContent.addClass('-loading');

  $.ajax({
    type: "POST",
    url: ajaxUrl,
    data: {
      action: "product_modal_loading",
      post_id: productId,
    },
    success(html) {
      ajaxFilterContent.removeClass('-loading');
      ajaxFilterContent.find('.modal-content').html(html);
    },
    error(e) {
      alert(e);
    },
  });
}