function flagExternalLinks() {

    $.getJSON('/assets/get-domains', function (domains) {

        hostname = new RegExp(location.host);

        var allowed_domains = [];

        $.each(domains, function (key, val) {
            if (typeof val !== 'undefined') {
                allowed_domains.push(val);
            }
        });

        window.allowed_domains = allowed_domains;

        $('a').each(function (i, v) {

            var url = $(v).attr("href");

            if (
                (typeof url != 'undefined'
                && (
                    url.toLowerCase().indexOf('http') == 0
                    || url.toLowerCase().indexOf('https') == 0
                )
                && url.slice(0, 1) != "#"
                && hostname.test(url) !== true
                && checkValidDomain(url, allowed_domains) !== true
                && new URL(url).hostname !== window.location.hostname)
                || url === '#login-option'
            ) {
                $(v).addClass('external-link-warning')
                    .attr('data-toggle', 'modal')
                    .attr('data-target', '#external-link-warning')
                    .attr('data-url', url)
                    .attr('href', '#');
            }
        });
    });

}

function checkValidDomain(_domain, _allowed) {

    for (i = 0; i < _allowed.length; i++) {

        if (_allowed[i] != '' && _domain.toLowerCase().indexOf(_allowed[i]) != -1) {
            return true;
        }
    }

    return false;
}

(function (window, document) {

    setTimeout(function () {
        flagExternalLinks();
    }, 500);

})(window, document);


$('#external-link-warning').on('show.bs.modal', function (event) {

    $('a#external-link-button').attr('href', event.relatedTarget.dataset.url);
    $('a#external-link-button').attr('target', event.relatedTarget.dataset.target);

    // Close the menu when the modal is shown
    const navToggle = document.querySelector('.primary-header__nav-toggle');
    if (navToggle && document.documentElement.classList.contains('menu-open')) {
        navToggle.click();
    }

});

$('a#external-link-button').click(function () {
    $('#external-link-warning').modal('hide');
});
