document.addEventListener("DOMContentLoaded", () => {
    base_url = `${window.location.protocol}//${window.location.host.replace(/^nextcloud\./, 'api.')}`
    $.getJSON(`${base_url}/json`, (result) => {
        if (result.logo) {
            $("#navbar-logo #nextcloud img").attr('src', result.logo)
        }
        if (result.product_logo) {
            $("#product-logo img").attr("src", result.product_logo)
        }
        if (result.product_url) {
            $("#product-logo a").attr("href", result.product_url)
        }
    })
    $.get(`${base_url}/header/html/nextcloud`, (result) => {
        $("#dd-megamenu").html(result)
        $('#dropdownMenuAppsButton').click(() => {
            $('#dropdownMenuApps').toggle()
        })
        $('#dropdownMenuApps a').click(() => {
            $('#dropdownMenuApps').toggle()
        })
    })
    $(window).click( (event) => {
        [{parents: '#dropdownMenuAppsButton, #dropdownMenuApps', target: '#dropdownMenuApps'},
         {parents: '#dd-user-menu, #dd-user-menu-trigger', target: '#dd-user-menu-dropdown'},
        ].forEach((it) => {
            if (
                !$(event.target).parents(
                    it.parents
                ).length
            ) {
                $(it.target).hide()
            }
	    })
    })
    $(window).blur( (event) => {
        $('#dropdownMenuApps').hide()
        $('#dd-user-menu-dropdown').hide()
    })
    $('#dd-user-menu-trigger').click(() => {
        $('#dd-user-menu-dropdown').toggle();
    });
})
