// let baseURL = window.location.origin;
let baseURL = window.location.origin + "/ccs/";

/***********************************
   ---  Sidebar Scroll Check ---
***********************************/
const maroon_sections = document.querySelectorAll('.section__bg-maroon');
const sidebar_cta = document.querySelectorAll('.sidebar-cta');

window.addEventListener('scroll', function () {
    for(var i = 0; i < sidebar_cta.length; i++){
        var b = sidebar_cta[i].getBoundingClientRect();
        var overlaps = false;

        for(var x = 0; x < maroon_sections.length; x++){
            if(!overlaps){
                var a = maroon_sections[x].getBoundingClientRect();
                if (b.top <= a.top + a.height && b.top + b.height > a.top) {
                    sidebar_cta[i].classList.add("btn-sidebar-cta-overlap");
                    overlaps = true;
                } 
                else {
                    sidebar_cta[i].classList.remove("btn-sidebar-cta-overlap");
                }
            }
        }
    }
});


const social_sidebar = document.getElementById('social-sidebar');
if(social_sidebar){
    window.addEventListener('scroll', function () {
        var b = social_sidebar.getBoundingClientRect();
        var overlaps = false;

        for(var x = 0; x < maroon_sections.length; x++){
            if(!overlaps){
                var a = maroon_sections[x].getBoundingClientRect();
                if (b.top <= a.top + a.height && b.top + b.height > a.top) {
                    social_sidebar.classList.add("sidebar-cta__container-overlap");
                    overlaps = true;
                } 
                else {
                    social_sidebar.classList.remove("sidebar-cta__container-overlap");
                }
            }
        }
    });
}



/**************************
   ---  Mega Menu ---
**************************/
const menu_button_open = document.getElementById("menu-open");
const menu_button_close = document.getElementById("menu-close");
const mega_menu = document.getElementById("mega-menu");
const mega_menu_left = document.getElementById("mega-menu-left");
const mega_menu_right = document.getElementById("mega-menu-right");
const body = document.body;

menu_button_open.addEventListener('click', function () {
    mega_menu.classList.toggle("mega-menu-active");
    mega_menu_left.classList.toggle("mega-menu__left-active");
    mega_menu_right.classList.toggle("mega-menu__right-active");
    body.classList.toggle("locked");
});
menu_button_close.addEventListener('click', function () {
    mega_menu.classList.toggle("mega-menu-active");
    mega_menu_left.classList.toggle("mega-menu__left-active");
    mega_menu_right.classList.toggle("mega-menu__right-active");
    body.classList.toggle("locked");
});



/**************************
   ---  Event Cards ---
**************************/
const events = document.querySelectorAll(".event");
const event__overlay = document.getElementById("event__overlay");
const event__cards = document.querySelectorAll(".event__card");

for(var i = 0; i < events.length; i++){
    events[i].addEventListener('click', function(){
        event__overlay.classList.toggle("event__overlay-active");
        this.nextElementSibling.classList.toggle("event__card-active");
        body.classList.toggle("locked");
    });
}

if(event__overlay){
    event__overlay.addEventListener('click', function(){
        event__overlay.classList.toggle("event__overlay-active");
        for(var i = 0; i < event__cards.length; i++){
            if(event__cards[i].classList.contains('event__card-active')){
                event__cards[i].classList.toggle("event__card-active");
                body.classList.toggle("locked");
            }
        }
    });
}



/************************************
   ---  Fade In Scroll Effect ---
*************************************/
const scroll_fades = document.querySelectorAll(".section-fade");
const observer_scroll_fade_options = {
    root: null,
    rootMargin: '10px',
    threshold: 0.3,
   };
const observer_scroll_fade = new IntersectionObserver(observerCallback, observer_scroll_fade_options);

function observerCallback(entries) {
    entries.forEach((entry) => {
     if (entry.isIntersecting) {
      entry.target.classList.add('section-fade-active');
     }
    });
   }

scroll_fades.forEach((el) => observer_scroll_fade.observe(el));



/*********************************
      ---  Testimonials ---
*********************************/
const testimonials_lists = document.querySelectorAll(".testimonials__list");

if(testimonials_lists){
    for(var i = 0; i < testimonials_lists.length; i++){
        var list_element = testimonials_lists[0];
        rotateTestimonial(list_element);
    }
}

function rotateTestimonial(element){
     //every 4 seconds
     setInterval(function(){
        var length = element.children.length;
        //Fade Out first element
        element.children[0].classList.add("testimonials-out");
        //Move first item to end of the list
        setTimeout(function(){
            element.appendChild(element.children[0]);
        },1000);
        //Fade In new first element
        element.children[0].classList.add("testimonials-in");
        //cleanup
        element.children[length-1].classList.remove("testimonials-out");
        element.children[length-1].classList.remove("testimonials-in");
    } ,7000);
}



/*****************************
      ---  Parallax ---
******************************/
(function ($) {
    $('.parallax__image').each(function(){
        var img = $(this);
        var imgParent = $(this).parent();
        function parallaxImg () {
            var speed = img.data('speed');
            var imgY = imgParent.offset().top;
            var thisToTop = $(this).scrollTop();
            var thisHeight = $(this).height();
            var parentHeight = imgParent.innerHeight();
    
            var thisBottom = thisToTop + thisHeight;
    
            // If block is shown on screen
            if (thisBottom > imgY) {
            // Number of pixels shown after block appear
            var imgBottom = ((thisBottom - imgY) * speed);
            // Max number of pixels until block disappear
            var imgTop = thisHeight + parentHeight;
            // Calc percentage to move the "background" image
            var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
            }
            img.css({
                // top: imgPercent + '%',
                // transform: 'translate(0%, -' + imgPercent + '%)'
                bottom: imgPercent + '%',
                transform: 'translate(0%, ' + imgPercent + '%)'
            });
        }
        $(document).ready(function(){
            parallaxImg();
        });
        $(document).scroll(function(){
            parallaxImg();
        });
    });
})(jQuery);

/**************************************
   ---  Header Title Background  ---
**************************************/
var headerBG = document.getElementById("header_title_bg");
var titleTall = document.getElementById("header_title_tall");
var titleShort = document.getElementById("header_title_short");
var titleSingle = document.getElementById("header_title_single");

if(headerBG){
    updateHeaderTitleBackground();
    
    window.addEventListener('resize', function(event) {
        updateHeaderTitleBackground()
    }, true);
}

function updateHeaderTitleBackground(){
    if(titleTall){
        var size = titleTall.getBoundingClientRect();
        headerBG.style.width = (size.width + 40).toString() + "px";
        headerBG.style.height = (size.height).toString() + "px";
    }
    if(titleShort){
        var size = titleShort.getBoundingClientRect();
        headerBG.style.width = (size.width + 40).toString() + "px";
        headerBG.style.height = size.height.toString() + "px";
    }
    if(titleSingle){
        var size = titleSingle.getBoundingClientRect();
        headerBG.style.width = (size.width + 150).toString() + "px";
        headerBG.style.height = (size.height + 100).toString() + "px";
        headerBG.style.bottom = "150px";
    }
}


/**********************************
    ---  News List <-> Grid ---
**********************************/
const news_display_toggle = document.getElementById("newsToggle");

if(news_display_toggle){
    news_display_toggle.addEventListener('click', function(){
        toggleNewsDisplay();
    });
}

function toggleNewsDisplay(){
    var news_items = document.querySelectorAll(".news__item");
    if(news_items){
        for(var i = 0; i < news_items.length; i++){
            news_items[i].classList.toggle("news__item-listed");
        }
    }

    if(news_display_toggle.innerText.includes("LIST")){
        news_display_toggle.innerText = "VIEW AS A GRID";
    }
    else{
        news_display_toggle.innerText = "VIEW AS A LIST";
    }
}



/**********************************
    ---  Contact Carousel  ---
**********************************/
let carousel = document.querySelectorAll('.carousel');

carousel.forEach((car) => {
    let carInner = car.children[0];
    let slides = carInner.children;
    for(var x=0; x < slides.length; x++){
        const minPerSlide = 3;
        let next = slides[x].nextElementSibling
        for (var i=1; i< minPerSlide; i++) {
            if (!next) {
                    next = slides[0]
            }
            let cloneChild = next.cloneNode(true)
            slides[x].appendChild(cloneChild.children[0])
            next = next.nextElementSibling
        }
    }

});


/**************************************
  ---  Athletics Carousel Toggle  ---
**************************************/
if(document.getElementById('schedule_btn')){

    let scheduleBtn = document.getElementById('schedule_btn');
    let scheduleCarousel = document.getElementById('scheduleCarousel');
    let scoreBtn = document.getElementById('score_btn');
    let scoreCarousel = document.getElementById('scoreCarousel');

    scheduleBtn.addEventListener("click", function(){
        scoreBtn.classList.add('btn-maroon');
        scoreBtn.classList.remove('btn-maroon-active');
        scheduleBtn.classList.add('btn-maroon-active');
        scheduleBtn.classList.remove('btn-maroon');
        scheduleCarousel.style.display = "block";
        scoreCarousel.style.display = "none";
    });
    scoreBtn.addEventListener("click", function(){
        scheduleBtn.classList.add('btn-maroon');
        scheduleBtn.classList.remove('btn-maroon-active');
        scoreBtn.classList.add('btn-maroon-active');
        scoreBtn.classList.remove('btn-maroon');
        scheduleCarousel.style.display = "none";
        scoreCarousel.style.display = "block";
    });
    
};


/**************************************
  ---  Athletics Table Toggle  ---
**************************************/
if(document.querySelectorAll('.table__tab')){

    let tableTabs = document.querySelectorAll('.table__tab');
    let tableSchedule = document.getElementById("athletics_table_schedule");
    let tableRoster = document.getElementById("athletics_table_roster");
    let tabSchedule = document.getElementById("schedule_tab");
    let tabRoster = document.getElementById("roster_tab");

    tableTabs.forEach((tab) => {
        tab.addEventListener("click", function(){
            
            if(tab.dataset.table == "schedule"){
                tableSchedule.classList.add("table__container-active");
                tableRoster.classList.remove("table__container-active");
                tabSchedule.classList.add("table__tab-active");
                tabRoster.classList.remove("table__tab-active");
            }
            else{
                tableSchedule.classList.remove("table__container-active");
                tableRoster.classList.add("table__container-active");
                tabSchedule.classList.remove("table__tab-active");
                tabRoster.classList.add("table__tab-active");
            }
        });

    });

}



/**************************
   ---  News Filter ---
**************************/
function createQueryString(args, pagination, remove_wp = false, remove_empty = false) {
    var thisString = "?";
    if (pagination) {
        thisString += (args.paged) ? "paged=" + args.paged : "paged=" + 1;
        delete args.paged;
        thisString += (args.per_page) ? "&per_page=" + args.per_page : "&per_page=" + 10;
        delete args.per_page;
    }

    if (remove_wp) {
        delete args._wpnonce;
    }

    for (var key in args) {
        var value = key + "=" + args[key];

        //check to see if there was a value added to the param
        if (remove_empty) {
            value = (value === key + "=") ? '' : value;
        }

        if (value) {
            if (thisString === "?") {
                thisString += value;
            } else {
                thisString += "&" + value;
            }
        }
    }

    return thisString;
}

if(document.getElementById('news_search')){
    document.getElementById('news_search').addEventListener("change", function(){
        getNewItems(true);
    });
    if(document.getElementById('news_search').value){
        getNewItems(true);
    }
};
if(document.getElementById('news__config__filter')){
    document.getElementById('news__config__filter').addEventListener("change", function(){
        getNewItems(true);
    });
    if(document.getElementById('news__config__filter').value){
        getNewItems(true);
    }
};


function getNewItems(newList){
    // $('.loader').show();
    // $('.photo-gallery__load-more').hide();
    (function ($) {
        if (newList) 
            $('#rest_page').val(1);

        var args = {
            paged: $('#rest_page').val() || 1,
            per_page: 6,
            category: $('#news__config__filter').val(),
            search: $('#news_search').val(),
            // _wpnonce: $('#_wp_rest').val(),
        };

        queryParameters = createQueryString(args, true);

        $.ajax({
            url: baseURL + '/wp-json/clarksville/news' + queryParameters,
            type: 'GET',
            dataType: 'json',
            cache:false,
            beforeSend: function (xhr) {
                // xhr.setRequestHeader('X-WP-Nonce', $('#_wp_rest').val());
            },
            success : function(data) {    
                if (data) {
                    if(data.html){
                        $('.news__list').empty();
                        
                        $('.news__list').append(data.html);
                    }
                    else{
                        $('.news__list').empty();
                        
                        $('.news__list').append(
                            "<div id=\"post-404\" class=\"noposts\"><p>No Articles Found Matching Search</p></div>"
                        );
                    }
                }
            },
            error : function(request,error) {
                console.log(error);
                console.log(request);
            }
        });

    })(jQuery);
}

/*******************************
   ---  Nav Search Routing ---
********************************/
let navSearch = document.getElementById('nav__search__icon');
let navSearchInput = document.getElementById('nav__search__input');

if(navSearch){
    navSearch.addEventListener("click", function(){
        let searchString = document.getElementsByName('nav-search')[0].value;
        window.location.href = baseURL + "?s=" + searchString;
    });
}
if(navSearchInput){
    navSearchInput.addEventListener("keydown", function(e){
        if(e.key === 'Enter'){
            let searchString = document.getElementsByName('nav-search')[0].value;
            window.location.href = baseURL + "?s=" + searchString;
        }
    });
}