
[save_position, restore_position] = function () {
    let basename = "";
    let top_heading_id = "";
    let y_offset = 0;
    let toc_width = 0;
    let save = function () {
        console.log("\n");
        console.log("save_position");
        basename = window.location.toString().split("#")[1];
        let top_heading = first_highlighted_navlink();
        console.log("top heading:");
        console.log(top_heading);
        if (!top_heading) {
            return;
        }
        top_heading_id = K.attr(top_heading, "data-target");

        //y_offset = Math.round(K.top(top_heading) - K.top("#text"));
        let textw = K.get("#text");
        //y_offset = textw.scrollHeight -textw.scrollTop;

        y_offset = K.get("#text").scrollTop;
        console.log("y_offset: " + y_offset);

        toc_width = K.width("#toc");
        console.log("toc_width: " + toc_width);
        console.log("save_position: " + basename + " " + top_heading_id + " " + y_offset);
    }
    let restore = function () {
        let page = K.get("#pagecache #_page_" + basename);
	K.get("#text").innerHTML = page.innerHTML;
        resize_text_width(toc_width);
	K.get("#text").scrollTo(0, y_offset);
    }
    return [save, restore];
}();


function page_cache_id(name) {
    return "_page_" + name;
}

async function cache_pages() {
    if (K.get("#pagecache").children.length === 0) {
        K.style("#pagecache", "display", "none");
        const pagecache = K.get("#pagecache");
        let loads = [];
        pages_basenames().forEach(function (p) {
            let page = document.createElement("div");
            loads.push(K.load(page, "pages/" + p + ".html"));
            K.attr(page, "id", page_cache_id(p));
	    K.attr(page, "class", "content_page");
            pagecache.append(page);
        });

        let help_page = document.createElement("div");
        loads.push(K.load(help_page, "pages/help.html"));
        K.attr(help_page, "id", "help_page");
        pagecache.append(help_page);

        let search_page = document.createElement("div");
        K.attr(search_page, "id", "search_page");
        pagecache.append(search_page);

        await Promise.all(loads);
    }
}


window.addEventListener("popstate", function (event) {
    const parts = window.location.toString().split("#");
    const basename = parts[1];
    const target = parts[2];
    if (basename && target) {
        if (K.get("#help").textContent === "Back") {
            if (!K.visible("#toc")) {
                textshow();
            }
            modify_buttons_for_help("show");
            frame_resize();
        } else {
            go_to_section(null, basename, target, true);
        }
    }
});


window.addEventListener("load", async function (event) {
    let last_location = localStorage.getItem("klammertext_location");
    let last_fit_check = localStorage.getItem("klammertext_fit");
    let last_links_check = localStorage.getItem("klammertext_links");

    await cache_pages();

    K.getv("#toc .caret[data-level='0']").forEach(function (o) {
        if (!K.has_class(o, "caret-down")) {
            o.click();
        }
    });

    // Set initial hash so the browser back button can return to the first page
    if (!window.location.hash) {
        let first = K.get(".navlink");
        if (first) {
            let basename = K.attr(first, "data-page");
            let target = K.attr(first, "data-target");
            history.replaceState(null, null, "#" + basename + "#" + target);
        }
    }

    if (last_location) {
        localStorage.setItem("klammertext_reload", "true");
        let parts = last_location.split(":");
        //console.log("\n");
        //console.log("load parts:");
        //console.log(parts);
        go_to_section(null, parts[0], parts[1], true);
    }

    resize_toc(true);

    // Restore fit and links states directly (not via .click()) to avoid
    // desync with the browser's checkbox state restoration on refresh.
    if (last_fit_check === "true") {
        K.attr("#fit_check", "active", "true");
        K.get("#fit_check").checked = true;
    } else {
        K.attr("#fit_check", "active", "false");
        K.get("#fit_check").checked = false;
    }
    resize_toc();

    if (last_links_check === "true") {
        K.attr("#linkshow_check", "active", "true");
        K.get("#linkshow_check").checked = true;
        show_link_boxes(true);
    } else {
        K.attr("#linkshow_check", "active", "false");
        K.get("#linkshow_check").checked = false;
    }

    /*
    if (last_location) {
        const parts = last_location.toString().split("#");
        console.log("parts:");
        console.log(parts);
        //go_to_section(null, parts[1], parts[2]);
    }
    */

    /*
    let hash = "#" + basename;
    if (target) {
        hash += "#" + target;
    }
    */




    //save_position();
    /*
    let last_location = localStorage.getItem("klammertext_location");
    console.log("last_location from storage: " + last_location);
    if (last_location && last_location != window.location.toString()) {
        //history.replaceState(last_location.toString(), "");
        const parts = last_location.toString().split("#");
        const basename = parts[1];
        const target = parts[2];
        window.location.hash = "#" + basename + "#" + target;
        console.log("last_location: " + basename + " " + target);
        //go_to_section(null, basename, target);

        let locator = "#toc .navlink[data-target='" + target + "'] .section-title-text";
        console.log(locator);
        let title = K.get(locator);
        console.log("title");
        console.log(title);
        title.click();
    }
    */
});





/*
function get_position() {
    const basename = window.location.toString().split("#")[1];
    return [basename, K.get("#text").scrollTop];
}

function set_position(basename, y) {
    K.get("#text").innerHTML = K.get("#_page_" + basename).innerHTML;
    K.get("#text").scrollTo(0, y);
}
*/  


