/**
 * Check an href for an anchor. If exists, and in document, scroll to it.
 * If href argument omitted, assumes context (this) is HTML Element,
 * which will be the case when invoked by jQuery after an event
 */
function scroll_if_anchor(href) {
    href = typeof(href) == "string" ? href : $(this).attr("href");
    if(!href) return;

    // siteheader Höhe einlesen
    let fromTop = $("#siteheader").outerHeight();

    let $target = $(href);

    if($target.length) {
        $("html, body").animate({ scrollTop: $target.offset().top - fromTop });
        if(history && "pushState" in history) {
            history.pushState({}, document.title, window.location.pathname + href);
            return false;
        }
    }
}

$(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            let target = $(this.hash);
            const offset = 30;
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            let headerHeight = $("#siteheader").outerHeight(true) + offset;

            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top - headerHeight
                }, 500, function() {
                    // Animation complete.
                    headerHeightNew = $("#siteheader").outerHeight(true) + offset;
                    if(headerHeight != headerHeightNew) {
                        $('html, body').animate({
                            scrollTop: target.offset().top - headerHeightNew
                        });
                    }
                });
                return false;
            }
        }
    });
});

jQuery(document).ready(function($) {
    try {
        scroll_if_anchor(window.location.hash);
        $("body").on("click", "a[href^='#']", scroll_if_anchor);
    } catch(e) {}

});
