///////////////////////////////////////////////////////////////
//    Global Variables
//////////////////////////////////////////////////////////////

const app = {
    siteID: 'bluecareplus',                  // value to determine site is pulled in for analytics
    siteName: 'BCP',                // Used to name items in tagging
    devEnvironments: ['anwas65.bcbst.com', 'dev-bluecareplus.bcbst.com'],
    testEnvironments: ['andxtst03', 'test-bluecareplus.bcbst.com', 'test2-bluecareplus.bcbst.com', 'rlse-bluecareplus.bcbst.com'],
    prodEnvironments: ['bluecareplus.bcbst.com'],
    hostname: location.hostname,      // Ex: www.bcbst.com
    pathname: location.pathname,      // Ex: /use-insurance/documents-forms
    urlBreadcrumb: '',                // Ex: use insurance > documents forms
    siteSection: '',                  // Ex: use insurance
    sitePage: '',                     // Ex: documents forms
    searchParameter: '',
    searchResultsNumber: ''
}


///////////////////////////////////////////////////////////////
//    Global Google Analytics
//////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
//    Global Variables
//////////////////////////////////////////////////////////////

const gaApp = {
    environment: 'prod',
    gtmID: 'GTM-5GNS5V6',
    pageType: 'landing page',
    lineOfBusiness: 'member',
    linkType: '',
    productDetailPagesArray: [],
    domains: ['bluecareplus', 'bluecare', 'medicare', 'employer', 'broker', 'provider'],
    currentDomain: '',
};
// Video Player variables
const videoApp = {
    getVideo: '',
    getTitle: '',
    getType: '',
    currentWatch: 0,
    watchDuration: 0,
    watchTime: 0,
    videoBreakpoints: {
        ten: false,
        twentyFive: false,
        fifty: false,
        seventyFive: false,
    },
};
const dataLayer = (window.dataLayer = window.dataLayer || []);

$(document).ready(() => {
    ///////////////////////////////////////////////////////////////
    //    Setting Up GTM
    //////////////////////////////////////////////////////////////
    // Create <head> Script
    const googleScript = document.createElement('script');
    const googleNoScript = document.createElement('noscript');
    const googleIframe = document.createElement('iframe');
    const styles = {
        width: '0px',
        height: '0px',
        display: 'none',
        visibility: 'hidden',
    };
    // Creation of script tag
    googleScript.append(`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var 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','${gaApp.gtmID}');`);

    // Creation of iframe tag
    googleIframe.src = `https://www.googletagmanager.com/ns.html?id=${gaApp.gtmID}`;
    Object.assign(googleIframe.style, styles);
    googleNoScript.append(googleIframe);

    // Adding GTMs to respective places in <head> and <body>
    document.head.append(googleScript);
    document.body.insertBefore(googleNoScript, document.body.firstChild);

    ///////////////////////////////////////////////////////////////
    //    Initiate Helper Functions
    //////////////////////////////////////////////////////////////
    environmentChecker();
    determinePageType();
    determineLOB();

    ///////////////////////////////////////////////////////////////
    //    Pageview Tagging
    //////////////////////////////////////////////////////////////
    dataLayer.push({
        page_type: gaApp.pageType,
        page_name: $('title').first().text().toLowerCase(),
        business_unit: gaApp.lineOfBusiness,
        user_id: undefined,
        group_id: undefined,
    });

    ///////////////////////////////////////////////////////////////
    //    Login Tagging
    //////////////////////////////////////////////////////////////
    $('#login-form-header .button, #login-form button[type$="submit"], #loginBox .btn-primary, [id*="login"] .button').on('click', (event) => {
        const target = event.target;
        let section = 'hero';
        if ($(target).parents().hasClass('sub-nav') || $(target).parents().hasClass('main-nav')) {
            section = 'header';
        }
        dataLayer.push({
            event: 'login',
            click_text: 'log in',
            click_url: $(target).parents('form').attr('action'),
            site_section: `login ${section} form`,
            element_id: `login ${section} form`,
            element_category: 'login',
        });
    });

    ///////////////////////////////////////////////////////////////
    //    Dropdown Clicks
    //////////////////////////////////////////////////////////////
    $('#component-dropdown-button-text, #selectionIndicatorText, .tabSelector,.component-dropdown-menu-item').on('click', (event) => {
        const target = event.target;
        const linktext = evaluateText(target);
        const headerName = searchHeader(target);
        let dropdownState = 'expand';
        let dropdownId = 'drop selection';
        if ($(target).hasClass('tabSelector') || $(target).hasClass('component-dropdown-menu-item')) {
            dropdownState = 'click';
            dropdownId = 'drop selection';
        } else {
            dropdownState = 'expand';
            dropdownId = 'drop selector';
        }
        dataLayer.push({
            event: 'select_content',
            click_text: linktext,
            click_url: undefined,
            site_section: undefined,
            header_name: headerName,
            selection_type: 'click',
            element_id: dropdownId,
            element_category: 'content interaction',
            action: dropdownState,
        });
    });

    ///////////////////////////////////////////////////////////////
    //    Plan Cards
    //////////////////////////////////////////////////////////////
    $('.plan-card .plan-card-link, .plan-card-close').on('click', (event) => {
        let target = event.target;
        const linktext = evaluateText(target);
        const headerName = searchHeader(target);
        let tileState = 'expand';
        if ($(target).hasClass('plan-card-close')) tileState = 'click';
        else tileState = 'expand';
        dataLayer.push({
            event: 'select_content',
            click_text: linktext,
            click_url: undefined,
            site_section: undefined,
            header_name: headerName,
            selection_type: 'click',
            element_id: 'content tile',
            element_category: 'content interaction',
            action: tileState,
        });
    });

    ///////////////////////////////////////////////////////////////
    //    Accordion Tagging/Side Nav Tagging
    //    -Side nav used on Documents & Forms, FAQs, and other pages
    //////////////////////////////////////////////////////////////

    $('.component-text-accordion-card').on('click', (event) => {
        const getChild = $(event.target).parents('.component-text-accordion-card').find('.component-text-accordion-card-body');
        const getChildCSS = $(getChild).css('display');
        const target = $(event.target);
        const linktext = evaluateText(target);
        let state;
        // Check to see if the accordion is open already
        if (getChildCSS === 'none') {
            state = 'collapse';
            // Bypass for other events - instances where 'accordian expand' triggers when it should not
        } else if (getChildCSS === 'block' && $(event.target).hasClass('component-text-accordion-card-header')) {
            state = 'expand';
        }

        // Side Nav Selection
        if ($(event.target).parents().hasClass('component-text-accordion-items') || $(event.target).parents().hasClass('tabbed-document-list')) {
            dataLayer.push({
                event: 'select_content',
                click_text: linktext,
                click_url: undefined,
                site_section: undefined,
                header_name: searchHeader(event),
                selection_type: 'click',
                element_id: 'content toggle',
                element_category: 'content interaction',
                action: 'click',
            });

            // Accordion Clicks
        } else if ($(event.target).is('span')) {
            dataLayer.push({
                event: 'select_content',
                click_text: linktext,
                click_url: undefined,
                site_section: undefined,
                header_name: searchHeader(event),
                selection_type: 'accordion',
                element_id: 'accordion',
                element_category: 'content interaction',
                action: state,
            });
        }
    });

    ///////////////////////////////////////////////////////////////
    //    Nav Hamburger Open/Close Tagging
    //////////////////////////////////////////////////////////////
    $('.header-hamburger-menu').on('click', (event) => {
        let state;
        if ($(event.target).hasClass('open')) state = 'open';
        else state = 'close';
        dataLayer.push({
            event: 'menu_click',
            action: `menu ${state}`,
        });
    });

    ///////////////////////////////////////////////////////////////
    //    Footer Link Tagging
    //////////////////////////////////////////////////////////////

    $('.cmp-psi-unauthenticated-footer a').on('click', (event) => {
        let target = event.target;
        let text = $(target).text().toLowerCase();
        if ($(event.target).is('svg') || $(event.target).is('path')) target = $(event.target).parents('a');
        const clickURL = evaluateHref($(target).attr('href'));
        if ($(target).attr('href').indexOf('facebook') > -1 || $(target).attr('href').indexOf('twitter') > -1 || $(target).attr('href').indexOf('youtube') > -1) text = $(target).attr('class').split('-')[1];
        if (gaApp.currentDomain !== 'bluecare') {
            dataLayer.push({
                event: 'navigation',
                click_text: text,
                click_url: clickURL,
                site_section: 'footer',
                nav_section: 'footer',
            });
        }
    });

    ///////////////////////////////////////////////////////////////
    //    Navigation Link Tagging
    //////////////////////////////////////////////////////////////
    // Dropdown link navigation tagging
    $('.sub-nav a').on('click', (event) => {
        let target = event.target;
        let attrHref = $(target).attr('href');
        let section;
        let clickText;
        // Null check and finding item if needed
        if (attrHref === undefined || attrHref === false || attrHref === 'undefined') {
            target = findItem(event.target);
            attrHref = $(target).attr('href');
        }

        attrHref = evaluateHref(attrHref);
        clickText = $(target).text().toLowerCase();

        if ($(target).is('.nav-item-link, .tertiary')) {
            section = $(target).text().toLowerCase();
        } else {
            section = $(target).parents('.nav-item-title').find('.nav-item-link, .nav-section-link').text().toLowerCase();
        }
        navTagging(attrHref, section, clickText);
    });

    // Logo navigation tagging
    $('.logo-link').on('click', (event) => {
        const attrHref = evaluateHref($(event.target).parent().attr('href'));
        const section = 'logo';
        const clickText = 'logo';
        navTagging(attrHref, section, clickText);
    });

    ///////////////////////////////////////////////////////////////
    //    Video Tagging
    //////////////////////////////////////////////////////////////
    let pathArray;
    let getPage = location.pathname.substring(location.pathname.lastIndexOf('/') + 1).replaceAll('-', ' ');
    if (getPage === '') {
        pathArray = location.pathname.split('/');
        const removeItem = '';
        pathArray = jQuery.grep(pathArray, (value) => {
            return value != removeItem;
        });
        getPage = pathArray.pop();
        if (getPage === '' || getPage === undefined) getPage = 'homepage';
    }
    if (getPage.indexOf('-') > -1) getPage = getPage.replaceAll('-', ' ');
    $.each($('video'), function (ind) {
        $(this).attr('name', getPage + ': video' + parseInt(ind + 1));
        $(this).parent().parent().addClass('videoAnalytics');
    });

    // Triggering Analytics on intial click
    $('.playButton-container, #videoPreviewimg .videoPlayArrow').on('click', (event) => {
        videoInfo(event.target);
        dataLayer.push({
            event: 'video_start',
            site_section: undefined,
            video_percent: '0',
            video_title: videoApp.getTitle,
            video_duration: videoApp.watchDuration,
            video_interaction: 'play',
            video_type: videoApp.getType,
        });
    });

    // Fires video progress tags at intervals during the play of the video
    // - current itervals: 10%, 25%, 50%, 75%
    $('video').bind('timeupdate', function (event) {
        videoInfo(event.target);
        if (videoApp.watchPercent === 10 && videoApp.videoBreakpoints.ten === false) {
            videoApp.videoBreakpoints.ten = true;
            videoProgress();
        } else if (videoApp.watchPercent === 25 && videoApp.videoBreakpoints.twentyFive === false) {
            videoApp.videoBreakpoints.twentyFive = true;
            videoProgress();
        } else if (videoApp.watchPercent === 50 && videoApp.videoBreakpoints.fifty === false) {
            videoApp.videoBreakpoints.fifty = true;
            videoProgress();
        } else if (videoApp.watchPercent === 75 && videoApp.videoBreakpoints.seventyFive === false) {
            videoApp.videoBreakpoints.seventyFive = true;
            videoProgress();
        }
    });

    // Video Ended
    $('video').on('ended', function (event) {
        videoInfo(event.target);
        dataLayer.push({
            event: 'video_complete',
            site_section: undefined,
            video_percent: '100',
            video_title: videoApp.getTitle,
            video_duration: videoApp.watchDuration,
            video_interaction: 'complete',
            video_type: videoApp.getType,
        });
        videoApp.videoBreakpoints = {
            ten: false,
            twentyFive: false,
            fifty: false,
            seventyFive: false,
        };
    });

    ///////////////////////////////////////////////////////////////
    //    Link Clicks
    //////////////////////////////////////////////////////////////
    $('a').on('click', (event) => {
        let target = event.target;
        let attrHref = $(target).attr('href');
        // Null check and finding item if needed
        if (attrHref === undefined || attrHref === false || attrHref === 'undefined') {
            target = findItem(event.target);
            attrHref = $(target).attr('href');
        }
        linkClick(target, attrHref);
    });

    ///////////////////////////////////////////////////////////////
    //    General Form Submissions
    //////////////////////////////////////////////////////////////
    $('a[type$="submit"], button[type$="submit"], input[type$="submit"], span.back').on('click', (event) => {
        const target = event.target;
        const onclickAttr = $(target).attr('onclick');
        // Excluding form submissions from tagging
        if (location.pathname.indexOf('password') > -1 || location.pathname.indexOf('register-member') > -1 || location.pathname.indexOf('username') > -1 || $(target).parents().attr('id') === 'login-form-header' || $(target).parents().attr('id') === 'login-form' || $(target).parents().attr('id') === 'loginBox') {
            // Start tagging
        } else {
            const linktext = evaluateText(event);
            const headerName = searchHeader(event);
            if (typeof onclickAttr === undefined && onclickAttr === false) {
                target = findItem(event);
                onclickAttr = $(target).attr('onclick');
            }
            dataLayer.push({
                event: 'form_submit',
                click_text: linktext,
                click_url: $(target).parents('form').attr('action'),
                header_name: headerName,
            });
        }
    });

    ///////////////////////////////////////////////////////////////
    //    Acoustic Tagging Removal
    //    - Sunseted analytics tool that still has thousands of query string parameters and manual_cm_sp attributes spread throughout our site
    //    - This is the backup to ensure that these attibutes are not shown in reporting
    //////////////////////////////////////////////////////////////
    const linkArray = $('a[href*="cm_sp"], a[href*="cm_mmc"]');
    for (i = 0; i < linkArray.length; ++i) {
        linkArray[i].href = linkArray[i].href.replace(linkArray[i].search, '');
    }
    $('a, button, input, select').removeAttr('manual_cm_sp');
});

///////////////////////////////////////////////////////////////
//    Generic Helper Functions
//////////////////////////////////////////////////////////////

function environmentChecker() {
    if (app.hostname.indexOf('test') > -1 || app.hostname === 'andxtst03:10062') {
        gaApp.environment = 'test';
    } else if (app.hostname.indexOf('dev') > -1 || app.hostname == 'anwas65.bcbst.com:10042') {
        gaApp.environment = 'dev';
    } else {
        gaApp.environment = 'prod';
    }
}

function determinePageType() {
    // Determine if this is a Product Detail Page
    for (i = 0; i < gaApp.productDetailPagesArray.length; ++i) {
        if (location.pathname.indexOf(gaApp.productDetailPagesArray[i]) > -1) {
            gaApp.pageType = 'product detail page';
        }
    }

    // Determine if this is the Homepage
    if (location.pathname === '/') {
        gaApp.pageType = 'homepage';
    }
}

function determineLOB() {
    if (app.hostname.indexOf('provider') > -1) gaApp.lineOfBusiness = 'provider';
    else if (app.hostname.indexOf('broker') > -1) gaApp.lineOfBusiness = 'broker';
    else if (app.hostname.indexOf('employer') > -1) gaApp.lineOfBusiness = 'employer';

    for (i = 0; i < gaApp.domains.length; ++i) {
        if (app.hostname.indexOf(gaApp.domains[i]) > -1) {
            gaApp.currentDomain = gaApp.domains[i];
            break;
        }
    }
}

function trimWCMUrl(url) {
    const baseUrl = new URL(url);
    let path = baseUrl.pathname;
    if (path.indexOf('!ut') > -1) {
        path = path.replace(/sharedhealth\/sharedhealth?.+|publicsites?.+|!ut?.+|\?.+/g, '');
    }
    const trimmedUrl = `${baseUrl.protocol}//${baseUrl.hostname}${path}${baseUrl.search}${baseUrl.hash}`;
    return trimmedUrl;
}

///////////////////////////////////////////////////////////////
//    Evaluation Helper Functions
//////////////////////////////////////////////////////////////

function searchHeader(event) {
    const headerArray = ['h1', 'h2', 'h3', 'h4'];
    let nearestSection = $(event).closest('section');
    if (typeof nearestSection === undefined || nearestSection === false) {
        nearestSection = $(event).closest('div');
    }
    for (i = 0; i < headerArray.length; ++i) {
        const findHeader = $(nearestSection).find(headerArray[i]);
        const headerEvaluation = $(findHeader).is(headerArray[i]);
        if (typeof headerEvaluation !== undefined && headerEvaluation !== false) {
            const headerText = $(findHeader).first().text().toLowerCase();
            const trimText = headerText.trim();
            return trimText;
        }
    }
    return undefined;
}

function evaluateHref(attrHref) {
    let updatedUrl;
    if (attrHref === undefined || attrHref === null || attrHref === '') {
        return attrHref;
    } else if (attrHref.indexOf('javascript') > -1) {
        gaApp.linkType = 'internal';
        updatedUrl = undefined;
        return updatedUrl;
        // Making internal links valid urls for new URL() function in for loop below
        // Check for relative links
    } else if (Array.from(attrHref)[0] === '/') {
        updatedUrl = `${location.protocol}//${location.hostname}${attrHref}`;
        // Check for anchor links
    } else if (Array.from(attrHref)[0] === '#') {
        updatedUrl = trimWCMUrl(`${location.protocol}//${location.hostname}${location.pathname}${attrHref}`);
        gaApp.linkType = 'anchor';
        return updatedUrl;
        // No updates needed
    } else {
        updatedUrl = trimWCMUrl(attrHref);
    }

    // Evaluation for internal vs outbound links
    // Checking against gaApp.domains and internalLinkParamsArray arrays
    for (i = 0; i < gaApp.domains.length; ++i) {
        const url = new URL(updatedUrl);
        const hostname = url.hostname;
        if (updatedUrl.indexOf('javascript') > -1 || updatedUrl.indexOf('mailto:') > -1 || updatedUrl.indexOf('tel:') > -1 || updatedUrl.indexOf('.pdf') > -1 || hostname.indexOf(gaApp.domains[i]) > -1) {
            gaApp.linkType = 'internal';
            break;
        } else {
            gaApp.linkType = 'outbound';
        }
    }
    return updatedUrl;
}

function evaluateText(event) {
    let linkText = $(event).text().toLowerCase();
    if (linkText !== '' || linkText !== false || linkText !== undefined) {
        const trimmedText = linkText.toLowerCase().trim();
        const cleanText = trimmedText.replaceAll('  ', '').replaceAll('\n', '').replaceAll('\t', '');
        return cleanText;
    }
    return undefined;
}

function findItem(event) {
    let newItem = event;
    // Check if a parent is a link
    if ($(event).parents().is('a')) {
        newItem = $(event).parents('a');
        // Check if a parent is a button
    } else if ($(event).parents().is('button')) {
        newItem = $(event).parents('button');
    }
    return newItem;
}

function navTagging(attrHref, section, clickText) {
    dataLayer.push({
        event: 'navigation',
        click_text: clickText,
        click_url: attrHref,
        site_section: 'navigation',
        nav_section: section,
    });
}

///////////////////////////////////////////////////////////////
//    Link/Button Click Helper Functions
//////////////////////////////////////////////////////////////

function linkClick(event, attrHref) {
    const clickURL = evaluateHref(attrHref);
    const linktext = evaluateText(event);
    const headerName = searchHeader(event);

    if (gaApp.linkType === 'outbound') {
        dataLayer.push({
            event: 'outbound_link_click',
            click_text: linktext,
            click_url: clickURL,
            site_section: undefined,
            header_name: headerName,
            element_id: undefined,
            element_category: undefined,
            destination: undefined,
        });
    } else {
        try {
            switch (true) {
                // PDFs
                case clickURL.indexOf('.pdf') > -1:
                    const urlArray = clickURL.split('/');
                    const lastItem = urlArray[urlArray.length - 1];
                    const fileName = lastItem.split('.')[0].replaceAll('-', ' ');
                    dataLayer.push({
                        event: 'file_download',
                        click_text: linktext,
                        click_url: clickURL,
                        site_section: undefined,
                        file_name: fileName,
                        file_type: 'pdf',
                    });
                    break;

                // Email
                case clickURL.indexOf('mailto:') > -1:
                    dataLayer.push({
                        event: 'select_content',
                        click_text: linktext,
                        click_url: clickURL,
                        site_section: undefined,
                        header_name: headerName,
                        selection_type: 'click',
                        element_id: `email: ${linktext}`,
                        element_category: 'content interaction',
                        action: 'click',
                    });
                    break;

                // Phone
                case clickURL.indexOf('tel:') > -1:
                    dataLayer.push({
                        event: 'select_content',
                        click_text: linktext,
                        click_url: clickURL,
                        site_section: undefined,
                        header_name: headerName,
                        selection_type: 'click',
                        element_id: `phone: ${linktext}`,
                        element_category: 'content interaction',
                        action: 'click',
                    });
                    break;

                // Anchor Links
                case gaApp.linkType === 'anchor':
                    dataLayer.push({
                        event: 'select_content',
                        click_text: linktext,
                        click_url: clickURL,
                        site_section: undefined,
                        header_name: headerName,
                        selection_type: 'click',
                        element_id: 'link: anchor',
                        element_category: 'content interaction',
                        action: 'anchor',
                    });
                    break;

                // Start Registration
                case clickURL.indexOf('register-member') > -1:
                    dataLayer.push({
                        event: 'start_registration',
                        click_text: linktext,
                        click_url: clickURL,
                        site_section: 'registration',
                        element_id: `link: ${linktext}`,
                        element_category: 'registration',
                        user_id: undefined,
                        group_id: undefined,
                    });

                // Check for other tagging before firing the general link click
                // - current stops: footer, nav
                case $(event).parents().hasClass('cmp-psi-unauthenticated-footer') || $(event).parents().hasClass('sub-nav') || $(event).parents().hasClass('main-nav') || $(event).hasClass('plan-card-link'):
                    break;

                // General Link Click
                // - Only fires if the other internal tags are not fired
                case $(event).is('a'):
                    dataLayer.push({
                        event: 'internal_link_click',
                        click_text: linktext,
                        click_url: clickURL,
                        site_section: undefined,
                        header_name: headerName,
                        element_id: `link: ${linktext}`,
                        element_category: 'content interaction',
                        action: 'click',
                    });
            }
        } catch (event) {}
    }
}

///////////////////////////////////////////////////////////////
//    Video Helper Functions
//////////////////////////////////////////////////////////////

function videoProgress() {
    dataLayer.push({
        event: 'video_progress',
        site_section: undefined,
        video_percent: videoApp.watchPercent,
        video_title: videoApp.getTitle,
        video_duration: videoApp.watchDuration,
        video_interaction: 'continue',
        video_type: videoApp.getType,
    });
}

function videoInfo(target) {
    const videoTag = $(target).parents('.videoAnalytics').find('video');
    videoApp.getVideo = $(target).parents('.videoAnalytics').find('video');
    videoApp.getTitle = $(videoTag).attr('name').toLowerCase();
    videoApp.getType = $(videoTag).children('source').attr('type');
    videoApp.currentWatch = Math.round(videoTag.get(0).currentTime);
    videoApp.watchDuration = Math.round(videoTag.get(0).duration);
    videoApp.watchPercent = Math.round((videoApp.currentWatch / videoApp.watchDuration) * 100);
}
