function pass_utm(target_url) {
    // Get the current URL
    var currentUrl = new URL(window.location.href);

    // Get UTM parameters
    var utmSource = currentUrl.searchParams.get("utm_source");
    var utmMedium = currentUrl.searchParams.get("utm_medium");
    var utmCampaign = currentUrl.searchParams.get("utm_campaign");

    // Create a new URL object
    var newUrl = new URL(target_url);

    // Get the search parameters of the new URL
    var params = newUrl.searchParams;

    // Append UTM parameters to the new URL
    if (utmSource) params.set("utm_source", utmSource);
    if (utmMedium) params.set("utm_medium", utmMedium);
    if (utmCampaign) params.set("utm_campaign", utmCampaign);

    // Set the search parameters of the new URL
    newUrl.search = params.toString();

    return newUrl.toString();
}

document.addEventListener('DOMContentLoaded', function() {
    $.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;

        // Wait for potential accordions, etc
        setTimeout(() => {
            document.querySelectorAll('a[href]').forEach(function(element) {
                var targetUrl = element.getAttribute('href');
                if (!targetUrl) {
                    return;
                }

                // console.log('allowed_domains', allowed_domains);
                // console.log('targetUrl', targetUrl);

                function getDomain(url) {
                    var a = document.createElement('a');
                    a.href = url;
                    return a.hostname.replace('www.', '');
                }

                var targetDomain = getDomain(targetUrl);
                // console.log('targetDomain', targetDomain);

                var isMatchingUrl = allowed_domains.some(url => targetDomain === url);
                if (isMatchingUrl) {
                    element.setAttribute('href', pass_utm(targetUrl));
                }
            });
        }, 1000);

    });
});

