//console.log('global init');
var loading = false;
window.addEventListener('DOMContentLoaded', function(){ 
    
    const menuTrigger = document.getElementById('ftm-mobile-menu-trigger');
    const siteNavigation = document.getElementById('site-navigation');
    const menuItems = document.querySelectorAll('li.menu-item.menu-item-has-children');    

    // Add a click event listener to the button
    menuTrigger.addEventListener('click', () => {
      // Toggle the 'show' class on the siteNavigation element
      siteNavigation.classList.toggle('show');
      menuTrigger.classList.toggle('show');
    });

    menuItems.forEach(menuItem => {
        menuItem.addEventListener('click', (e) => {
          // Toggle the 'show' class on the corresponding submenu
          e.preventDefault();
          e.stopPropagation();
          menuItem.classList.toggle('show');
        });
      });

    try
    {
      MicroModal.init({
        awaitCloseAnimation: true,
        disableScroll: true,
        onClose: function(modal){
          const selectedValue = getSelectedValue();
          setCookie('currState', selectedValue);
          
          // Reload the page after setting the cookie
          location.reload();
        }
      });
    }
    catch(e){
      console.log('micromodal error: ',e);
    }      

    try{      
      const swiper = new Swiper('.swiper', {
        // Optional parameters
        direction: 'horizontal',
        loop: true,    
      
        // Navigation arrows
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
      
      });
    }
    catch(e){
      console.log('Swiper init error: ',e);
    }  
   
    // Check if an element with the class "ftm_load_more" exists
    var ftmloadMoreElement = document.querySelector(".ftm_load_more");

    if (ftmloadMoreElement !== null) {
        // Check if the user has scrolled to the footer
        window.addEventListener("scroll", function () {
          if (
              window.innerHeight + window.scrollY >=
              document.body.offsetHeight - 500
          ) {
              loadMorePosts();
          }
      });
    }  
});


 // Function to set the cookie
 function setCookie(name, value) {
    document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
  }

  // Function to get the selected value of the select element
  function getSelectedValue() {
    const selectElement = document.getElementById('ftm-header__state');
    return selectElement.value;
  }

  // Function to load more posts via AJAX
  function loadMorePosts() {
    if (loading) return;
    loading = true;
    
    var xhr = new XMLHttpRequest();
    xhr.open("POST", pw_script_vars.ajaxurl, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        var loadMoreLogo = document.querySelector(".ftm_load_more");
        loadMoreLogo.classList.add("active");

        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = xhr.responseText;
            var postContainer = document.getElementById("latest_post_wrapper");
            var currentoffset = document.getElementById("latest_posts_offset");
            var offset = Number(currentoffset.value);
            
            if (response !== "no-more-posts") {
                // Append the new posts to your container                
                postContainer.insertAdjacentHTML("beforeend", response);

                // Increment the offset for the next request
                offset += 9; // Change to match the posts_per_page value
                currentoffset.value = offset;
            } else {
                // No more posts to load
                $no_more_control = document.getElementById("no-more-posts");
                if( !$no_more_control ){
                  postContainer.insertAdjacentHTML("beforeend", '<div id="no-more-posts">-- No More Posts to Load --</div>');
                }                
            }

            loading = false;
        }

        loadMoreLogo.classList.remove("active");
    };

    var currentoffset = Number(document.getElementById("latest_posts_offset").value);
    currentoffset += 9; // Change to match the posts_per_page value
    xhr.send("action=ftm_load_more_posts&offset=" + currentoffset);
  }