/* Minification failed. Returning unminified contents.
(278,79-80): run-time error JS1195: Expected expression: *
(290,15-16): run-time error JS1195: Expected expression: .
(290,23-24): run-time error JS1195: Expected expression: .
(290,40-41): run-time error JS1003: Expected ':': )
(290,55-56): run-time error JS1003: Expected ':': ;
(291,28-29): run-time error JS1006: Expected ')': ;
 */
$(document).ready(() => {
    if (window.location.hash && document.querySelector(".yt-img-container")) {
        youtubeThumbnailClicked(window.location.hash);
    }
});

/*---------------------------------------------------- Thumbnail to video --------------------------------------------------------*/
var currntYTid;
document.querySelectorAll(".yt-img").forEach((el) => {
    el.parentNode.onclick = (e) => e.preventDefault();
    el.onclick = (e) => youtubeThumbnailClicked(e);
});

function youtubeThumbnailClicked(e) {
    let el;
    if (e.target)
        el = e.target;
    else if (document.querySelector(`[data-ytid="${e.substring(1)}"]`))
        el = document.querySelector(`[data-ytid="${e.substring(1)}"]`);
    else return;// some youtube ids dont work as selector id

    let t = document.createElement("iframe");
    currntYTid = el.id;
    t.id = "yt_" + currntYTid;
    t.setAttribute(
        "src",
        "https://www.youtube.com/embed/" +
        el.id +
        "?rel=0&modestbranding=1&enablejsapi=1"
    );//autoplay=1& only worked in ff
    t.setAttribute("frameborder", "0");
    t.style.cssText = el.style.cssText;//for aspectRatio 
    if (window.location.href.indexOf("page") == -1)
        t.style.width = "100%";
    else
        t.setAttribute("width", el.getAttribute("width"));
    //t.addEventListener("load", () => {
    //    let player = new YT.Player(currntYTid, {
    //        events: {
    //            onReady: () => player.playVideo()
    //        }
    //    });
    //});

    el.parentNode.parentNode.replaceChildren(t);
    if (window.location.hash.includes(currntYTid))//only when came from out of website, not click
        t.scrollIntoView();
    YTapiStuff();
    //loadYtapi();
};

function onYouTubeIframeAPIReady() {//this is called from iframe_api
    let player = new YT.Player("yt_" + currntYTid, {
        events: {
            onReady: () => {
                player.mute(); // wont start if not mute
                player.playVideo();
            }
        }
    });
}

function YTapiStuff() {
    if (window.YT && window.YT.Player) {
        onYouTubeIframeAPIReady();
    } else {
        // Load the YouTube Iframe API if not already loaded
        let tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        let firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
    }
}

//function loadAndPlayVideo() {
//    window.YT.ready(() => {
//        var player = new YT.Player("yt_" + currntYTid, {
//            events: {
//                onReady: () => {
//                    player.mute(); // wont start if not mute
//                    player.playVideo();
//                }
//            }
//        });
//    });
//}

//function loadYtapi() {
//    var tag = document.createElement("script");
//    tag.src = "https://www.youtube.com/iframe_api";
//    tag.id = "yt_iframe_api";
//    var firstScriptTag = document.getElementsByTagName("script")[0];
//    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//    whenAvailable("YT", loadAndPlayVideo)
//}

//function whenAvailable(name, callback) {
//    console.log('checking ' + name);
//    var interval = 100; // ms
//    window.setTimeout(function () {
//        if (window[name]) {
//            callback(window[name]);
//        } else {
//            whenAvailable(name, callback);
//        }
//    }, interval);
//}

/*---------------------------------------------------- home impact --------------------------------------------------------*/

//    $.ajax({
//        url: "/home/HomeImpact",
//        dataType: "html",
//        success: function (html) {
//            $('#impact').append(html).fadeIn(500);
//            checkLazyImgs();
//        },
//        error: function (xhr, status, error) {
//            cLog(xhr, status, error);
//        }
//    });

//function cLog(xhr, status, error) {
//    console.log("AJAX error: " + status + "\nError: " + error + "\nDetail: " + xhr.responseText);
//};
let imgCount = document.querySelectorAll("#slider img").length;
if (imgCount > 0) {
    let inSlider = false;
    let pauseSlider = false;
    let perCent = 0;
    let mouseOnSlide = false;
    let slideRun;
//set space based on number of images
    document.querySelector("#slider figure").style.width = `${(imgCount + 1) * 100
        }%`;
    document.querySelector("#slider figure").style.gridTemplateColumns = `repeat(${imgCount + 1
        }, 1fr)`;

    //add first image to the end for smooth transition back to first slide
    let firstImgClone = document
        .querySelector("#slider figure")
        .firstElementChild.cloneNode(true);
    document.querySelector("#slider figure").append(firstImgClone);
    //display first image description
    document.querySelector("figureDescription").innerText = document
        .querySelector(`#slider a:nth-of-type(1) img`)
        .getAttribute("alt");

    //need before sliderTabIndexRest()
    let sliderTabed = document.querySelector("#sliderTabed");

    let pauseBtn = document.querySelector("#pauseBtn");
    pauseBtn.onclick = pauseIt;
    //needed if clicked out during active slides
    pauseBtn.onfocus = () => {
        sliderTabIndexRest();
    };

    //needed when going back from active slides to pauseBtn
    sliderTabed.onkeydown = (e) => {
        if (e.key == "Tab" && e.shiftKey) sliderTabIndexRest();
    };

    // Make slides tabbable checkbox
    sliderTabed.onchange = (e) => {
        // make not tabbable
        if (!e.target.checked) {
            sliderTabIndexRest();
            return;
        }
        // console.log("make slides tabable");
        inSlider = true;
        pauseIt();
        let tabI = 1;
        sliderTabed.tabIndex = tabI++;
        document.querySelectorAll("#imgJumper .imgTab").forEach((el) => {
            el.tabIndex = tabI++;
            document.querySelector(
                `#slider a:nth-of-type(${el.dataset.count})`
            ).tabIndex = tabI++;
        });
        //reset when exisiting last image
        document.querySelector(`#slider a:nth-of-type(${imgCount})`).onkeydown = (e) => {
            if (e.key == "Tab" && !e.shiftKey) sliderTabIndexRest();
        }
    };
    //exit on esc
    document.querySelector("#sliderCon").onkeydown = (e) => {
        if (inSlider && e.key == "Escape") sliderTabIndexRest();
    }

    //set slider tabs to -1 and tabbed checkbox unchecked
    function sliderTabIndexRest() {
        // console.log("reset tabindex");
        inSlider = false;
        sliderTabed.tabIndex = 0;
        document.querySelectorAll("#imgJumper .imgTab").forEach((el) => {
            el.tabIndex = -1;
            document.querySelector(
                `#slider a:nth-of-type(${el.dataset.count})`
            ).tabIndex = -1;
        });
        sliderTabed.checked = false;
    }

    //make img buttons
    for (i = 1; i < imgCount + 1; i++) {
        let btn = document.createElement("button");
        btn.classList.add("imgTab");
        btn.dataset.count = i;
        btn.tabIndex = -1;
        btn.onfocus = jumpToSlide;
        btn.onclick = jumpToSlide;
        btn.setAttribute("aria-label", `slide ${i} of ${imgCount}`);
        imgJumper.append(btn);
        //set corresponding img link with the same i
        let imgLink = document.querySelector(`#slider a:nth-of-type(${i})`);
        imgLink.dataset.count = i;
        //jump to slide when going back
        imgLink.onkeyup = (e) => {
            if (e.key == "Tab" && e.shiftKey) jumpToSlide(e);
        };
    }

    function jumpToSlide(e) {
        //console.log("jumpToSlide");
        perCent = -100 * e.target.dataset.count + 102;
        clearTimeout(slideRun);
        startSliderIn(10);
        pauseIt();
    }

    startSliderIn(4000);
    //mouse on slide
    let imgsDiv = document.querySelector("#slider");
    imgsDiv.addEventListener("mouseover", () => (mouseOnSlide = true));
    // mouse leave slide
    imgsDiv.addEventListener("mouseleave", () => {
        if (pauseSlider) return;
        mouseOnSlide = false;
        clearTimeout(slideRun);
        startSliderIn(1500);
    });

    function moveit() {
        perCent -= 2;
        if (mouseOnSlide) perCent = Math.round((perCent + 30) / 100) * 100; //added 30 to tend to chatch the leaving img
        document.documentElement.style.setProperty("--slider-left", perCent + "%");
        if (perCent == imgCount * -100) {
            perCent = 0;
        }

        document
            .querySelector("figureDescription")
            .classList.toggle("fade", perCent % 100 != 0);
        document.querySelectorAll(`#imgJumper .imgTab`).forEach((el) => {
            el.style.backgroundColor = "#9e9e9e";
        });

        if (perCent % 100 == 0) {
            document.querySelector(
                "figureDescription"
            ).innerText = document
                .querySelector(`#slider a:nth-of-type(${(perCent - 100) / -100}) img`)
                .getAttribute("alt");
            let spanJump = document.querySelector(
                `#imgJumper .imgTab:nth-of-type(${perCent == 0 ? 1 : perCent / -100 + 1})`
            );
            spanJump.style.backgroundColor = "#636363";

            if (mouseOnSlide || pauseSlider) return;
        }

        startSliderIn(
            perCent % 100 == 0 ? 4000 : 200 * (((perCent % 100) + 50) / 100) ** 2
        );
        // : Math.abs(Math.cos((perCent * Math.PI) / 100)) * 50 //slower at the edges
    }

    function startSliderIn(milis) {
        slideRun = setTimeout(moveit, milis);
    }

    function pauseIt(e) {
        // console.log("paused");
        let toggle = false;
        if (e?.target?.id == "pauseBtn") toggle = true;
        mouseOnSlide = true; // so we dont stop in middel of image
        pauseSlider = toggle ? !pauseSlider : true;
        document.querySelector("#pauseBtn").innerText = pauseSlider
            ? "Play"
            : "Pause";
        if (!pauseSlider) {
            mouseOnSlide = false;
            startSliderIn(500);
        }
    }
};
