/**
 * Init parameters
 */
let holder                = jQuery('#adwords-configuration');
let instantMessagingCode  = holder.data('instant-messaging-code');
let instantMessagingLabel = holder.data('instant-messaging-label');
let newsletterCode        = holder.data('newsletter-code');
let newsletterLabel       = holder.data('newsletter-label');
let ga_tracking_id;

instantMessagingCode  = instantMessagingCode  || null;
instantMessagingLabel = instantMessagingLabel || null;
newsletterCode        = newsletterCode        || null;
newsletterLabel       = newsletterLabel       || null;
ga_tracking_id        = instantMessagingCode  || newsletterCode;

// Include Google Tag Manager script
if (ga_tracking_id) {
    let script   = document.createElement('script');
    script.async = 'async';
    script.src   = 'https://www.googletagmanager.com/gtag/js?id=' + ga_tracking_id;

    jQuery('body').append(script);
}

/**
 * Append arguments to data layer
 */
function gtag() {
    dataLayer.push(arguments);
}

/**
 * Report conversion
 *
 * @param {Object} parameters
 */
function gtag_report_conversion(parameters) {
    // Do not report conversion if AdWords is not configured
    if (ga_tracking_id) {
        gtag('event', 'conversion', parameters);
    }
}

/*
 * Configure newsletter conversion reporting
 */
function gtag_report_conversion_newsletter() {
    // Do not report conversion of newsletter if AdWords is not configured
    if (newsletterCode && newsletterLabel) {
        let sendTo = newsletterCode + '/' + newsletterLabel;
        let name   = 'Newsletter';

        gtag_report_conversion({
            send_to: sendTo,
            name:    name
        })
    }
}

/*
 * Configure instant messaging conversion reporting
 *
 * @param {string} contactType
 */
function gtag_report_conversion_instant_messaging(contactType) {
    // Do not report conversion of instant messaging if AdWords is not configured
    if (instantMessagingCode && instantMessagingLabel) {
        let sendTo = instantMessagingCode + '/' + instantMessagingLabel;
        let name   = contactType;

        gtag_report_conversion({
            send_to: sendTo,
            name:    name
        })
    }
}

// Init Google Tag Manager container
window.dataLayer = window.dataLayer || [];

if (ga_tracking_id) {
    gtag('js', new Date());
}

if (instantMessagingCode) {
    gtag('config', instantMessagingCode);
}

if (newsletterCode) {
    gtag('config', newsletterCode);
}

// Register instant messaging listener on all tagged items
jQuery('body').on('click', '.instant-messaging[data-contact-type]', (event) => {
    let contactType = event.currentTarget.dataset.contactType;

    gtag_report_conversion_instant_messaging(contactType);
});
