// BEGIN general Functions
function getLocale() {
    let urlPath = document.URL;
    let locale = '';
    if (document.URL.indexOf('disneyplushelpcenter') != -1) {
        urlPath = document.URL.substring(document.URL.indexOf('disneyplushelpcenter')+21);
        locale = urlPath.substring(0, urlPath.indexOf('/'));
    } else {
        urlPath = document.URL.substring(document.URL.indexOf('.com')+5);
        locale = urlPath.substring(0, urlPath.indexOf('/'));
    }

    const regex = /[a-z]{2}-[a-zA-Z]{2}/gm;
    let localeMatch = locale.match(regex);
    
    if ((locale.length==5 && localeMatch) || locale.length==2) {
        console.log('page-init: locale match: ' + localeMatch);
        return locale;
    } else {
        return 'en-US';
    }
    
}

function getLangCountryStr() {

    let documentURL = document.URL;
    let articleIndex = documentURL.indexOf("article/");
    let isArticle = false;
    let storageCountry = '';
    let storageLanguage = '';
    if (articleIndex != -1) {
        const regex = /-[a-z]{2}-[a-z]{2}-/gm;
        let urlName = documentURL.substring(articleIndex + 8);
        let result = urlName.match(regex);
        console.log('page-init: article page: URL regex match: ' + JSON.stringify(result));
        if (result) {
            storageLanguage = result[0].substring(1,3);
            console.log('page-init: article page: URL language: ' + storageLanguage);
            storageCountry = result[0].substring(4,6);
            console.log('page-init: article page: URL country: ' + storageCountry);
            isArticle = true;
        }
    }

    if (isArticle) {
        return '&language=' + storageLanguage + '&country=' + storageCountry;
    } else {
        return '';
    }
    
}

function isActiveSession() {
    //check for an active session
    let currentStatus = "";
    let language = window.sessionStorage.getItem("LSKey[c]language");
    // add any checks if necessary
    //let storageKey = "-" + language + "___chat";    
    let storageKey = "-___chat";    
    for (i = 0; i < localStorage.length; i++)   {

        if (localStorage.key(i).includes(storageKey)) {

            console.log('page-init: chat-log: isActiveSession found localstorage');

            let sessionStatus = JSON.parse(localStorage.getItem(localStorage.key(i)));
            currentStatus = sessionStatus.session.status;
            break;
        }

    };

    console.log('page-init: chat-log: isActiveSession currentStatus = ' + currentStatus);
    return (currentStatus == "OPEN" || currentStatus == "ASSIGNING" || currentStatus == "CLOSED");
}
// END functions


// BEGIN nice script
const BOT_ALLOWED_COUNTRIES = [
    'US', 'UK', 'AR', 'BR', 'CL', 'CO', 'CR', 'EC', 'MX', 'PA', 'PE', 'UY', 'AU', 'NZ', 'SG',
    'BO', 'DO', 'SV', 'GT', 'HN', 'NI', 'PY', 'VE'
];
const BRAND_DISNEY = 'Disney';
const TIER = 'Tier1';
const SF_BOT_LANGUAGES = [
    {"sfLanguage": "es-AR", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-CL", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-CO", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-CR", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-EC", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-MX", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-PA", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-PE", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-UY", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-US", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-BO", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-DO", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-SV", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-GT", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-HN", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-NI", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-PY", "botLanguage" : "es-LA"},
    {"sfLanguage": "es-VE", "botLanguage" : "es-LA"}
];

function getBotLanguage(sfLanguage) {
    let botLanguage = sfLanguage;
    let filteredValues = SF_BOT_LANGUAGES.filter(item => {
        return item.sfLanguage == sfLanguage;
    });
    return (filteredValues.length > 0) ? filteredValues[0].botLanguage : botLanguage;
}

function isBotEnabled() {
    const isChatBotActive = window.sessionStorage.getItem('LSKey[c]isChatBotActive');
    console.log('page-init: chat-log: isBotEnabled: ' + isChatBotActive);
    //return countryValue && BOT_ALLOWED_COUNTRIES.includes(countryValue);
    //country value ensures country has been set.
    let botEnabled = (isChatBotActive == "true");
    return botEnabled;
}

document.addEventListener('loadnice', function (event) {

    if (typeof brandembassy !== "undefined") { 

        // if nice is already loaded, just set brandembassy fields sent from theme component
        console.log('page-init: chat-log: loadnice: brandembassy already exists');
       // setBrandEmbassyFields();

    } else {
        console.log('page-init: chat-log: loadnice script and init');

        let intervalTimeout = 0;
        let waitForAdobe = setInterval(() => {
        
            if (getCookie('s_fid') != null || intervalTimeout >= 20) {
                clearInterval(waitForAdobe);
                initiateNice();
            } 
            intervalTimeout++;
               
        }, 100);
    }
});

function initiateNice() {
    let brandEmbassyId;
    //let chatProvider = window.sessionStorage.getItem("LSKey[c]chatProvider");

    if (isBotEnabled()) {
        console.log('page-init: chat-log: initiateNice BOT');
        brandEmbassyId = BRAND_EMBASSY_VA_ID;
    } else { //if (chatProvider == "Nice")
        console.log('page-init: chat-log: initiateNice LA_AGENT');
        brandEmbassyId = BRAND_EMBASSY_LIVEAGENT_ID;
    } /*else {
        //no bot and sf chat...no need to instantiate bot
        //we will need to check if brandembassy object is instantiated every where.
        return;
    } */

    console.log('page-init: chat-log: initiateNice');
    (function (i, s, o, r, g, v, a, m) {
        g = v ? g + '?v=' + v : g; i['BrandEmbassy'] = r;
        i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }; i[r].l = +new Date();
        a = s.createElement(o); m = s.getElementsByTagName(o)[0]; a.async = 1;
        a.src = g + '?' + Math.round(Date.now() / 1000 / 3600); m.parentNode.insertBefore(a, m)
    }) (window, document, 'script', 'brandembassy', BRAND_EMBASSY_JS);

    let language = window.sessionStorage.getItem("LSKey[c]language");
    brandembassy('init', 3717, brandEmbassyId, language);
    console.log("page-init: chat-log: BRAND EMBASSY Id: " + brandEmbassyId);

    brandembassy('setWindowWidth', '400px');
    brandembassy('setWindowHeight', '610px');
    brandembassy('setCustomCss', '[data-selector="Header"] {margin-bottom: 18px;}');
    brandembassy('setCustomCss', '[data-selector="MESSENGER"] {display: none;}');

    showHidePreChatSurvey();
    
    //brandembassy('openChatWindow');
    if (isBotEnabled()) {
        brandembassy('sendFirstMessageAutomatically', 'Hello');
    }
    
    //brandembassy('autoStartSession');
    //Displays the chat window as if there are agents available*/
    brandembassy('enableChatAlwaysOnline');

    //SHOW SEND BUTTON*/
    brandembassy('showSendButton');
    //mute sound - VXSS-1123
    brandembassy('muteAudioNotification');

    document.addEventListener('chatBotStatusChange', showHideBot);

    brandembassy('onPushUpdate', ['PageViewCreated'], pageViewPayload => {
        console.log('page-init: chat-log: brandembassy onPushUpdate PageViewCreated entered');
        setBrandEmbassyFields();

        //console.log('is init? : ' + pageViewPayload.data.pageView.isOpeningVisit)
        if (pageViewPayload.data.pageView.isOpeningVisit) {
            // send adobe chat initiation event
            let chatDataProps = {}
            chatDataProps.prop5 = 'Contact Button';
            chatDataProps.evar5 = 'Contact Button';
            chatDataProps.prop6 = 'N/A';
            chatDataProps.evar6 = 'N/A';
            chatDataProps.prop7 = 'FAB';
            chatDataProps.evar35 = 'FAB';
            chatDataProps.event7 = 1;
            chatDataProps.pageName = dataProps.pageName;
            chatDataProps.prop13 = dataProps.prop13;
            chatDataProps.prop14 = dataProps.prop14;
            chatDataProps.prop39 = dataProps.prop39;
            chatDataProps.evar74 = dataProps.evar74;
            chatDataProps.prop27 = dataProps.prop27;
            chatDataProps.evar27 = dataProps.evar27;

            handleAdobeData(chatDataProps, 'event', 'isOpeningVisit PageViewCreated event');
            console.log('page-init: chat-log: onPushUpdate isOpeningVisit: send adobe event7');
        }
    });

    brandembassy('onPushUpdate', ['CaseStatusChanged'], pushUpdatePayload => {
        console.log('page-init: chat-log: brandembassy onPushUpdate CaseStatusChanged entered');
        if (typeof pushUpdatePayload === 'undefined' || typeof pushUpdatePayload.data === 'undefined') {
            return;
        }
        const { status } = pushUpdatePayload.data.case || {};

        console.log('page-init: chat-log: brandembassy onPushUpdate status : ' + status);
        if (typeof status === 'undefined') {
            return;
        }
        // When a previous case has been closed, this will set the custom fields again.

        if (status === 'closed') {
            console.log('page-init: chat-log: call setBrandEmbassyFields (onPushUpdate listener)');
            setBrandEmbassyFields();
        }

    });

    // send custom fields immediately (which works well for new sessions)
    // also send again with delay for existing session with mid-session auth    
    //setBrandEmbassyFields();   
    /*
    setTimeout(() => {
        
    }, BRAND_EMBASSY_DELAY);
    */
    setBrandEmbassyFields();
    showHideBot();
}

//show/hide bot
function showHideBot() {
    let documentURL = document.URL;
    const HIDE_BOT_URL = ['/contact-us', '/feedback/va'];
    let hideBot = false;
    for (const url of HIDE_BOT_URL) {
        hideBot = hideBot || documentURL.indexOf(url) != -1;
    }
    console.log("hideBot = " + hideBot);

    let chatbotActive = window.sessionStorage.getItem("LSKey[c]isChatBotActive");

    console.log ('page-init: chat-log: showHideBot: chatbotactive: ' + chatbotActive + ' not contactus? ' + (documentURL.indexOf('/contact-us') == -1) + ' isActiveSession: ' + isActiveSession());

    if (chatbotActive == "true" && ((!hideBot) || (isActiveSession()))) {
        console.log("page-init: chat-log: show the bot");
        brandembassy('setCustomCss', '[data-selector="MESSENGER"] {display: initial};');
    } else {
        console.log("page-init: chat-log: hide the bot");
        brandembassy('closeWindow');
        brandembassy('setCustomCss', '[data-selector="MESSENGER"] {display: none};');
        
    }

}

function showHidePreChatSurvey() {
    //hide the precontact survey form - 12/10/24 - only for BOT..not for agent*/
    if (isBotEnabled()) {
        console.log("RM:BOT ENABLED: hide PreSurvey");
        brandembassy('hidePreSurvey');
    } else {
        console.log("RM:BOT DISABLED: show PreSurvey");
    }
}

function setBrandEmbassyFields(details) {
    console.log('page-init: chat-log: inside setBrandEmbassyFields : ');
    brandembassy('setCaseCustomField', 'brand', BRAND_DISNEY);
    brandembassy('setCaseCustomField', 'tier', TIER);
    //brandembassy('setCaseCustomField', 'authenticated', "false");
   // brandembassy('setCaseCustomField', 'user_id', "N/A");

    const country = window.sessionStorage.getItem("LSKey[c]country");
    const language = window.sessionStorage.getItem("LSKey[c]language");
    const localCountry = window.localStorage.getItem("LSKey[c]country");
    const localLanguage = window.localStorage.getItem("LSKey[c]language");

    var brandEmbassyCountry = "NO_COUNTRY_FOUND";
    var brandEmbassyLanguage = "NO_LANGUAGE_FOUND";

    if (!isEmpty(country)) {
        brandEmbassyCountry = country;
    } else if (!isEmpty(localCountry)) {
        brandEmbassyCountry = localCountry;
    }

    if (!isEmpty(language)) {
        brandEmbassyLanguage = language;
    } else if (!isEmpty(localLanguage)) {
        brandEmbassyLanguage = localLanguage;
    }        

    
    let botLanguage = getBotLanguage(brandEmbassyLanguage);
    console.log('page-init: chat-log: setBrandEmbassyFields: ' + language + " => botLanguage: " + botLanguage);

    if (LOG_BRANDEMBASSY_DATA) {
        let logId = Math.floor(Math.random() * 1000000);
        logBrandEmbassyData(brandEmbassyCountry, brandEmbassyLanguage, localCountry, localLanguage, country, language, logId);
        brandembassy('setCaseCustomField', 'sflogid', logId);
    }

    brandembassy('setCaseCustomField', 'country', brandEmbassyCountry);
    console.log('page-init: chat-log: setCaseCustomField: country: ' + brandEmbassyCountry);
    brandembassy('setCaseCustomField', 'language', brandEmbassyLanguage);
    console.log('page-init: chat-log: setCaseCustomField: language: ' + brandEmbassyLanguage);
    brandembassy('setCaseCustomField', 'locale', brandEmbassyLanguage.replace('-','_'));
    console.log('page-init: chat-log: setCaseCustomField: locale: ' + brandEmbassyLanguage.replace('-','_'));
    brandembassy('setCaseCustomField', 'botlanguage', botLanguage);
    console.log('page-init: chat-log: setCaseCustomField: botlanguage: ' + botLanguage);
    //set the ipAddress and browser name
    let ipAddress = window.sessionStorage.getItem("LSKey[c]ip");
    brandembassy('setCaseCustomField', 'ipaddress',(ipAddress != null ? ipAddress : 'N/A'));
    brandembassy('setCaseCustomField', 'browser', getBrowserName());
    console.log('page-init: chat-log: setCaseCustomField: ip: ' + (ipAddress != null ? ipAddress : 'N/A') +' browser: ' + getBrowserName());
    
    let adobeId = getCookie('s_fid');
    //adobeId = adobeId?.toLowerCase();
    console.log('page-init: chat-log: setCaseCustomField: adobe: ' + (adobeId != null ? adobeId : 'N/A'));
    brandembassy('setCaseCustomField', 'adobeid', (adobeId != null ? adobeId : 'N/A'));

    //get chatdata from session
    let chatData = window.sessionStorage.getItem("LSKey[c]chatdata");
    //console.log("page-init: chat-log setBrandEmbassyFields: chatData = " + chatData);
    if (chatData) {
        chatData = JSON.parse(chatData);
    }
    let authenticated = chatData && chatData.contactId ? "true" : "false";
    let user_id = chatData && chatData.userId ? chatData.userId : "N/A";
    let identity_id = chatData && chatData.identityId ? chatData.identityId : "N/A";
    let account_id = chatData && chatData.disneyAccountId ? chatData.disneyAccountId : "N/A";
    let swid = chatData && chatData.swid ? chatData.swid : "N/A";
    let name = chatData && chatData.name ? chatData.name : "N/A";
    let email = chatData && chatData.email ? chatData.email : "N/A";
    
    brandembassy('setCaseCustomField', 'authenticated', authenticated);
    console.log("page-init: chat-log: setCaseCustomField: authenticated: " + authenticated);
    brandembassy('setCaseCustomField', 'user_id', user_id);
    console.log("page-init: chat-log: setCaseCustomField: user_id: " + user_id);
    brandembassy('setCaseCustomField', 'identity_id', identity_id);
    console.log("page-init: chat-log: setCaseCustomField: identity_id: " + identity_id);
    brandembassy('setCaseCustomField', 'account_id', account_id);
    console.log("page-init: chat-log: setCaseCustomField: account_id: " + account_id);
    brandembassy('setCaseCustomField', 'swid', swid);    
    console.log("page-init: chat-log: setCaseCustomField: swid: " + swid);
    /*brandembassy('setCaseCustomField', 'name', name);    
    console.log("page-init: chat-log: setCaseCustomField: name: " + name);
    brandembassy('setCaseCustomField', 'email', email);    
    console.log("page-init: chat-log: setCaseCustomField: email: " + email);*/
}

async function logBrandEmbassyData(brandEmbassyCountry, brandEmbassyLanguage, localCountry, localLanguage, country, language, logId) {

    let documentURL = document.URL;
    let index = documentURL.indexOf('.com');
    let baseURL = documentURL.substring(0, index + 4);

    let communityName = COMMUNITY_NAME;
    let communityNameVforce = COMMUNITY_NAME_VFORCE;
    let serviceURL = SITE_DOMAIN + '/' + communityNameVforce;

    if(documentURL.indexOf(communityName) == -1) {
        communityName = "";
        communityNameVforce = "";
        serviceURL = baseURL;
    }

    let calloutURI = serviceURL + '/services/apexrest/BrandEmbassyLoggerService' +
        '?brand=' + BRAND_DISNEY + '&country=' + brandEmbassyCountry + '&language=' + brandEmbassyLanguage +
        '&localLanguage=' + localLanguage + '&localCountry=' + localCountry +
        '&sessionLanguage=' + language + '&sessionCountry=' + country +
        '&tier=' + TIER + '&authenticated=' + false + '&userId=N/A&randomNumber=' + logId;
    fetch(calloutURI, {
        method: "GET",
        cache: 'no-cache'
    }).then((response) => {
        console.log("BrandEmbassy Logged");
    }).catch(error => {
        console.error("Calling async logging error: ", error);
    });

}

/**stop body scrolling when feedback form is displayed**/
document.addEventListener('feedback', function (event) {
    //console.log("Received feedback event.", event.detail.status);
    let body = document.getElementsByTagName("body");
    if (body && body.length > 0) {
        let overflowValue = (event.detail.status == "open") ? "hidden" : "auto";
        body[0].style.overflow = overflowValue;
    }
});

document.addEventListener('startnicechat', function (event) {

    console.log('page-init: chat-log: inside startnicechat event listener');

    let detail = event.detail;
    if (detail.chatServiceProvider == "Salesforce") {

        var top = screen.height-660;//20px margin
        var left=screen.width-375;
    
        if (isBotEnabled()) {
            brandembassy('hideChatWindow');
        }
    
        //set cookie
        let chatType = detail.authenticated ? "startAuthChat" : "startChat";
        document.cookie = "LSKey-c$chatType=" + chatType + "; expires=0; path=/";

        let chatUrl = LIVE_AGENT_URL + "?product=" + BRAND_DISNEY + "&tier=" + TIER + "&language=" + detail.language
            + "&country=" + detail.country + "&contactId=" + detail.contactId + "&accountId=" + detail.accountId
            + "&category=" + detail.category + "&action=" + detail.action 
            + "&switchButtonId=" + detail.switchButtonId + "&ameliaconvid=" + detail.ameliaconvid
            + "&authenticated=" +  detail.authenticated + "&user_id=" +  detail.user_id + "&chatContactId=" + detail.chatContactId;

        let options = "width=375,height=640,toolbar=no,scrollbars=no,resizable=no,titlebar=no,left=" + left + ",top=" + top;
        window.open(chatUrl, "chatwindow", options);
        
    } else {
        //do we need to call setBrandEmbassyFields here?
        brandembassy('setCustomCss', '[data-selector="MESSENGER"] {display: initial};');
        showHidePreChatSurvey();
        brandembassy('openChatWindow');
        //brandembassy('sendFirstMessageAutomatically', 'Hello');
    
        if (!isActiveSession()) {
            brandembassy('hideAssignedAgent');
            //brandembassy('autoStartSession');
        }   
    
    }

});


document.addEventListener('startnicebot', function () {

    console.log('page-init: chat-log: startnicebot event');
    brandembassy('setCustomCss', '[data-selector="MESSENGER"] {display: initial};');
    showHidePreChatSurvey();
    brandembassy('openChatWindow');

    //bot enabled should be true here..but still add check
    if (isBotEnabled()) {
        brandembassy('sendFirstMessageAutomatically', 'Hello');
        if (!isActiveSession()) {
            brandembassy('hideAssignedAgent');
            brandembassy('autoStartSession');
        }
    } else {
        brandembassy('hideAssignedAgent');
    }

});

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
    console.log("page-init: generic message-event");
    
    try{
        var jsonObject = "";
        if (event && event.data && typeof event.data === "string") {
            if (event.data.startsWith("loadSalesForceLiveChat")) {

                console.log('page-init: message-event: chat-log: loadSalesForceLiveChat');

                const delimiter = "#sep#";
                const splitArray = event.data.split(delimiter);
                try {
                    jsonObject = JSON.parse(splitArray[1]);
                    console.log("page-init: message-event: chat-log: json object: ", jsonObject);
                } catch (error) {
                    console.error("page-init: chat-log: Error parsing JSON:", error);
                }

                let country = window.sessionStorage.getItem("LSKey[c]country");
                let language = window.sessionStorage.getItem("LSKey[c]language");

                let chatData = window.sessionStorage.getItem("LSKey[c]chatdata");
                console.log("page-init: message-event: chat-log: chatData = " + chatData);
                if (chatData) {
                    chatData = JSON.parse(chatData);
                }
                let accountId = chatData && chatData.accountId ? chatData.accountId : null;
                let contactId = chatData && chatData.contactId ? chatData.contactId : null;
                let authenticated = contactId != null;
                let user_id = chatData && chatData.userId ? chatData.userId : "N/A";
                let chatContactId = chatData && chatData.chatContactId ? chatData.chatContactId : null;

                //set cookie
                let chatType = authenticated ? "EscalateAuthChat" : "EscalateChat";
                document.cookie = "LSKey-c$chatType=" + chatType + "; expires=0; path=/";                

                //minimize the VA chat
                if (isBotEnabled()) {
                    brandembassy('hideChatWindow');
                }

                let w = 375;
                let h = 650;
                let l = window.innerWidth - w;
                let t = window.innerHeight - h;
                let options = "width=" + w + ",height=" + h + ",toolbar=no,scrollbars=no,resizable=no,titlebar=no,left=" + l + ",top=" + t;

                let chatUrl = LIVE_AGENT_URL + "?product=" + BRAND_DISNEY + "&tier=" + TIER + "&language=" + language
                + "&country=" + country + "&contactId=" + contactId + "&accountId=" + accountId
                + "&category=" + "&action=EscalateChat" + "&switchButtonId=1" + "&ameliaconvid=" + jsonObject.ameliaconvid
                + "&authenticated=" + authenticated + "&user_id=" + user_id + "&chatContactId=" + chatContactId;
        
                window.open(chatUrl, "chatwindow", options);
            }

            if (event.data.startsWith("setnicefields")) {

                try {
                    //let country = window.sessionStorage.getItem("LSKey[c]country");
                    //let language = window.sessionStorage.getItem("LSKey[c]language");

                    console.log('page-init: message-event: chat-log: call setBrandEmbassyFields');
                    setBrandEmbassyFields();

                    showHidePreChatSurvey();
                    if (isBotEnabled()) {
                        brandembassy('sendFirstMessageAutomatically', 'Hello');
                        if (!isActiveSession()) {
                            brandembassy('hideAssignedAgent');
                            brandembassy('autoStartSession');
                        }
                    } else {
                        brandembassy('hideAssignedAgent');
                    }

                } catch (error) {
                    console.error("page-init: chat-log: Error parsing JSON:", error);
                }
            }

            if (event.data.startsWith("startnicebot")) {
                
                console.log('page-init: message-event: chat-log: startnicebot');

                //Rohit - 021425 - to handle Fab showing up for live agent
                if (isBotEnabled()) {
                    brandembassy('setCustomCss', '[data-selector="MESSENGER"] {display: initial};');
                }
                
                showHidePreChatSurvey();
                //brandembassy('openChatWindow');

                if (isBotEnabled()) {
                    brandembassy('sendFirstMessageAutomatically', 'Hello');
                    if (!isActiveSession()) {
                        brandembassy('hideAssignedAgent');
                        brandembassy('autoStartSession');
                    }
                } else {
                    brandembassy('hideAssignedAgent');
                }         

            }         
            
            if (event.data.startsWith("{")) {

                let eventData = JSON.parse(event.data);
                console.log('page-init: message-event: object data: ' + eventData);
                
                if (eventData.event && eventData.event == 'play') {
                    console.log('page-init: handleAdobeData-callout: video play event: ' + eventData.event);

                    const eventProps = {
                        'event17': 1,
                        'prop13': dataProps.prop13,
                        'prop14': dataProps.prop14,
                        'prop39': dataProps.prop39,
                        'evar74': dataProps.evar74,
                        'prop27': dataProps.prop27,
                        'evar27': dataProps.evar27,
                    };
                    handleAdobeData(eventProps, 'event', 'vidvard video play event');
                }
            }
        } 

    } catch(err) {
        console.error("page-init: chat-log: Error in receiveMessage broadcast:", err);
    }        
}
// END Nice chat

// BEGIN primary Salesforce events pageref and writemeta 
document.addEventListener('pagerefchange', function (event) {
    console.log("page-init: pagerefchange event start.");
    if ((typeof brandembassy != "undefined") && isBotEnabled()) {
        showHideBot();
    }

    // check for first time ref for this session.  if first pageref, add unload listener.  if listener exists and pageref runs, remove listener
    if (!window.sessionStorage.getItem('LSKey[c]firstPage')) {
        console.log('page-init: pagerefchange: set firstpage true');
        window.sessionStorage.setItem('LSKey[c]firstPage','true');
    } else if (window.sessionStorage.getItem('LSKey[c]firstPage') == 'true'){
        console.log('page-init: pagerefchange: no longer on first page, set firstPage to false');
        // window.removeEventListener("beforeunload", beforeUnloadHandler, { once: true });
        window.sessionStorage.setItem('LSKey[c]firstPage','false');
    }

    let documentURL = document.URL;

    handleRobotsMetaTag(documentURL);

    console.log('page-init: pagerefchange: adobe: set analytics props');
    if (event.detail.isGuest == true) {
        // login status
        dataProps.prop39 = 'Unauthenticated';
        dataProps.evar74 = 'Unauthenticated';
    } else {
        // login status
        dataProps.prop39 = 'Authenticated';
        dataProps.evar74 = 'Authenticated';
    }

    // function in common markup - check for campaign and other incoming querystring params that need to pass to adobe analytics
    checkQueryParams();

    if (document.title == 'Error') {
        dataProps.pageName = '404 Error Page';
        dataProps.prop27 = '404 Error Page';
        dataProps.evar27 = '404 Error Page';
        dataProps.prop14 = '404 Error Page';
        dataProps.prop13 = document.title;
        console.log('page-init: handleAdobeData-callout: error page');
        handleAdobeData(dataProps, 'page', 'pagerefchange - Error page');
    } else if (documentURL.indexOf('/article') == -1 && documentURL.indexOf('/category') == -1) {

        console.log('page-init: pagerefchange: not an article or category page');

        let elements = document.querySelectorAll("[data-src='js']");
        if (elements) {
            elements.forEach(e => {
                e.remove();
            });
        }

        setTimeout(() => {
    
            dataProps.prop13 = document.title;
            // "Parent Page Title" - English version of title for non-article pages.  article version in writemetatags event
    
            if (document.URL.indexOf('/contact-us') !== -1) {
                dataProps.pageName = 'Contact Us';
                dataProps.prop27 = 'Contact Us';
                dataProps.evar27 = 'Contact Us';
                dataProps.prop14 = 'Contact Us';
            } else if (document.URL.indexOf('/global-search') !== -1) {
                dataProps.pageName = 'Global Search';
                dataProps.prop27 = 'Global Search';
                dataProps.evar27 = 'Global Search';
                dataProps.prop14 = 'Search Results';
            } else if (document.URL.indexOf('/feedback') !== -1) {
                dataProps.pageName = 'Site Feedback';
                dataProps.prop27 = 'Site Feedback';
                dataProps.evar27 = 'Site Feedback';
                dataProps.prop14 = 'Site Feedback';
            } else {
                dataProps.pageName = 'Home';
                dataProps.prop27 = 'Home';
                dataProps.evar27 = 'Home';
                dataProps.prop14 = 'Home';
            }
            console.log('page-init: handleAdobeData-callout: pagerefchange: setting pagename: ', dataProps);
            handleAdobeData(dataProps, 'page', 'pagerefchange - ' + dataProps.pageName);
        }, 100);
    }
        
});

function handleRobotsMetaTag(urlPath) {
    //hardcode for now
    console.log("handleRobotsMetaTag");
    let elements = document.querySelectorAll("[content='nosnippet']");
    if (elements) {
        elements.forEach(e => {
            e.remove();
        });
    }

    let regex = /disneyplus-[a-z]{2}-[a-z]{2}-cancel/;
    if (urlPath.indexOf("/article/disneyplus-cancel") != -1 || regex.test(urlPath)) {
        var link = document.createElement('meta');
        link.setAttribute('name', 'robots');
        link.content = 'nosnippet';
        document.getElementsByTagName('head')[0].appendChild(link);
    }
}


/**dynamically add metadata to article pages **/
document.addEventListener('writemetatags', function (event) {
    console.log("page-init: Received writemetatags event.");
    console.log("title: " + event.detail.title);
    console.log("summary: " + event.detail.summary);
    console.log("page:" + event.detail.page);

    let elements = document.querySelectorAll("[data-src='js']");
    if (elements) {
        elements.forEach(e => {
            e.remove();
        });
    }

    if (event.detail.page == "category") {

        // adobe code needed for article page.  need to wait for this meta before firing
        dataProps.pageName = 'Help Topic';
        dataProps.prop27 = 'Help Topic';
        dataProps.evar27 = 'Help Topic';
        dataProps.prop13 = document.title;
        dataProps.prop14 = event.detail.topic;
        console.log('page-init: handleAdobeData-callout: category page');
        handleAdobeData(dataProps, 'page', 'category page');

        var link = document.createElement('meta');
        link.setAttribute('name', 'og:url');
        link.content = document.URL;
        link.setAttribute("data-src", "js");
        document.getElementsByTagName('head')[0].appendChild(link);

    } else {

        // adobe code needed for article page.  need to wait for this meta before firing
        dataProps.pageName = 'Article Detail';
        dataProps.prop27 = 'Article Detail';
        dataProps.evar27 = 'Article Detail';
        dataProps.prop13 = document.title;
        dataProps.prop14 = event.detail.parenttitleenglish;
        //Article Updated Date: prop15
        dataProps.prop15 = event.detail.lastpublished;
        //Article Version: prop16
        dataProps.prop16 = event.detail.articleversionnumber;
        //salesforce URLname: prop28
        dataProps.prop28 = event.detail.urlname;
        // category
        dataProps.prop34 = event.detail.category;

        console.log('page-init: handleAdobeData-callout: article detail page');
        handleAdobeData(dataProps, 'page', 'article detail page');

        var link = document.createElement('meta');
        link.setAttribute('name', 'og:title');
        link.content = event.detail.title;
        link.setAttribute("data-src", "js");
        document.getElementsByTagName('head')[0].appendChild(link);

        link = document.createElement('meta');
        link.setAttribute('name', 'og:description');
        link.content = event.detail.summary;
        link.setAttribute("data-src", "js");
        document.getElementsByTagName('head')[0].appendChild(link);

        link = document.createElement('meta');
        link.setAttribute('name', 'description');
        link.content = event.detail.summary;
        link.setAttribute("data-src", "js");
        document.getElementsByTagName('head')[0].appendChild(link);

        //<meta name="robots" content="noindex">
        if (event.detail.suppress) {
            link = document.createElement('meta');
            link.setAttribute('name', 'robots');
            link.content = "noindex";
            link.setAttribute("data-src", "js");
            document.getElementsByTagName('head')[0].appendChild(link);
        }   
    }

    let canlink = document.createElement('link');
    canlink.setAttribute('rel', 'canonical');
    let primSession =  window.sessionStorage.getItem('LSKey[c]primaryLocale');
    let pathname = location.pathname;
    if (event.detail.page=='article' && primSession == 'true')  {
        const regex = /-[a-z]{2}-[a-z]{2}-/gm;
        pathname = pathname.replace(regex, "-");
    }
    canlink.href = location.protocol + '//' + location.host + pathname;
    canlink.setAttribute("data-src", "js");
    console.log('page-init: add custom canonical');
    document.getElementsByTagName('head')[0].appendChild(canlink);

});
// END SF events

function seoTagObserver() {
    const targetNode = document.head;
    const config = { childList: true, subtree: true };
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
        if (mutation.addedNodes.length > 0) {
            const newElement = mutation.addedNodes[0];
            if (newElement.matches && newElement.matches("[hreflang][data-owner='setSEOProperties']")) {
                //console.log("mutation observer found hreflang " , newElement);
                newElement.remove();
            }
            if (newElement.matches && newElement.matches("[rel='canonical'][data-owner='setSEOProperties']")) {
                if (document.URL.indexOf("/article/") != -1 || document.URL.indexOf("/category/") != -1) {
                    //console.log("mutation observer found category/article page canonical " , newElement);
                    newElement.remove();
                }
                
            }
        }
        });
    });
    observer.observe(targetNode, config);
}	 

function initializeSession() {

    let documentURL = document.URL;
    let index = documentURL.indexOf('.com');
    let baseURL = documentURL.substring(0, index + 4);

    let communityName = COMMUNITY_NAME;
    let communityNameVforce = COMMUNITY_NAME_VFORCE;
    let serviceURL = SITE_DOMAIN + '/' + communityNameVforce;

    if(documentURL.indexOf(communityName) == -1) {
        communityName = "";
        communityNameVforce = "";
        serviceURL = baseURL;
    } else {
        baseURL += '/' + communityName;
    }

    //Rohit 12042023 - VXSS-370
    /*
    let articleIndex = documentURL.indexOf("article/");
    let storageLanguage = window.localStorage.getItem('LSKey[c]language');
    if (storageLanguage) {
        storageLanguage = storageLanguage.substring(0,2).toLowerCase();
    }
    let storageCountry = window.localStorage.getItem('LSKey[c]country');
    if (storageCountry) {
        storageCountry = storageCountry.toLowerCase();
    }
    console.log("pre storageLanguage = " + storageLanguage);
    console.log("pre storageCountry = " + storageCountry);
    
    let isArticle = false;
    if (articleIndex != -1) {
        const regex = /-[a-z]{2}-[a-z]{2}-/gm;
        let urlName = documentURL.substring(articleIndex + 8);
        let result = urlName.match(regex);
        console.log(JSON.stringify(result));
        if (result) {
            if (storageLanguage != result[0].substring(1,3)) {
                console.log('page-init: article page: URL language doesnt match session: ' + storageLanguage);
                storageLanguage = result[0].substring(1,3);
                isArticle = true;
            }
            if (storageCountry != result[0].substring(4,6)) {
                console.log('page-init: article page: URL country doesnt match session: ' + storageCountry);
                storageCountry = result[0].substring(4,6);
                isArticle = true;
            }
        }
    }
    console.log("documentURL = " + documentURL);
    console.log("storageLanguage = " + storageLanguage);
    console.log("storageCountry = " + storageCountry);
    console.log("isArticle = " + isArticle);
    */
    // VXSS-370

    let ipPromise = new Promise(function(resolve, reject) {
        
        console.log('page-init: initializeSession: begin promise');

        let calloutURI = serviceURL + '/services/apexrest/IPService?brand=Disney';
        if(isCrawlerBot()) {

            if (window.sessionStorage.getItem('LSKey[c]botLoaded')) {
                console.log('page-init: initializeSession: bot already loaded, resolve promise');
                window.sessionStorage.removeItem('LSKey[c]botLoaded');
                return resolve();
            }

            // this version of the callout for bots only to get metadata record for locale
            calloutURI += '&iscrawlerbot=true&locale=' + getLocale() + getLangCountryStr();
            console.log('page-init: crawlerbot TRUE: ' + calloutURI);
            fetch(calloutURI, {
                method: "GET",
            })
            .then((response) => response.json())
                .then(repos => {
                    console.log("page-init: ip service callback json for bot: ", repos);
                    window.sessionStorage.setItem('LSKey[c]ip', repos.ipAddress);
                    window.localStorage.setItem('LSKey[c]ip', repos.ipAddress);

                    window.sessionStorage.setItem('LSKey[c]botLoaded', 'true');

                    if (repos.isAvailable) {
                        setSession(repos);
                        console.log("page-init: bot reload page: ", document.URL);
                        window.open(document.URL, "_self");
                    } else {
                        window.sessionStorage.setItem('LSKey[c]country', 'US');
                        window.sessionStorage.setItem('LSKey[c]countryName', 'United States');
                        window.sessionStorage.setItem('LSKey[c]metadataName', 'United_States_English');
                        window.sessionStorage.setItem('LSKey[c]language', getLocale()); // this is to stop country/lang selector from reloading page again
                        window.sessionStorage.setItem('LSKey[c]region', 'NA');
                        window.sessionStorage.setItem('LSKey[c]primaryLocale', 'true');
                        window.localStorage.setItem('LSKey[c]country', 'US');
                        window.localStorage.setItem('LSKey[c]countryName', 'United States');
                        window.localStorage.setItem('LSKey[c]metadataName', 'United_States_English');
                        window.localStorage.setItem('LSKey[c]language', getLocale());
                        window.localStorage.setItem('LSKey[c]region', 'NA');
                        window.localStorage.setItem('LSKey[c]primaryLocale', 'true');
                        // set local/session so we don't trigger another refresh
                        // an isAvailable of false for bot means bad page / redirect to 404
                        console.log("page-init: bot send to 404 page: ", document.URL);
                        window.open(location.protocol + '//' + location.host + '/error-404', "_self");
                    }
                })
                .catch(error => {
                    reject();
                    console.error("error1:" + error);
                })
            .catch(error => {
                reject();
                console.error("error2:" + error);
            });
        } else {

            //VXSS-370
            /*
            if(isArticle) {
                calloutURI += '&isarticle=true&language=' + storageLanguage + '&country=' + storageCountry;
            } 
            */
            //VXSS-370

            // if (!isArticle) {  // VXSS-370 - remove conditional if not using 370

            let response = verifySessionStorage();
            if(response != 'create-session'){

                if (response == 'local-exists') {
                    window.sessionStorage.setItem('LSKey[c]originalReferrer', document.referrer);
                }
                console.log('page-init: initializeSession: session already set');
                return resolve();
            } else {
                console.log('page-init: initializeSession: need to create session');
            }
            //}
            
            let browserLanguage = navigator.language;
            //get the 2 letter language
            browserLanguage = (browserLanguage) ? browserLanguage.substring(0, 2).toUpperCase() : "";
            console.log("browserLanguage = " + browserLanguage);
            calloutURI += "&browserLanguage=" + browserLanguage;
            console.log('page-init: crawlerbot FALSE: ' + calloutURI);
            fetch(calloutURI, {
                method: "GET"
            })
            .then((response) => response.json())
                .then(repos => {
                    console.log("page-init: ip service callback json: ", repos);

                    if(!repos.isAvailable){
                        console.log("page-init: not available");
                        window.open(repos.notAvailableURL, '_self');
                        return resolve();
                    }

                    // if allowAdobe doesn't already exist, create it as false
                    if (!window.sessionStorage.getItem('LSKey[c]allowAdobe')) {
                        if (repos.region == 'APAC' || repos.region == 'LATAM') {
                            window.sessionStorage.setItem('LSKey[c]allowAdobe', 'allow');
                        } else {
                            window.sessionStorage.setItem('LSKey[c]allowAdobe', 'reject');
                        }
                    }
                
                    setSession(repos);

                    let languageValue = repos.languageCode;
                    if (languageValue == "en-US") {
                        languageValue = "";
                        document.cookie = "PreferredLanguage0DM8L000000Gn4tWAC=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
                    } else {
                        languageValue = "/" + languageValue;
                    }

                    let pageName = documentURL.substring(documentURL.lastIndexOf('/'));
                    let subPath = "";
                    //console.log('pagename: ' + pageName + ' subpath: ' + subPath);

                    // article url fix 
                    //text.replace(/-[a-z]{2}-[a-z]{2}-/gm, '-en-us-');

                    if (documentURL.indexOf("article") != -1) {
                        subPath = "/article";

                        const regex = /-[a-z]{2}-[a-z]{2}-/gm;
                        let urlMatch = pageName.match(regex);
                        let newLocale = '-'+(repos.languageCode.substring(0,2)).toLowerCase()+'-'+(repos.countryCode).toLowerCase()+'-';

                        if (urlMatch && urlMatch != newLocale) {
                            pageName = pageName.replace(/-[a-z]{2}-[a-z]{2}-/gm, newLocale);
                        }
                        
                    } else if (documentURL.indexOf("contact-us") != -1 && pageName != '/contact-us') {
                        subPath = '/contact-us';
                    } else if (documentURL.indexOf("category") != -1 && pageName != '/category') {
                        subPath = '/category';
                    } else if (documentURL.indexOf("feedback") != -1 && pageName != '/feedback') {
                        subPath = '/feedback';
                    }
                    console.log('subPath updated: ' + subPath);
                    if (pageName == null) {
                        pageName = "";
                    }

                    var url = baseURL + languageValue + subPath + pageName ;
                    console.log("page-init: reload page: ", url);
                    window.sessionStorage.setItem('LSKey[c]originalReferrer', document.referrer);
                    window.sessionStorage.removeItem('LSKey[c]firstPage');
                    console.log('page-init: reload page: original referrer value: ', document.referrer);
                    window.open(url, "_self");
                })
                .catch(error => {
                    reject();
                    console.error("page-init: error1:" + error);
                })
            .catch(error => {
                reject();
                console.error("page-init: error2:" + error);
            });
        } 
    });

    ipPromise.then(() => {
        console.log('page-init: initializeSession promise resolved');

        window.addEventListener("beforeunload", beforeUnloadHandler, { once: true });
        seoTagObserver();
        //initiateNice();
    });
    ipPromise.catch(() => {
        console.log('page-init: initializeSession promise REJECTED');
    })
    
}

//this call kicks off everything needed on initial page load
console.log('page-init: call initializeSession');
initializeSession();