/**
* Template Name: HeroBiz
* Template URL: https://bootstrapmade.com/herobiz-bootstrap-business-template/
* Updated: Mar 17 2024 with Bootstrap v5.3.3
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
*/

document.addEventListener('DOMContentLoaded', () => {
  "use strict";

  /**
   * Preloader
   */
  const preloader = document.querySelector('#preloader');
  if (preloader) {
    window.addEventListener('load', () => {
      preloader.remove();
    });
  }

  /**
   * Sticky header on scroll
   */
  const selectHeader = document.querySelector('#header');
  if (selectHeader) {
    document.addEventListener('scroll', () => {
      window.scrollY > 100 ? selectHeader.classList.add('sticked') : selectHeader.classList.remove('sticked');
    });
  }

  /**
   * Navbar links active state on scroll
   */
  let navbarlinks = document.querySelectorAll('#navbar .scrollto');

  function navbarlinksActive() {
    navbarlinks.forEach(navbarlink => {

      if (!navbarlink.hash) return;

      let section = document.querySelector(navbarlink.hash);
      if (!section) return;

      let position = window.scrollY;
      if (navbarlink.hash != '#header') position += 200;

      if (position >= section.offsetTop && position <= (section.offsetTop + section.offsetHeight)) {
        navbarlink.classList.add('active');
      } else {
        navbarlink.classList.remove('active');
      }
    })
  }
  window.addEventListener('load', navbarlinksActive);
  document.addEventListener('scroll', navbarlinksActive);

  /**
   * Function to scroll to an element with top ofset
   */
  function scrollto(el) {
    const selectHeader = document.querySelector('#header');
    let offset = 0;

    if (selectHeader.classList.contains('sticked')) {
      offset = document.querySelector('#header.sticked').offsetHeight;
    } else if (selectHeader.hasAttribute('data-scrollto-offset')) {
      offset = selectHeader.offsetHeight - parseInt(selectHeader.getAttribute('data-scrollto-offset'));
    }
    window.scrollTo({
      top: document.querySelector(el).offsetTop - offset,
      behavior: 'smooth'
    });
  }

  /**
   * Fires the scrollto function on click to links .scrollto
   */
  let selectScrollto = document.querySelectorAll('.scrollto');
  selectScrollto.forEach(el => el.addEventListener('click', function(event) {
    if (document.querySelector(this.hash)) {
      event.preventDefault();

      let mobileNavActive = document.querySelector('.mobile-nav-active');
      if (mobileNavActive) {
        mobileNavActive.classList.remove('mobile-nav-active');

        let navbarToggle = document.querySelector('.mobile-nav-toggle');
        navbarToggle.classList.toggle('bi-list');
        navbarToggle.classList.toggle('bi-x');
      }
      scrollto(this.hash);
    }
  }));

  /**
   * Scroll with ofset on page load with hash links in the url
   */
  window.addEventListener('load', () => {
    if (window.location.hash) {
      if (document.querySelector(window.location.hash)) {
        scrollto(window.location.hash);
      }
    }
  });

  /**
   * Mobile nav toggle
   */
  const mobileNavToogle = document.querySelector('.mobile-nav-toggle');
  if (mobileNavToogle) {
    mobileNavToogle.addEventListener('click', function(event) {
      event.preventDefault();

      document.querySelector('body').classList.toggle('mobile-nav-active');

      this.classList.toggle('bi-list');
      this.classList.toggle('bi-x');
    });
  }

  /**
   * Toggle mobile nav dropdowns
   */
  const navDropdowns = document.querySelectorAll('.navbar .dropdown > a');

  navDropdowns.forEach(el => {
    el.addEventListener('click', function(event) {
      if (document.querySelector('.mobile-nav-active')) {
        event.preventDefault();
        this.classList.toggle('active');
        this.nextElementSibling.classList.toggle('dropdown-active');

        let dropDownIndicator = this.querySelector('.dropdown-indicator');
        dropDownIndicator.classList.toggle('bi-chevron-up');
        dropDownIndicator.classList.toggle('bi-chevron-down');
      }
    })
  });

  /**
   * Auto generate the hero carousel indicators
   */
  let heroCarouselIndicators = document.querySelector('#hero .carousel-indicators');
  if (heroCarouselIndicators) {
    let heroCarouselItems = document.querySelectorAll('#hero .carousel-item')

    heroCarouselItems.forEach((item, index) => {
      if (index === 0) {
        heroCarouselIndicators.innerHTML += `<li data-bs-target="#hero" data-bs-slide-to="${index}" class="active"></li>`;
      } else {
        heroCarouselIndicators.innerHTML += `<li data-bs-target="#hero" data-bs-slide-to="${index}"></li>`;
      }
    });
  }

  /**
   * Scroll top button
   */
  const scrollTop = document.querySelector('.scroll-top');
  if (scrollTop) {
    const togglescrollTop = function() {
      window.scrollY > 100 ? scrollTop.classList.add('active') : scrollTop.classList.remove('active');
    }
    window.addEventListener('load', togglescrollTop);
    document.addEventListener('scroll', togglescrollTop);
    scrollTop.addEventListener('click', window.scrollTo({
      top: 0,
      behavior: 'smooth'
    }));
  }

  /**
   * Initiate glightbox
   */
  const glightbox = GLightbox({
    selector: '.glightbox'
  });

  /**
   * Porfolio isotope and filter
   */
  let portfolionIsotope = document.querySelector('.portfolio-isotope');

  if (portfolionIsotope) {

    let portfolioFilter = portfolionIsotope.getAttribute('data-portfolio-filter') ? portfolionIsotope.getAttribute('data-portfolio-filter') : '*';
    let portfolioLayout = portfolionIsotope.getAttribute('data-portfolio-layout') ? portfolionIsotope.getAttribute('data-portfolio-layout') : 'masonry';
    let portfolioSort = portfolionIsotope.getAttribute('data-portfolio-sort') ? portfolionIsotope.getAttribute('data-portfolio-sort') : 'original-order';

    window.addEventListener('load', () => {
      let portfolioIsotope = new Isotope(document.querySelector('.portfolio-container'), {
        itemSelector: '.portfolio-item',
        layoutMode: portfolioLayout,
        filter: portfolioFilter,
        sortBy: portfolioSort
      });

      let menuFilters = document.querySelectorAll('.portfolio-isotope .portfolio-flters li');
      menuFilters.forEach(function(el) {
        el.addEventListener('click', function() {
          document.querySelector('.portfolio-isotope .portfolio-flters .filter-active').classList.remove('filter-active');
          this.classList.add('filter-active');
          portfolioIsotope.arrange({
            filter: this.getAttribute('data-filter')
          });
          if (typeof aos_init === 'function') {
            aos_init();
          }
        }, false);
      });

    });

  }

  /**
   * Clients Slider
   */
  new Swiper('.clients-slider', {
    speed: 400,
    loop: true,
    autoplay: {
      delay: 5000,
      disableOnInteraction: false
    },
    slidesPerView: 'auto',
    breakpoints: {
      320: {
        slidesPerView: 2,
        spaceBetween: 40
      },
      480: {
        slidesPerView: 3,
        spaceBetween: 60
      },
      640: {
        slidesPerView: 4,
        spaceBetween: 80
      },
      992: {
        slidesPerView: 6,
        spaceBetween: 120
      }
    }
  });

  /**
   * Testimonials Slider
   */
  new Swiper('.testimonials-slider', {
    speed: 600,
    loop: true,
    autoplay: {
      delay: 5000,
      disableOnInteraction: false
    },
    slidesPerView: 'auto',
    pagination: {
      el: '.swiper-pagination',
      type: 'bullets',
      clickable: true
    }
  });

  /**
   * Testimonials Slider
   */
  new Swiper('.portfolio-details-slider', {
    speed: 600,
    loop: true,
    autoplay: {
      delay: 5000,
      disableOnInteraction: false
    },
    slidesPerView: 'auto',
    pagination: {
      el: '.swiper-pagination',
      type: 'bullets',
      clickable: true
    }
  });

  /**
   * Animation on scroll function and init
   */
  function aos_init() {
    AOS.init({
      duration: 1000,
      easing: 'ease-in-out',
      once: true,
      mirror: false
    });
  }
  window.addEventListener('load', () => {
    aos_init();
  });

});



    // utility functions
    if (!Util)
    function Util() {};

    Util.addClass = function(el, className) {
        var classList = className.split(' ');
        el.classList.add(classList[0]);
        if (classList.length > 1) Util.addClass(el, classList.slice(1).join(' '));
    };

    Util.removeClass = function(el, className) {
        var classList = className.split(' ');
        el.classList.remove(classList[0]);
        if (classList.length > 1) Util.removeClass(el, classList.slice(1).join(' '));
    };

    Util.toggleClass = function(el, className, bool) {
        if (bool) Util.addClass(el, className);
        else Util.removeClass(el, className);
    };

    Util.moveFocus = function(element) {
        if (!element) element = document.getElementsByTagName('body')[0];
        element.focus();
        if (document.activeElement !== element) {
            element.setAttribute('tabindex', '-1');
            element.focus();
        }
    };

    Util.getIndexInArray = function(array, el) {
        return Array.prototype.indexOf.call(array, el);
    };


    // File#: _1_language-picker
    // Usage: codyhouse.co/license
    (function() {
        var LanguagePicker = function(element) {
            this.element = element;
            this.select = this.element.getElementsByTagName('select')[0];
            this.options = this.select.getElementsByTagName('option');
            this.selectedOption = getSelectedOptionText(this);
            this.pickerId = this.select.getAttribute('id');
            this.trigger = false;
            this.dropdown = false;
            this.firstLanguage = false;
            // dropdown arrow inside the button element
            this.arrowSvgPath = '<svg viewBox="0 0 16 16"><polygon points="3,5 8,11 13,5 "></polygon></svg>';
            this.globeSvgPath = '<svg viewBox="0 0 16 16"><path d="M8,0C3.6,0,0,3.6,0,8s3.6,8,8,8s8-3.6,8-8S12.4,0,8,0z M13.9,7H12c-0.1-1.5-0.4-2.9-0.8-4.1 C12.6,3.8,13.6,5.3,13.9,7z M8,14c-0.6,0-1.8-1.9-2-5H10C9.8,12.1,8.6,14,8,14z M6,7c0.2-3.1,1.3-5,2-5s1.8,1.9,2,5H6z M4.9,2.9 C4.4,4.1,4.1,5.5,4,7H2.1C2.4,5.3,3.4,3.8,4.9,2.9z M2.1,9H4c0.1,1.5,0.4,2.9,0.8,4.1C3.4,12.2,2.4,10.7,2.1,9z M11.1,13.1 c0.5-1.2,0.7-2.6,0.8-4.1h1.9C13.6,10.7,12.6,12.2,11.1,13.1z"></path></svg>';

            initLanguagePicker(this);
            initLanguagePickerEvents(this);
        };

        function initLanguagePicker(picker) {
            // create the HTML for the custom dropdown element
            picker.element.insertAdjacentHTML('beforeend', initButtonPicker(picker) + initListPicker(picker));

            // save picker elements
            picker.dropdown = picker.element.getElementsByClassName('language-picker__dropdown')[0];
            picker.languages = picker.dropdown.getElementsByClassName('language-picker__item');
            picker.firstLanguage = picker.languages[0];
            picker.trigger = picker.element.getElementsByClassName('language-picker__button')[0];
        };

        function initLanguagePickerEvents(picker) {
            // make sure to add the icon class to the arrow dropdown inside the button element
            var svgs = picker.trigger.getElementsByTagName('svg');
            Util.addClass(svgs[0], 'li4-icon');
            Util.addClass(svgs[1], 'li4-icon');
            // language selection in dropdown
            // ⚠️ Important: you need to modify this function in production
            initLanguageSelection(picker);

            // click events
            picker.trigger.addEventListener('click', function() {
                toggleLanguagePicker(picker, false);
            });
            // keyboard navigation
            picker.dropdown.addEventListener('keydown', function(event) {
                if (event.keyCode && event.keyCode == 38 || event.key && event.key.toLowerCase() == 'arrowup') {
                    keyboardNavigatePicker(picker, 'prev');
                } else if (event.keyCode && event.keyCode == 40 || event.key && event.key.toLowerCase() == 'arrowdown') {
                    keyboardNavigatePicker(picker, 'next');
                }
            });
        };

        function toggleLanguagePicker(picker, bool) {
            var ariaExpanded;
            if (bool) {
                ariaExpanded = bool;
            } else {
                ariaExpanded = picker.trigger.getAttribute('aria-expanded') == 'true' ? 'false' : 'true';
            }
            picker.trigger.setAttribute('aria-expanded', ariaExpanded);
            if (ariaExpanded == 'true') {
                picker.firstLanguage.focus(); // fallback if transition is not supported
                picker.dropdown.addEventListener('transitionend', function cb() {
                    picker.firstLanguage.focus();
                    picker.dropdown.removeEventListener('transitionend', cb);
                });
                // place dropdown
                placeDropdown(picker);
            }
        };

        function placeDropdown(picker) {
            var triggerBoundingRect = picker.trigger.getBoundingClientRect();
            Util.toggleClass(picker.dropdown, 'language-picker__dropdown--right', (window.innerWidth < triggerBoundingRect.left + picker.dropdown.offsetWidth));
            Util.toggleClass(picker.dropdown, 'language-picker__dropdown--up', (window.innerHeight < triggerBoundingRect.bottom + picker.dropdown.offsetHeight));
        };

        function checkLanguagePickerClick(picker, target) { // if user clicks outside the language picker -> close it
            if (!picker.element.contains(target)) toggleLanguagePicker(picker, 'false');
        };

        function moveFocusToPickerTrigger(picker) {
            if (picker.trigger.getAttribute('aria-expanded') == 'false') return;
            if (document.activeElement.closest('.language-picker__dropdown') == picker.dropdown) picker.trigger.focus();
        };

        function initButtonPicker(picker) { // create the button element -> picker trigger
            // check if we need to add custom classes to the button trigger
            var customClasses = picker.element.getAttribute('data-trigger-class') ? ' ' + picker.element.getAttribute('data-trigger-class') : '';

            var button = '<button class="language-picker__button' + customClasses + '" aria-label="' + picker.select.value + ' ' + picker.element.getElementsByTagName('label')[0].textContent + '" aria-expanded="false" aria-controls="' + picker.pickerId + '-dropdown">';
            button = button + '<span aria-hidden="true" class="language-picker__label language-picker__flag language-picker__flag--' + picker.select.value + '">' + picker.globeSvgPath + '<em>' + picker.selectedOption + '</em>';
            button = button + picker.arrowSvgPath + '</span>';
            return button + '</button>';
        };

        function initListPicker(picker) { // create language picker dropdown
            var list = '<div class="language-picker__dropdown language-picker__dropdown--up" aria-describedby="' + picker.pickerId + '-description" id="' + picker.pickerId + '-dropdown">';
            list = list + '<p class="li4-sr-only" id="' + picker.pickerId + '-description">' + picker.element.getElementsByTagName('label')[0].textContent + '</p>';
            list = list + '<ul class="language-picker__list p-0 m-0" role="listbox" style="list-style-type: none;">';
            for (var i = 0; i < picker.options.length; i++) {
                var selected = picker.options[i].selected ? ' aria-selected="true"' : '',
                    language = picker.options[i].getAttribute('lang');

                list = list + '<li><a lang="' + language + '" hreflang="' + language + '" href="' + getLanguageUrl(picker.options[i]) + '"' + selected + ' role="option" data-value="' + picker.options[i].value + '" class="language-picker__item language-picker__flag language-picker__flag--' + picker.options[i].value + '"><span>' + picker.options[i].text + '</span></a></li>';
            };
            return list;
        };

        function getSelectedOptionText(picker) { // used to initialize the label of the picker trigger button
            var label = '';
            if ('selectedIndex' in picker.select) {
                label = picker.options[picker.select.selectedIndex].text;
            } else {
                label = picker.select.querySelector('option[selected]').text;
            }
            return label;
        };

        function getLanguageUrl(option) {
            // ⚠️ Important: You should replace this return value with the real link to your website in the selected language
            // option.value gives you the value of the language that you can use to create your real url (e.g, 'english' or 'italiano')
            let optval = option.value.substring(0,2);

var location = window.location.pathname;
var searchIndex = location.substr(1,optval.length );
var path = location.substr(2 + searchIndex.length); //this is where the magic happens :)
//console.log(searchIndex);
//console.log(path);
            return '/'+optval+'/'+path;
        };

        function initLanguageSelection(picker) {
            picker.element.getElementsByClassName('language-picker__list')[0].addEventListener('click', function(event) {
                var language = event.target.closest('.language-picker__item');
                if (!language) return;

                if (language.hasAttribute('aria-selected') && language.getAttribute('aria-selected') == 'true') {
                    // selecting the same language
                    event.preventDefault();
                    picker.trigger.setAttribute('aria-expanded', 'false'); // hide dropdown
                } else {
                    // ⚠️ Important: this 'else' code needs to be removed in production. 
                    // The user has to be redirected to the new url -> nothing to do here
                    if(1===2){
                    event.preventDefault();
                    picker.element.getElementsByClassName('language-picker__list')[0].querySelector('[aria-selected="true"]').removeAttribute('aria-selected');
                    language.setAttribute('aria-selected', 'true');
                    picker.trigger.getElementsByClassName('language-picker__label')[0].setAttribute('class', 'language-picker__label language-picker__flag language-picker__flag--' + language.getAttribute('data-value'));
                    picker.trigger.getElementsByClassName('language-picker__label')[0].getElementsByTagName('em')[0].textContent = language.textContent;
                    picker.trigger.setAttribute('aria-expanded', 'false');
                    }
                }
            });
        };

        function keyboardNavigatePicker(picker, direction) {
            var index = Util.getIndexInArray(picker.languages, document.activeElement);
            index = (direction == 'next') ? index + 1 : index - 1;
            if (index < 0) index = picker.languages.length - 1;
            if (index >= picker.languages.length) index = 0;
            Util.moveFocus(picker.languages[index]);
        };

        //initialize the LanguagePicker objects
        var languagePicker = document.getElementsByClassName('js-language-picker');
        if (languagePicker.length > 0) {
            var pickerArray = [];
            for (var i = 0; i < languagePicker.length; i++) {
                (function(i) { pickerArray.push(new LanguagePicker(languagePicker[i])); })(i);
            }

            // listen for key events
            window.addEventListener('keyup', function(event) {
                if (event.keyCode && event.keyCode == 27 || event.key && event.key.toLowerCase() == 'escape') {
                    // close language picker on 'Esc'
                    pickerArray.forEach(function(element) {
                        moveFocusToPickerTrigger(element); // if focus is within dropdown, move it to dropdown trigger
                        toggleLanguagePicker(element, 'false'); // close dropdown
                    });
                }
            });
            // close language picker when clicking outside it
            window.addEventListener('click', function(event) {
                pickerArray.forEach(function(element) {
                    checkLanguagePickerClick(element, event.target);
                });
            });
        }
    }());

