/*
// *****************************************************************************
// nico:rewede (https://nicolasim.com/template/)
// -----------------------------------------------------------------------------
// A responsive web design by Nicolás Ibáñez Moreno
// Licensed under CC BY-SA 4.0
//
// (https://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1)
// *****************************************************************************
*/
let bodyWidth = 0;

function init() {
    window.onresize = resize;
    window.onkeyup = handleTab;
    resize();
}

function resize() {
    if (bodyWidth != document.querySelector("body").offsetWidth) {
        bodyWidth = document.querySelector("body").offsetWidth;
        document.getElementById("menu").classList.remove("visible", "hidden");
    }
}

function keyDown(event, fn, params, key = 13) {
    if (event.keyCode == key) {
        if (fn) {
            fn.apply(null, params);
        } else {
            event.target.click();
        }
    }
}

function toggleMenu() {
    const menu = document.getElementById("menu");

    if (menu.classList.contains("visible")) {
        menu.classList.replace("visible", "hidden");
    } else if (menu.classList.contains("hidden")) {
        menu.classList.replace("hidden", "visible");
    } else {
        menu.classList.add("visible");
    }
}

function closeMenu() {
    const menu = document.getElementById("menu");

    if (menu.classList.contains("visible")) {
        menu.classList.replace("visible", "hidden");
    }
}

function scrollPage(id) {
    closeMenu();
    document.getElementById(id).scrollIntoView({ behavior: "smooth" });
}

function handleTab(event) {
    if (event.keyCode == 9) {
        let el = document.activeElement;
        while ((!el.id || el.id != "menu") && el.parentElement) {
            el = el.parentElement;
        }

        if (el.id && el.id == "menu" && window.getComputedStyle(document.getElementById("menu"))["left"] == "-300px") {
            event.preventDefault();
            if (event.shiftKey) {
                document.getElementById("menu-button").focus();
            } else {
                document.getElementById("content").focus();
            }
        }
    }
}

function openUrl(url, blank) {
    if (blank) {
        window.open(url, "_blank");
    } else {
        window.location = url;
    }
}
