
var _default_js_pageloader = {
    begin: (url) => { console.log("Started to load " + url); },
    progress: (url, current, total) => { console.log("Progress of " + url + ": " + current + "/" + current + " (" + ((current / total) * 100) + "%)"); },
    loaded: (url, after_load) => { console.log("Loaded " + url); after_load(); }
}

function _default_js_main() {
    let elements = document.getElementsByTagName("a");
    for (element of elements) {
        if (element.hostname == window.location.hostname) {
            element.onclick = _default_js_onclick;
        }
    }

    window.onpopstate = function () {
        var page = window.location
        _default_js_open_page(page, false);
    };

}

function _default_js_onclick(event) {
    event.preventDefault();

    let node = event.target;
    while (node.nodeName != "A") {
        if (node.parentNode == null) {
            return;
        }
        node = node.parentNode;
    }
    let url = node.href;


    _default_js_open_page(url, true);
}

function _default_js_open_page(url, no_pop_state) {
    let request = new XMLHttpRequest();
    request.addEventListener("loadstart", (progress) => {
        _default_js_pageloader.begin(url);
    });
    request.addEventListener("progress", (progress) => {
        _default_js_pageloader.progress(url, progress.loaded, progress.total);
    });
    request.addEventListener("loadend", (progress) => {
        _default_js_pageloader.loaded(url, () => {
            let parser = new DOMParser();
            let new_document = parser.parseFromString(request.responseText, "text/html");
            change_page(new_document, url, no_pop_state);
        });
    });
    request.open("GET", url);
    request.send();
}

function change_page(new_document, new_url, no_pop_state) {

    // Some meta tags
    document.title = new_document.title;

    let new_favicon = "";
    new_favicon = new_document.querySelector("link[rel*='icon']").href;

    document.querySelector("link[rel*='icon']").href = new_favicon;

    // Replace css/js tags
    let list = document.getElementsByClassName("_default_js_meta");
    for (i in list) {
        let element = list[0];
        if (element !== undefined) {
            element.parentNode.removeChild(element);
        }
    }

    let new_list = new_document.getElementsByClassName("_default_js_meta");
    for (i in new_list) {
        let element = new_list[0];
        if (element !== undefined) {
            document.head.appendChild(element);
        }
    }

    // Actually replace the content
    document.body = new_document.body;
    _default_js_main();

    // Do history modifications
    if (no_pop_state) {
        window.history.pushState(new_url, new_url, new_url);
    }

}
