var loadMenu = function () {
  let searchIcon = document.getElementById('search-icon-menu');
  hamburguerMenu = document.getElementById('mobile-menu'),
    overlayBackground = document.getElementById('back-menu'),
    overlayBackgroundDesktop = document.getElementById('back-menu-large'),
    menu = document.getElementById('header-menu'),
    adminBar = document.querySelector('.admin-bar'),
    menuParent = document.querySelectorAll('.parent-links');

  // all elements that have invoked functions 
  // must be set to load the menu correctly
  if ([searchIcon, hamburguerMenu, overlayBackground,
    overlayBackgroundDesktop, menu].some(vari => !vari)) {
    return;
  }

  searchIcon.addEventListener('click', function () {
    if (searchIcon.classList.contains('ds-icon-search')) {
      searchIcon.classList.remove('ds-icon-search');
      searchIcon.classList.add('ds-icon-close');
    } else {
      searchIcon.classList.remove('ds-icon-close');
      searchIcon.classList.add('ds-icon-search');
    }
  }, false);

  hamburguerMenu.addEventListener("change", function () {
    if (hamburguerMenu.checked) {
      overlayBackground.classList.add('active-back-menu');
    } else {
      overlayBackground.classList.remove('active-back-menu');
    }
  }, false);

  menu.addEventListener("mouseover", function () {
    overlayBackgroundDesktop.classList.add('active-back-menu');
  });

  menu.addEventListener("mouseout", function () {
    overlayBackgroundDesktop.classList.remove('active-back-menu');
  });

  menuParent.forEach(function (singleParent) {
    singleParent.addEventListener('click', function (event) {
      event.preventDefault();
      let parent = this.parentElement,
        subMenu = this.nextElementSibling;
      if (subMenu !== null) {
        if (subMenu.classList.contains('ds-hide')) {
          subMenu.classList.remove('ds-hide');
          singleParent.children[0].classList.add('ds-icon-arrow-up');
          singleParent.children[0].classList.remove('ds-icon-arrow-down');
          singleParent.classList.add('parent-dashed');
        }
        else {
          subMenu.classList.add('ds-hide');
          singleParent.children[0].classList.remove('ds-icon-arrow-up');
          singleParent.children[0].classList.add('ds-icon-arrow-down');
          singleParent.classList.remove('parent-dashed');
        }
      }
    }, false);
  });

  window.onscroll = function (e) {
    let scrollY = window.pageYOffset || document.documentElement.scrollTop,
      topbar = document.getElementById("topbar"),
      height = -topbar.clientHeight;
    if (scrollY <= Math.max(this.lastScroll, 50) || this.loaded === undefined) {
      if (adminBar !== null) {
        topbar.style.top = '32px'
      } else {
        topbar.style.top = '0'
      }
    } else {
      topbar.style.top = '-110px'
    }
    this.lastScroll = scrollY;
    this.loaded = true;
  }
}

loadMenu();

module.exports = loadMenu;
