/* nicic.gov *************************************************************************************
 * 
 * ACCORDIONS
 * 
 ****************************************************************************************/

/* USA BANNER Dropdown functionality*/
function usamenu() {
    let menubuttons = document.querySelectorAll('.usa-banner button.usa-accordion__button');
    for (let i = 0; i < menubuttons.length; i++) {
        menubuttons[i].addEventListener("click", function (e) {
            let openclose = this.getAttribute("aria-expanded");
            let targetElement = document.getElementById('gov-banner');
            if (openclose == "false") {
                let mbuttons = document.querySelectorAll('.usa-banner button.usa-accordion__button');
                // let subnavs = document.querySelectorAll('.usa-banner__content');
                for (let i = 0; i < mbuttons.length; i++) {
                    mbuttons[i].setAttribute("aria-expanded", false);
                }
                // for (let i = 0; i < subnavs.length; i++) {
                //     subnavs[i].hidden = true;
                // }
                this.setAttribute("aria-expanded", true);
                targetElement.hidden = false;
            } else {
                this.setAttribute("aria-expanded", false);
                targetElement.hidden = true;
            }
        });
    }
}
/*Main Menu Dropdown functionality*/
function mainmenu() {
    let menubuttons = document.querySelectorAll('.usa-nav__primary.usa-accordion > .usa-nav__primary-item button');
    for (let i = 0; i < menubuttons.length; i++) {
        menubuttons[i].addEventListener("click", function (e) {
            let openclose = this.getAttribute("aria-expanded");
            console.log(openclose + " openclose");
            if (openclose == "false") {
                let mbuttons = document.querySelectorAll('.usa-nav__primary.usa-accordion > .usa-nav__primary-item button');
                let subnavs = document.querySelectorAll('.usa-nav__primary.usa-accordion > .usa-nav__primary-item > .usa-nav__submenu');
                for (let i = 0; i < mbuttons.length; i++) {
                    mbuttons[i].setAttribute("aria-expanded", false);
                }
                for (let i = 0; i < subnavs.length; i++) {
                    subnavs[i].hidden = true;
                }
                this.setAttribute("aria-expanded", true);
                this.nextElementSibling.hidden = false;
            } else {
                this.setAttribute("aria-expanded", false);
                this.nextElementSibling.hidden = true;
            }
        });
    }
}
/*Main Content area Accordion Functionality*/
function usaMainContentAccordion() {
    //Determine if the accordion has 1 child or many


    let accordions = document.querySelectorAll('main .usa-accordion .usa-accordion__button');

    console.log(accordions.length + " Main Accordions");

    for (let i = 0; i < accordions.length; i++) {
    
        var getID = accordions[i].getAttribute('aria-controls');
        console.log("69 "+getID);
        let currenttitle = false;

        if (document.querySelector('#' + getID + " > .field--name-title h4")) {
            currenttitle = document.querySelector('#' + getID + " > .field--name-title h4").innerText;
            console.log("74 "+currenttitle);

        } else if (document.querySelector('#' + getID + " > .grid-row > .grid-col-fill > .field--name-field-title")) {
            currenttitle = document.querySelector('#' + getID + " > .grid-row > .grid-col-fill > .field--name-field-title").innerText;
            console.log("78 " + currenttitle);

        } else if (document.querySelector('#' + getID + " > .field--name-field-title")) {
            currenttitle = document.querySelector('#' + getID + " > .field--name-field-title").innerText;
            console.log("83 " + currenttitle);

        }
        if (currenttitle) {
            console.log("86 " + currenttitle);

            if (document.querySelector('#' + getID + " > .field--name-title")) {
                document.querySelector('#' + getID + " > .field--name-title").style.display = 'none';
            } else if (document.querySelector('#' + getID + " > .field--name-field-title")) {
                document.querySelector('#' + getID + " > .field--name-field-title").style.display = 'none';
            } else if (document.querySelector('#' + getID + " > .grid-row > .grid-col-fill > .field--name-field-title")) {
                document.querySelector('#' + getID + " > .grid-row > .grid-col-fill > .field--name-field-title").style.display = 'none';
            }
            document.querySelector('[aria-controls=' + getID + "]").innerText = currenttitle;
        }


        const mainAccordions = document.querySelectorAll('main .usa-accordion > a.usa-accordion__button, main .usa-accordion > button.usa-accordion__button, main .usa-accordion > .usa-accordion__heading > a.usa-accordion__button, main .usa-accordion > .usa-accordion__heading > button.usa-accordion__button');
        const mainContents = document.querySelectorAll('main .usa-accordion > .usa-accordion__content');

        // console.dir(mainAccordions);

        mainAccordions.forEach((accordion) => {
            accordion.addEventListener("click", function () {
                // console.log("clicked "+this)
                const isOpen = this.getAttribute("aria-expanded") === "true";
                const matchmaker = this.getAttribute("aria-controls");

                mainAccordions.forEach((accordion) => {
                    // console.log("button");
                    button.setAttribute("aria-expanded", false);
                    button.classList.remove('active');
                });

                mainContents.forEach((content) => {
                    content.hidden = true;
                    content.style.display = "none";
                });

                this.setAttribute("aria-expanded", isOpen);
                const contentElement = document.querySelector('#' + matchmaker);
                if (contentElement) {
                    contentElement.hidden = isOpen;
                    contentElement.style.display = isOpen ? "none" : "block";
                }
            });
        });



    }
}

/* Project Page Accordions*/


function usaFieldStackAccordion() {
    const accordions = document.querySelectorAll('.field--name-field-stack .usa-accordion__button');

    accordions.forEach((accordion) => {
        const panel = accordion.parentNode.nextElementSibling;
        const title = panel.querySelector('.field--name-field-title');

        accordion.innerHTML = title.innerText;
        title.style.display = 'none';

        accordion.addEventListener("click", function () {
            // Toggle the "active" class and aria-expanded attribute
            this.classList.toggle("active");
            const isExpanded = this.getAttribute("aria-expanded") === "true";
            this.setAttribute("aria-expanded", isExpanded ? "false" : "true");

            // Toggle the visibility of the panel
            if (isExpanded) {
                panel.style.display = "none";
                panel.setAttribute("hidden", true);
            } else {
                panel.style.display = "block";
                panel.removeAttribute("hidden");
            }
        });
    });
}

/* Blocks Accordions*/
function usaBlockAccordion() {
    console.log("block accordion fired");
    if (document.querySelectorAll('.views-element-container').length > 0) {
        var containers = document.querySelectorAll('.views-element-container');
        var c;
        for (c = 0; c < containers.length; c++) {
            console.log(containers[c].getAttribute('id'));
            if (containers[c].querySelectorAll('.usa-accordion__button').length > 0) {
                var acc = containers[c].querySelectorAll('.usa-accordion__button');
                var i;
                //console.log("block accordion found");
                //console.log(acc);
                for (i = 0; i < acc.length; i++) {
                    var getID = acc[i].getAttribute('aria-controls');
                    //console.log(getID);
                    acc[i].addEventListener("click", function () {
                        console.log("you clicked it");
                        /* Toggle between adding and removing the "active" class,
                        to highlight the button that controls the panel */
                        this.classList.toggle("active");
                        if (this.getAttribute("aria-expanded") == "true"){
                            this.setAttribute("aria-expanded", "false");
                        } else {
                            this.setAttribute("aria-expanded", "true");
                        }                        

                        /* Toggle between hiding and showing the active panel */
                        var panel = this.parentNode.nextElementSibling;
                        //console.log(panel);
                        if (panel.style.display === "none") {
                            panel.style.display = "none";
                            panel.setAttribute("hidden", true);
                        } else {
                            panel.style.display = "block";
                            panel.removeAttribute("hidden");
                        }
                    });
                }
            }
        }
    }
}


/* USWDS Banner */
// Get a reference to the button and the #gov-banner element
const button = document.querySelector(".dialog-off-canvas-main-canvas .usa-banner .usa-accordion__button");
const govBanner = document.getElementById("gov-banner");

// Add a click event listener to the button
button.addEventListener("click", function () {
    // Toggle the hidden attribute of the #gov-banner element
    if (govBanner) {
        govBanner.hidden = !govBanner.hidden;
    }
});

/* Show/hide the in page TOC */
function showtoc() {
    console.log("hidemenu function");
    let menuButton = document.querySelectorAll('a.pagetoc');
    for (let i = 0; i < menuButton.length; i++) {
        menuButton[i].addEventListener("click", function (e) {
            e.preventDefault();
            console.log("showTOC clicked");
            document.querySelector(".anchor-list").classList.toggle("open-toc")

        });
    }
}



/* Close the Mobile Menu */
function hidemenu() {
    console.log("hidemenu function");
    let mobileMenuButton = document.querySelectorAll('button.usa-nav__close');
    for (let i = 0; i < mobileMenuButton.length; i++) {
        mobileMenuButton[i].addEventListener("click", function (e) {
            console.log("hidemenu clicked");
            const mobileNavisActive = document.body.classList.contains("usa-mobile_nav-active");
            if (mobileNavisActive) {
                document.body.classList.remove("usa-mobile_nav-active");
                Array.from(document.querySelectorAll('.usa-overlay')).forEach(function (el) {
                    el.classList.remove('is-visible');
                });
                Array.from(document.querySelectorAll('.usa-nav')).forEach(function (el) {
                    el.classList.remove('is-visible');
                });
            } else {

            }
        });
    }

}

/* Smooth Scroll */
function smoothClickHandler(e) {
    var href = this.getAttribute("href");
    console.log(href);
    if (href.startsWith('#')) {
        e.preventDefault();

        const getOffsetTop = element => {
            let offsetTop = 0;
            while(element) {
                offsetTop += element.offsetTop;
                element = element.offsetParent;
            }
            return offsetTop;
        }

        const href = this.getAttribute("href");
        const offsetTop = getOffsetTop(document.querySelector(href))-100;

        scroll({
            top: offsetTop,
            behavior: "smooth"
        });
    }
}


/* For autofilling editable_fields fields when doing data correction in a view - takes right column data and inserts into left column input fields */
// function autofill(){
// 	let rowCount = document.querySelectorAll('table.views-table tbody tr').length;
// 	console.log(rowCount);
// 	for (let i = 0; i < rowCount; i++) {
// 	    let iter = i+1;
// 	    console.log(iter);
// 	    let thisText = document.querySelector('table.views-table tbody tr:nth-child(' + iter + ') td:nth-child(2)').innerText;
// 	    console.log(thisText);
// 	    document.querySelector('table.views-table tbody tr:nth-child(' + iter + ') td:nth-child(1) input[type="text"]').value = thisText;
// 	}
// }


/* *************************************************************************************
 * 
 * Slideshow
 * 
 ****************************************************************************************/

function nicSlideshow() {
    let slideshowSlides = document.querySelectorAll(".usa-hero .nic-slideshow .views_slideshow_slide");
    console.log(slideshowSlides.length);
    for (let i = 0; i < slideshowSlides.length; i++) {
        let image = slideshowSlides[i].querySelector('.slider-slide img').getAttribute('src');
        console.log(image);
        slideshowSlides[i].querySelector('.slide-background').style.backgroundImage = "url('" + image + "')";
    }
}




/* *************************************************************************************
 * 
 * Responsive Image Maps
 * 
 ****************************************************************************************/
/*! Image Map Resizer (imageMapResizer.min.js ) - v1.0.10 - 2019-04-10
 *  Desc: Resize HTML imageMap to scaled image.
 *  Copyright: (c) 2019 David J. Bradshaw - dave@bradshaw.net
 *  License: MIT
 */

!function () { "use strict"; function r() { function e() { var r = { width: u.width / u.naturalWidth, height: u.height / u.naturalHeight }, a = { width: parseInt(window.getComputedStyle(u, null).getPropertyValue("padding-left"), 10), height: parseInt(window.getComputedStyle(u, null).getPropertyValue("padding-top"), 10) }; i.forEach(function (e, t) { var n = 0; o[t].coords = e.split(",").map(function (e) { var t = 1 == (n = 1 - n) ? "width" : "height"; return a[t] + Math.floor(Number(e) * r[t]) }).join(",") }) } function t(e) { return e.coords.replace(/ *, */g, ",").replace(/ +/g, ",") } function n() { clearTimeout(d), d = setTimeout(e, 250) } function r(e) { return document.querySelector('img[usemap="' + e + '"]') } var a = this, o = null, i = null, u = null, d = null; "function" != typeof a._resize ? (o = a.getElementsByTagName("area"), i = Array.prototype.map.call(o, t), u = r("#" + a.name) || r(a.name), a._resize = e, u.addEventListener("load", e, !1), window.addEventListener("focus", e, !1), window.addEventListener("resize", n, !1), window.addEventListener("readystatechange", e, !1), document.addEventListener("fullscreenchange", e, !1), u.width === u.naturalWidth && u.height === u.naturalHeight || e()) : a._resize() } function e() { function t(e) { e && (!function (e) { if (!e.tagName) throw new TypeError("Object is not a valid DOM element"); if ("MAP" !== e.tagName.toUpperCase()) throw new TypeError("Expected <MAP> tag, found <" + e.tagName + ">.") }(e), r.call(e), n.push(e)) } var n; return function (e) { switch (n = [], typeof e) { case "undefined": case "string": Array.prototype.forEach.call(document.querySelectorAll(e || "map"), t); break; case "object": t(e); break; default: throw new TypeError("Unexpected data type (" + typeof e + ").") }return n } } "function" == typeof define && define.amd ? define([], e) : "object" == typeof module && "object" == typeof module.exports ? module.exports = e() : window.imageMapResize = e(), "jQuery" in window && (window.jQuery.fn.imageMapResize = function () { return this.filter("map").each(r).end() }) }();


/* *************************************************************************************
 * 
 * Sticky Header
 * 
 ****************************************************************************************/
// When the user scrolls the page, execute myFunction
window.onscroll = function () { myFunction() };

// Get the header
var header = document.getElementById("header");

// Get the offset position of the navbar
var sticky = header.offsetTop;

// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
    if (window.pageYOffset > sticky) {
        header.classList.add("sticky");
    } else {
        header.classList.remove("sticky");
    }
}
/* *************************************************************************************
 * 
 * END Sticky Header
 * 
 ****************************************************************************************/

/* *************************************************************************************
 * 
 * TILT JS
 * 
 ****************************************************************************************/



/* implementing Tilt.js*/
console.log("tilt found");

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function (root, jQuery) {
            if (jQuery === undefined) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if (typeof window !== 'undefined') {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    $.fn.tilt = function (options) {

        /**
         * RequestAnimationFrame
         */
        const requestTick = function () {
            if (this.ticking) return;
            requestAnimationFrame(updateTransforms.bind(this));
            this.ticking = true;
        };

        /**
         * Bind mouse movement evens on instance
         */
        const bindEvents = function () {
            const _this = this;
            $(this).on('mousemove', mouseMove);
            $(this).on('mouseenter', mouseEnter);
            if (this.settings.reset) $(this).on('mouseleave', mouseLeave);
            if (this.settings.glare) $(window).on('resize', updateGlareSize.bind(_this));
        };

        /**
         * Set transition only on mouse leave and mouse enter so it doesn't influence mouse move transforms
         */
        const setTransition = function () {
            if (this.timeout !== undefined) clearTimeout(this.timeout);
            $(this).css({ 'transition': `${this.settings.speed}ms ${this.settings.easing}` });
            if (this.settings.glare) this.glareElement.css({ 'transition': `opacity ${this.settings.speed}ms ${this.settings.easing}` });
            this.timeout = setTimeout(() => {
                $(this).css({ 'transition': '' });
                if (this.settings.glare) this.glareElement.css({ 'transition': '' });
            }, this.settings.speed);
        };

        /**
         * When user mouse enters tilt element
         */
        const mouseEnter = function (event) {
            this.ticking = false;
            $(this).css({ 'will-change': 'transform' });
            setTransition.call(this);

            // Trigger change event
            $(this).trigger("tilt.mouseEnter");
        };

        /**
         * Return the x,y position of the mouse on the tilt element
         * @returns {{x: *, y: *}}
         */
        const getMousePositions = function (event) {
            if (typeof (event) === "undefined") {
                event = {
                    pageX: $(this).offset().left + $(this).outerWidth() / 2,
                    pageY: $(this).offset().top + $(this).outerHeight() / 2
                };
            }
            return { x: event.pageX, y: event.pageY };
        };

        /**
         * When user mouse moves over the tilt element
         */
        const mouseMove = function (event) {
            this.mousePositions = getMousePositions(event);
            requestTick.call(this);
        };

        /**
         * When user mouse leaves tilt element
         */
        const mouseLeave = function () {
            setTransition.call(this);
            this.reset = true;
            requestTick.call(this);

            // Trigger change event
            $(this).trigger("tilt.mouseLeave");
        };

        /**
         * Get tilt values
         *
         * @returns {{x: tilt value, y: tilt value}}
         */
        const getValues = function () {
            const width = $(this).outerWidth();
            const height = $(this).outerHeight();
            const left = $(this).offset().left;
            const top = $(this).offset().top;
            const percentageX = (this.mousePositions.x - left) / width;
            const percentageY = (this.mousePositions.y - top) / height;
            // x or y position inside instance / width of instance = percentage of position inside instance * the max tilt value
            const tiltX = ((this.settings.maxTilt / 2) - ((percentageX) * this.settings.maxTilt)).toFixed(2);
            const tiltY = (((percentageY) * this.settings.maxTilt) - (this.settings.maxTilt / 2)).toFixed(2);
            // angle
            const angle = Math.atan2(this.mousePositions.x - (left + width / 2), - (this.mousePositions.y - (top + height / 2))) * (180 / Math.PI);
            // Return x & y tilt values
            return { tiltX, tiltY, 'percentageX': percentageX * 100, 'percentageY': percentageY * 100, angle };
        };

        /**
         * Update tilt transforms on mousemove
         */
        const updateTransforms = function () {
            this.transforms = getValues.call(this);

            if (this.reset) {
                this.reset = false;
                $(this).css('transform', `perspective(${this.settings.perspective}px) rotateX(0deg) rotateY(0deg)`);

                // Rotate glare if enabled
                if (this.settings.glare) {
                    this.glareElement.css('transform', `rotate(180deg) translate(-50%, -50%)`);
                    this.glareElement.css('opacity', `0`);
                }

                return;
            } else {
                $(this).css('transform', `perspective(${this.settings.perspective}px) rotateX(${this.settings.disableAxis === 'x' ? 0 : this.transforms.tiltY}deg) rotateY(${this.settings.disableAxis === 'y' ? 0 : this.transforms.tiltX}deg) scale3d(${this.settings.scale},${this.settings.scale},${this.settings.scale})`);

                // Rotate glare if enabled
                if (this.settings.glare) {
                    this.glareElement.css('transform', `rotate(${this.transforms.angle}deg) translate(-50%, -50%)`);
                    this.glareElement.css('opacity', `${this.transforms.percentageY * this.settings.maxGlare / 100}`);
                }
            }

            // Trigger change event
            $(this).trigger("change", [this.transforms]);

            this.ticking = false;
        };

        /**
         * Prepare elements
         */
        const prepareGlare = function () {
            const glarePrerender = this.settings.glarePrerender;

            // If option pre-render is enabled we assume all html/css is present for an optimal glare effect.
            if (!glarePrerender)
                // Create glare element
                $(this).append('<div class="js-tilt-glare"><div class="js-tilt-glare-inner"></div></div>');

            // Store glare selector if glare is enabled
            this.glareElementWrapper = $(this).find(".js-tilt-glare");
            this.glareElement = $(this).find(".js-tilt-glare-inner");

            // Remember? We assume all css is already set, so just return
            if (glarePrerender) return;

            // Abstracted re-usable glare styles
            const stretch = {
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%',
            };

            // Style glare wrapper
            this.glareElementWrapper.css(stretch).css({
                'overflow': 'hidden',
                'pointer-events': 'none',
            });

            // Style glare element
            this.glareElement.css({
                'position': 'absolute',
                'top': '50%',
                'left': '50%',
                'background-image': `linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%)`,
                'width': `${$(this).outerWidth() * 2}`,
                'height': `${$(this).outerWidth() * 2}`,
                'transform': 'rotate(180deg) translate(-50%, -50%)',
                'transform-origin': '0% 0%',
                'opacity': '0',
            });

        };

        /**
         * Update glare on resize
         */
        const updateGlareSize = function () {
            this.glareElement.css({
                'width': `${$(this).outerWidth() * 2}`,
                'height': `${$(this).outerWidth() * 2}`,
            });
        };

        /**
         * Public methods
         */
        $.fn.tilt.destroy = function () {
            $(this).each(function () {
                $(this).find('.js-tilt-glare').remove();
                $(this).css({ 'will-change': '', 'transform': '' });
                $(this).off('mousemove mouseenter mouseleave');
            });
        };

        $.fn.tilt.getValues = function () {
            const results = [];
            $(this).each(function () {
                this.mousePositions = getMousePositions.call(this);
                results.push(getValues.call(this));
            });
            return results;
        };

        $.fn.tilt.reset = function () {
            $(this).each(function () {
                this.mousePositions = getMousePositions.call(this);
                this.settings = $(this).data('settings');
                mouseLeave.call(this);
                setTimeout(() => {
                    this.reset = false;
                }, this.settings.transition);
            });
        };

        /**
         * Loop every instance
         */
        return this.each(function () {

            /**
             * Default settings merged with user settings
             * Can be set trough data attributes or as parameter.
             * @type {*}
             */
            this.settings = $.extend({
                maxTilt: $(this).is('[data-tilt-max]') ? $(this).data('tilt-max') : 10,
                perspective: $(this).is('[data-tilt-perspective]') ? $(this).data('tilt-perspective') : 300,
                easing: $(this).is('[data-tilt-easing]') ? $(this).data('tilt-easing') : 'cubic-bezier(.03,.98,.52,.99)',
                scale: $(this).is('[data-tilt-scale]') ? $(this).data('tilt-scale') : '1',
                speed: $(this).is('[data-tilt-speed]') ? $(this).data('tilt-speed') : '400',
                transition: $(this).is('[data-tilt-transition]') ? $(this).data('tilt-transition') : true,
                disableAxis: $(this).is('[data-tilt-disable-axis]') ? $(this).data('tilt-disable-axis') : null,
                axis: $(this).is('[data-tilt-axis]') ? $(this).data('tilt-axis') : null,
                reset: $(this).is('[data-tilt-reset]') ? $(this).data('tilt-reset') : true,
                glare: $(this).is('[data-tilt-glare]') ? $(this).data('tilt-glare') : false,
                maxGlare: $(this).is('[data-tilt-maxglare]') ? $(this).data('tilt-maxglare') : 1,
            }, options);

            // Add deprecation warning & set disableAxis to deprecated axis setting
            if (this.settings.axis !== null) {
                console.warn('Tilt.js: the axis setting has been renamed to disableAxis. See https://github.com/gijsroge/tilt.js/pull/26 for more information');
                this.settings.disableAxis = this.settings.axis;
            }

            this.init = () => {
                // Store settings
                $(this).data('settings', this.settings);

                // Prepare element
                if (this.settings.glare) prepareGlare.call(this);

                // Bind events
                bindEvents.call(this);
            };

            // Init
            this.init();

        });
    };

    /**
     * Auto load
     */
    $('[data-tilt]').tilt();

    return true;
}));

jQuery('.js-tilt img').tilt({
    glare: true,
    maxGlare: .5
})
jQuery('.js-tilt-self').tilt({
    glare: true,
    maxGlare: .5
})



/* *************************************************************************************
 * 
 * Checkboxes not checking fix
 * 
 ****************************************************************************************/

const adminbuttons = document.querySelectorAll('.usa-checkbox__label.control-label');
adminbuttons.forEach((adminbutton) => {
    adminbutton.addEventListener("click", function () {
        this.classList.toggle('checked');
        // this.closest('tr').classList.toggle('selected');
        if (this.classList.contains('checked')){
            this.nextElementSibling.setAttribute('checked', 'checked');
            // this.closest('tr').classList.add('selected');
        } else {
            this.nextElementSibling.removeAttribute('checked');
            // this.closest('tr').classList.remove('selected');
        }
        
    });
});


/* *************************************************************************************
 * 
 * Video Chapters & Skip Buttons
 * 
 ****************************************************************************************/

/* 
This is a rewrite of the tutorials found here:
http://thenewcode.com/977/Create-Interactive-HTML5-Video-with-WebVTT-Chapters
https://hacks.mozilla.org/2014/08/building-interactive-html5-videos/

They work mostly, but I needed a solution that worked on all videos on my site and for multiple videos on the same page.

Now we activate the displayChapters function when the chapters track is loaded for each video.
I've rewritten the code so it should work better for multiple videos with chapters on the same page.

Everything is relative to the current video track.
*/

function displayChapters(trackElement) {
    //trackElement is already being brought in as the "chapters" element via code below when the page loads.
    if (!trackElement) return;
    //consider removing figure and figcaption if no chapters exist.

    const locationList = trackElement.closest('figure')?.querySelector(".chapters");
    console.log(locationList);
    if (!locationList) return;
    
    const textTrack = trackElement.track;
    if (!textTrack) return;
    if (textTrack.kind !== "chapters") return;
    textTrack.mode = 'hidden';

    for (let i = 0; i < textTrack.cues.length; ++i) {
        const cue = textTrack.cues[i];
        const chapterName = cue.text;
        const start = cue.startTime;

        const location = document.createElement("a");
        location.setAttribute('rel', start);
        location.setAttribute('tabindex', '0');
        location.innerHTML = chapterName;

        const newLocale = document.createElement("li");
        newLocale.appendChild(location);
        locationList.appendChild(newLocale);

        location.addEventListener("click", handleChapterClick.bind(location, trackElement), false);
    }
    textTrack.addEventListener("cuechange", handleCueChange.bind(textTrack, locationList), false);
}

function handleChapterClick(trackElement) {
    const videoElement = this.closest('figure').querySelector("video");
    if (videoElement) {
        videoElement.currentTime = parseFloat(this.getAttribute('rel'));
    }
}

function handleCueChange(locationList) {
    const activeCue = this.activeCues[0];
    if (!activeCue) return;

    const currentLocation = activeCue.startTime;
    const cueMatch = activeCue.text;
    const matchingCueArray = document.querySelectorAll('[rel="' + currentLocation + '"]');

    matchingCueArray.forEach((thisChapter) => {
        if (thisChapter.textContent === cueMatch) {

            const locations = Array.from(chapter.closest('figure').querySelectorAll("figcaption .chapters li"));
            const thisChapterIndex = locations.findIndex((item) => item === thisChapter.parentNode);

            locations.forEach((item, index) => {
                item.classList.remove("currentli", "watched");
                item.querySelector('a').classList.remove("current");

                if (index === thisChapterIndex) {
                    item.classList.add("currentli");
                    item.querySelector('a').classList.add("current");
                } else if (index < thisChapterIndex) {
                    item.classList.add("watched");
                }
            });


        }
    });

    // Additional logic for handling chapters
}

/* It's bad practice, but my client wanted to include HTML in their Chapters files with <small> tags. 
So we need to interpret the chapter content from plain text to HTML
the file looks like this:
WEBVTT

1
00:00:00.000 --> 00:00:39.824
Welcome

2
00:00:39.825 --> 00:03:31.441
Logging in and Account Creation <small>This also includes resetting your password</small>

*/

let support = (function () {
    if (!window.DOMParser) return false;
    var parser = new DOMParser();
    try {
        parser.parseFromString('x', 'text/html');
    } catch (err) {
        return false;
    }
    return true;
})();
let stringToHTML = function (str) {
    // check for DOMParser support
    if (support) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(str, 'text/html');
        return doc.body.innerHTML;
    }
    // Otherwise, create div and append HTML
    var dom = document.createElement('div');
    dom.innerHTML = str;
    return dom;
};

/* This code is for adding the 15 and 30 second skip buttons. 
 * Note that if you change the timings, you have to change both the text 'Rewind XX seconds' and the function rew(XX, this)
 * same with the fast forward functions. The nice part is that this is the only place you need to change the timing.
 * The actual functions that do the work rely on the time variable and perform their work automatically based on what you put in them.
 * 
*/
var figurefound = 0;

//This is the rewind funtion
function nicrew(time, el) {
    const anchorElement = el;
    // Find the closest parent figure element
    const figureElement = anchorElement.closest("ul").previousElementSibling;
    if (figureElement && figureElement.tagName === "FIGURE") {
        // Find the video element within the figure element
        const videoElement = figureElement.querySelector("video");
        if (videoElement) {
            // Adjust the video's currentTime by the specified time
            videoElement.currentTime -= time;
        }
    } else if (figureElement && figureElement.tagName === "VIDEO") {
        figureElement.currentTime -= time;
    } else {
        return;
    }
}

// This is the fast forward function
function nicff(time, el) {
    const anchorElement = el;
    // Find the closest parent figure element
    const figureElement = anchorElement.closest("ul").previousElementSibling;
    if (figureElement && figureElement.tagName === "FIGURE") {
        // Find the video element within the figure element
        const videoElement = figureElement.querySelector("video");
        if (videoElement) {
            // Adjust the video's currentTime by the specified time
            videoElement.currentTime += time;
        }
    } else if (figureElement && figureElement.tagName === "VIDEO") {
        //videos without chapters aren't wrapped in a <figure> element.
        figureElement.currentTime += time;
    } else {
        return;
    }
}

/* *************************************************************************************
 * 
 * EXECUTE FUNCTIONS
 * 
 ****************************************************************************************/
function generateRandomString(length) {
    const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let result = "";
    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * charset.length);
        result += charset.charAt(randomIndex);
    }
    return result;
}

document.addEventListener("DOMContentLoaded", function () {
    console.log("Dom Loaded");

    /* Video Skip Buttons Implementation */
    let collection = document.getElementsByTagName("video");
    console.dir(collection);
    // Find all video elements and go to work on them
    for (let item of collection) {
        displayChapters(item.querySelector('[kind="chapters"]'));
        // console.log(item);
        let element = document.createElement('ul');
        element.classList.add('video_buttons');
        let randomString = generateRandomString(5);
        element.innerHTML = `
            <li><a class="rew_30 color-grey-1" id="`+randomString+`" title="Rewind 30 seconds" onClick="nicrew(30, this)"><i class="fas fa-angle-double-left"> </i></a></li>
            <li><a class="rew_15 color-grey-5" id="`+randomString+`" title="Rewind 15 seconds" onClick="nicrew(15, this)"><i class="fas fa-backward"> </i></a></li>
            <li><a class="ff_15 color-grey-5" id="`+randomString+`" title="Fast Forward 15 seconds" onClick="nicff(15, this)"><i class="fas fa-forward"> </i></a></li>
            <li><a class="ff_30 color-grey-1" id="`+randomString+`" title="Fast Forward 30 seconds" onClick="nicff(30, this)"><i class="fas fa-angle-double-right"> </i></a></li>
        `;
        if (item.parentElement.nodeName == "FIGURE") {
            // checking if the video element is wrapped in a figure element for adding chapters
            item.closest('figure').after(element);
            figurefound = 1;
        } else {
            // if the video element isn't wrapped in a figure element
            item.after(element);
        }
    }

    /* Accordion Implementation */
    var existCondition = setInterval(function () {
        if (jQuery('.usa-hero .nic-slideshow .views_slideshow_slide').length) {
            // console.log("Slideshow Exists!");
            clearInterval(existCondition);
            nicSlideshow();
        }
    }, 100); // check every 100ms
    var existCondition2 = setInterval(function () {
        if (jQuery('.usa-nav__primary.usa-accordion > .usa-nav__primary-item button').length) {
            // console.log("Menu Exists!");
            clearInterval(existCondition2);
            mainmenu();
        }
    }, 100); // check every 100ms
    var existCondition2a = setInterval(function () {
        if (jQuery('.region-header+nav.usa-nav .usa-nav__inner nav.menu--main ul.menu--main li.expanded.dropdown>span.dropdown-toggle').length) {
            // console.log("Alt Main Menu Exists!");
            clearInterval(existCondition2a);
            mainmenuAlternate();
        }
    }, 100); // check every 100ms

    //hidemenu()
    var existConditionMenu = setInterval(function () {
        if (jQuery('.usa-nav__close').length) {
            // console.log("Mobile Menu Exists!");
            clearInterval(existConditionMenu);
            hidemenu();
        }
    }, 100); // check every 100ms


    var existCondition3 = setInterval(function () {
        if (jQuery('main .usa-accordion').length) {
            // console.log("Main Accordion Exists!");
            clearInterval(existCondition3);
            usaMainContentAccordion();
        }
    }, 100); // check every 100ms
    var existCondition4 = setInterval(function () {
        if (jQuery('.views-element-container .views-field .usa-accordion__button').length) {
            // console.log("Block Accordion Exists!");
            clearInterval(existCondition4);
            usaBlockAccordion();
        }
    }, 100); // check every 100ms
    var existCondition5 = setInterval(function () {
        if (jQuery('.field--name-field-stack .usa-accordion__button').length) {
            // console.log("Field Stack Accordion Exists!");
            clearInterval(existCondition5);
            usaFieldStackAccordion();
        }
    }, 100); // check every 100ms
    var existCondition6 = setInterval(function () {
        if (jQuery('.usa-banner button.usa-accordion__button').length) {
            // console.log("USA-banner Accordion Exists!");
            clearInterval(existCondition6);
            usamenu();
        }
    }, 100); // check every 100ms
    // var existCondition7 = setInterval(function () {
    //     if (jQuery('.usa-accordion__heading button.usa-accordion__button').length) {
    //         // console.log("USDWS Accordion Exists!");
    //         clearInterval(existCondition7);
    //         uswdsBlockAccordion();
    //     }
    // }, 100); // check every 100ms


    showtoc();

    
    /* USWDS Banner */
    // var button = document.getElementsByClassName("usa-banner__button")[0];
    // if (button) {
    //     button.addEventListener("click", function (e) {
    //         jQuery("#gov-banner").slideToggle();
    //     }, false);
    // }


    
    jQuery('map').imageMapResize();

/* Accordion */
    jQuery('body').on('click', '.book-blocks-toc a.expandable', function (e) {
        e.stopImmediatePropagation();
        e.preventDefault();
        // console.log('clicked a.expandable');
        if (jQuery(this).closest('li').hasClass('expanded') === true) {
            jQuery(this).closest('li').removeClass('expanded');
            jQuery(this).closest('li').addClass('collapsed');
            jQuery(this).siblings('ul').hide();
        } else {
            jQuery(this).closest('li').removeClass('collapsed');
            jQuery(this).closest('li').addClass('expanded');
            jQuery(this).siblings('ul').slideDown(500);
            jQuery(this).closest('li').siblings('li').removeClass('expanded');
            jQuery(this).closest('li').siblings('li').addClass('collapsed');
            jQuery(this).closest('li').siblings('li').children('ul').hide();
        }
        return false;
    });

    // jQuery('body').on('click', 'aside .book-blocks-toc a.expandable', function (e) {
    //     e.stopImmediatePropagation();
    //     e.preventDefault();
    //     console.log('clicked a.expandable');
    //     if (jQuery(this).closest('li').hasClass('expanded') === true) {
    //         jQuery(this).closest('li').removeClass('expanded');
    //         jQuery(this).closest('li').addClass('collapsed');
    //         jQuery(this).siblings('ul').hide();
    //     } else {
    //         jQuery(this).closest('li').removeClass('collapsed');
    //         jQuery(this).closest('li').addClass('expanded');
    //         jQuery(this).siblings('ul').show();
    //     }
    //     return false;
    // });

    //hidemenu()
    // var existConditionMenu = setInterval(function () {
    //     if (jQuery('.usa-nav__close').length) {
    //         console.log("Mobile Menu Exists!");
    //         clearInterval(existConditionMenu);
    //         hidemenu();
    //     }
    // }, 100); // check every 100ms
});

// Load after all other content has loaded
window.addEventListener("load", function () {
//   console.log("page is fully loaded");

    /* Smooth Scroll */
    const links = document.querySelectorAll("a.smooth, .usa-button-group a[href*='#']");

    for (const link of links) {
        link.addEventListener("click", smoothClickHandler);
    }
});