document.addEventListener("DOMContentLoaded", function () {
    const gtmConfiguration = $("#gtm-configuration");
    const pageTagsJson = gtmConfiguration.data("page-tags-json");
    gtmConfiguration.data("gtm-container-id");
    const biibCountry = gtmConfiguration.data("biib-country");
    const biibLanguage = gtmConfiguration.data("biib-language");
    const biibAssetCode = gtmConfiguration.data("biib-asset-code");
    const biibRegion = gtmConfiguration.data("biib-region");
    const gtmContainerId = gtmConfiguration.data("gtm-container-id");
	const currentMDMID = getUrlParameter("mid");
	let userProps;
    let JSONUserProps;
    let visitorID = "undefined";

    // Google Tag Manager DataLayer
    if (typeof dataLayer === "undefined") {
        dataLayer = [];
    }

    if (typeof chkInfo === 'function') {
		userProps = chkInfo();
        JSONUserProps = IsValidJsonString(userProps) && userProps ? JSON.parse(userProps) : [];
        ifUserPropsExist();
	}

    // Populate the Object Attributes
    if (typeof CQ_Analytics !== "undefined") {
        CQ_Analytics.EventDataMgr.data = populate.values;
    }

    // Google Tag Manager DataLayer : Page tags
    dataLayer.push(pageTagsJson);
    // Google Tag Manager DataLayer : SITE DETAILS
    dataLayer.push({
        MDMID: currentMDMID,
        "error_status" : getErrorStatus()
    });

    const cqEventDataMgrData = getEventDataMgrData();

    // Google Tag Manager DataLayer : DIGITAL ASSET
    dataLayer.push({
        'biib_env': getEnvironment(),					// Production environnent
        'biib_asset_code': convertValue(biibAssetCode, '-'),
        'biib_region': biibRegion,
        'biib_language': biibLanguage,
        'biib_country': biibCountry
    });
    // Google Tag Manager DataLayer : DIGITAL ASSET

    dataLayer.push({
        'site_search_team': cqEventDataMgrData.searchTerm,
        'site_search_results': cqEventDataMgrData.resultNumber
    });



    function ifUserPropsExist() {
        //Add the visitor ID to the dataLayer if it's not empty
        visitorID = $.cookie('uuid');
		let loginStatus = getLoginStatus(JSONUserProps);
		let userGroup = getUserGroup(JSONUserProps);
		let userStatus = getUserProp(JSONUserProps, 'status');
		let emailValidCheck = isEmailAddressValid(getUserProp(JSONUserProps, 'email'));
        // Google Tag Manager DataLayer : VISITOR
        dataLayer.push({
            'visitorLoginState': (loginStatus !== null && loginStatus !== undefined) ? loginStatus : '', 					// Login state of the user, anonymous for public websites
            'visitor_login_state': (loginStatus !== null && loginStatus !== undefined) ? loginStatus : '',
            'userGroup' : (userGroup !== null && userGroup !== undefined) ? userGroup : '',
            'user_group' : (userGroup !== null && userGroup !== undefined) ? userGroup : '',
            'visitor_id' : (visitorID !== null && visitorID !== undefined) ? visitorID : '',
            'visitorId' : (visitorID !== null && visitorID !== undefined) ? visitorID : '',
            'user_status' : (userStatus !== null && userStatus !== undefined) ? userStatus : '',
            'biogenEmail' : (emailValidCheck !== null && emailValidCheck !== undefined) ? emailValidCheck : '',
            'biogen_email' : (emailValidCheck !== null && emailValidCheck !== undefined) ? emailValidCheck : ''
        });
    }

    // Google Tag Manager
    (function (w, d, s, l, i) {
        w[l] = w[l] || [];
        w[l].push({
            'gtm.start': new
            Date().getTime(), event: 'gtm.js'
        });
        const f = d.getElementsByTagName(s)[0],
            j = d.createElement(s), dl = l !== 'dataLayer' ? '&l=' + l : '';
        j.async = true;
        j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
        f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', gtmContainerId);
});




function getUserGroup(userProps) {
    return userProps.groups && userProps.groups.length>0 ? userProps["groups"].join(',') : undefined;
}

function getUserProp(userProps, field) {
    return userProps[field];
}

function getErrorStatus() {
    const re = /\w+ (\d{3})/;
    const searchResult = document.title.match(re);
    return searchResult !== null && searchResult.length > 2 ? searchResult[1] : '200';
}

//Retrieve the Environment which the site is running
function getEnvironment() {
    return document.URL.indexOf("biogen-support.com") >= 0 ? "stg" : "prod";
}

//Retrieve the Login Status
function getLoginStatus(userProps) {
    return jQuery.isEmptyObject(userProps) ? "anonymous" : "logged";
}

function getUrlParameter(name) {
    const parsedName = new RegExp("[?&]" + encodeURIComponent(name) + "=([^&]*)").exec(location.search);
    return parsedName != null ? decodeURIComponent(parsedName[1]) : "";
}

function getEventDataMgrData() {
    return (typeof CQ_Analytics !== "undefined" && CQ_Analytics.EventDataMgr.data) ? CQ_Analytics.EventDataMgr.data : {};
}

function IsValidJsonString(str) {
    try {
        const json = JSON.parse(str);
        return (typeof json === 'object');
    } catch (e) {
        return false;
    }
}

function convertValue(value, symbol) {
    const re = new RegExp(symbol, 'g');
    return value !== null && value !== undefined ? value.replace(re, '|') : value;
}

function isEmailAddressValid(email) {
    if (email === undefined) {
        return email;
    }
    const DOMAINS = ['@biogen.com', '@mailinator.com', '@vertic.com', '@anthilagency.com', '@antwerpes.com', '@test.com',
        '@viseven.com'];
    for (let i = 0; i < DOMAINS.length; i++) {
        if (email.indexOf(DOMAINS[i]) > -1) {
            return true;
        }
    }
    return false;
}