// Utility Functions function setCookie(cname, cvalue, domain, duration) { const d = new Date(); let expires = '', calc_duration = 0, set_domain; if (duration) { if (duration.minutes) { calc_duration = duration.minutes * 60 * 1000; } else if (duration.hours) { calc_duration = duration.hours * 60 * 60 * 1000; } else if (duration.days) { calc_duration = duration.days * 24 * 60 * 60 * 1000; } else if (duration.weeks) { calc_duration = duration.weeks * 7 * 24 * 60 * 60 * 1000; } else if (duration.months) { calc_duration = duration.months * 30 * 24 * 60 * 60 * 1000; } else if (duration.years) { calc_duration = duration.years * 365 * 24 * 60 * 60 * 1000; } d.setTime(d.getTime() + calc_duration); expires = "expires=" + d.toUTCString() + ';'; } set_domain = domain ? domain : '.' + document.domain.replace('www.', ''); document.cookie = cname + "=" + cvalue + ";" + expires + "domain=" + set_domain + ";path=/;" + "SameSite=None; secure;"; } function getCookie(cname) { const result = new RegExp('(?:^|; )' + encodeURIComponent(cname) + '=([^;]*)').exec(document.cookie); return result ? decodeURIComponent(result[1]) : null; } // User Location Details function initializeUserDetails() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { const data = JSON.parse(this.responseText); setCookie('tvc_location_details', JSON.stringify({ ct: data.ct, rg: data.rg, lat: data.lat, long: data.long }), '.bajajfinserv.in'); setCookie('tvc_device_details', JSON.stringify({ dc: data.dc, os: data.os, osv: data.osv, br: data.br, brv: data.brv }), '.bajajfinserv.in'); setCookie('tvc_user_city', data.ct, '.bajajfinserv.in'); } }; xhttp.open("GET", "https://ua-ip-lookup-dot-bajaj-finserv-177211.appspot.com/?os", true); xhttp.send(); } // Clevertap Functions function initializeClevertap() { if (typeof clevertap !== 'undefined') { const ct_id = clevertap.getCleverTapID(); window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'ct_id': ct_id }); setCookie('clevertap_id', ct_id, '.bajajfinserv.in'); } } function setupClevertapNotifications() { if (typeof clevertap !== 'undefined' && Notification.permission === "granted") { clevertap.notifications.push({ titleText: "Would you like to receive Push Notifications?", bodyText: "We promise to only send you relevant content and give you updates on your transactions", okButtonText: "Sign me up!", skipDialog: "true", rejectButtonText: "No thanks", okButtonColor: "#F28046", askAgainTimeInSeconds: 5, serviceWorkerPath: "/service-worker.js" }); } } // Campaign Attribution function initializeCampaignTracking() { let campaignUtmSource = 'organic_bfl'; if (window.location.href.toString().includes('/service-guides')) { campaignUtmSource = 'organic_myaccount'; } const campaign = { utm_medium: getUrlValue('utm_medium') || 'bfl', utm_campaign: getUrlValue('utm_campaign') || 'NA', utm_keyword: getUrlValue('utm_keyword') || 'NA', utm_source: getUrlValue('utm_source') || campaignUtmSource, utm_content: getUrlValue('utm_content') || 'NA' }; setCookie('campaignCookienew', JSON.stringify(campaign), '.bajajfinserv.in'); setCookie('campaignCookie', JSON.stringify(campaign), '.bajajfinserv.in'); pushCampaignToDataLayer(campaign); } function getUrlValue(param) { param = param.replace(/[\\[]/, "\\\\[").replace(/[\\]]/, "\\\\]"); const regex = new RegExp("[\\\\?&]" + param + "=([^&#]*)"); const results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\\+/g, " ")); } function pushCampaignToDataLayer(campaign) { window.dataLayer = window.dataLayer || []; dataLayer.push({ 'event': 'utm_campaign_stamping', 'page_url': document.location.pathname, 'utm_source': campaign.utm_source, 'utm_medium': campaign.utm_medium, 'utm_campaign': campaign.utm_campaign, 'utm_content': campaign.utm_content, 'utm_keyword': campaign.utm_keyword }); } // Decibel Integration function initializeDecibel() { const script = document.createElement('script'); script.type = 'text/javascript'; script.innerHTML = [ 'const accountId = 14099;', 'var propertyId = "";', 'if (window.location.hostname === "www.bajajfinserv.in") {', ' propertyId = 992937;', '} else if (window.location.hostname === "cont-sites.bajajfinserv.in") {', ' propertyId = 1143569;', '}', '(function(d,e,c,i,b,el,it) {', ' d._da_=d._da_||[];_da_.oldErr=d.onerror;_da_.err=[];', ' d.onerror=function(){_da_.err.push(arguments);_da_.oldErr&&_da_.oldErr.apply(d,Array.prototype.slice.call(arguments));};', ' d.DecibelInsight=b;d[b]=d[b]||function(){(d[b].q=d[b].q||[]).push(arguments);};', ' el=e.createElement(c),it=e.getElementsByTagName(c)[0];el.async=1;el.src=i;it.parentNode.insertBefore(el,it);', '})(window,document,"script","https://cdn.decibelinsight.net/i/" + accountId + "/" + propertyId + "/di.js","decibelInsight");' ].join('\n'); document.head.appendChild(script); // Send GA Client ID to Decibel if (typeof decibelInsight !== 'undefined') { const gaClientId = getCookie('_ga'); if (gaClientId) { decibelInsight("sendCustomDimension", "GA_ID", gaClientId); } // Send Adobe Target Experiment data const atExp = localStorage.getItem('AT_Exp'); if (atExp) { decibelInsight("sendCustomDimension", "AT_Variant", atExp); } } } // Adobe Integration function initializeAdobeTarget() { if (typeof adobe !== 'undefined' && typeof adobe.target !== 'undefined') { adobe.target.getOffer({ mbox: "target-click", params: { "clicked_buy_online": "true", "profile.click_buy_online_insights": "true" }, success: function (offer) { adobe.target.applyOffer({ mbox: "target-click", offer: offer }); }, error: function (status, error) { } }); } } // Enhanced Event Tracking function trackCustomEvent(eventData) { if (typeof clevertap !== 'undefined') { clevertap.event.push("click", { event_type: eventData.eventType || "form_event", custom_event: eventData.customEvent || "form_event", component: eventData.component, element: eventData.element, page_url: window.location.href, destination_url: eventData.destinationUrl, section_title: eventData.sectionTitle, cta_text: eventData.ctaText, tab_position: eventData.tabPosition, sub_section: eventData.subSection, page_type: getPageType(), product_name: getProductName(), product_category: getProductCategory(), customer_tag: getCustomerTag(), customer_id: getCustomerId(), journey_tag: eventData.journeyTag, stage_tag: eventData.stageTag, application_id: eventData.applicationId, iswebview: isWebView() }); } } // User Profile Management function updateUserProfile(profileData) { if (typeof clevertap !== 'undefined') { clevertap.profile.push({ "Site": { ...profileData, "Timestamp": new Date() } }); } } // Metadata Functions function getPageType() { const metaTag = document.querySelector('meta[name="tag-1"]'); return metaTag ? metaTag.content : 'NA'; } function getProductName() { const metaTag = document.querySelector('meta[name="tag-3"]'); return metaTag ? metaTag.content : 'NA'; } function getProductCategory() { const metaTag = document.querySelector('meta[name="tag-2"]'); return metaTag ? metaTag.content : 'NA'; } function getCustomerTag() { return localStorage.getItem('ssoCustType') || 'NA'; } function getCustomerId() { return localStorage.getItem('custId') || 'NA'; } function isWebView() { return typeof isWebView !== 'undefined' ? isWebView : false; } // GA4 Ecommerce Tracking function trackEcommercePurchase(transactionData) { window.dataLayer = window.dataLayer || []; dataLayer.push({ event: 'purchase', ecommerce: { transaction_id: transactionData.transactionId, affiliation: transactionData.affiliation || 'Online Store', value: transactionData.value, tax: transactionData.tax || 0, shipping: transactionData.shipping || 0, currency: transactionData.currency || 'INR', items: transactionData.items || [] } }); } // Popup Management function handlePopupClose() { try { const parentClassSelector = document.querySelector("#wzrkImageOnlyDiv"); if (!parentClassSelector) { return; } const popupElement = document.querySelector("#wzrkImageOnlyDiv > ct-web-popup-imageonly"); if (!popupElement || !popupElement.shadowRoot) { return; } const overlay = popupElement.shadowRoot.querySelector("div > div.opacity"); if (!overlay) { return; } overlay.addEventListener('click', function () { parentClassSelector.style.display = 'none'; popupElement.remove(); }); } catch (err) { return; } } // Medallia Integration function initializeMedallia(environment) { const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; if (environment === 'production') { script.src = 'https://resources.digital-cloud-sin1.medallia.com/wdcsin1/42372/onsite/embed.js'; } else if (environment === 'development') { script.src = 'https://resources.digital-cloud-sin1.medallia.com/wdcsin1/42372/onsite/embed.js'; } document.head.appendChild(script); } // EMI Card Identity Management function setEmiCardIdentity(mobileNumber) { if (typeof clevertap !== 'undefined' && mobileNumber) { const phoneNumber = '+91' + mobileNumber; if (phoneNumber.length === 13) { clevertap.onUserLogin.push({ "Site": { "Identity": phoneNumber, "Phone": phoneNumber, "Timestamp": new Date() } }); // Push event to dataLayer window.dataLayer = window.dataLayer || []; window.dataLayer.push({ "event": "button_click", "component": "login_popup", "element": "login_success", "customer_id": getCustomerId(), "customer_tag": getCustomerTag() }); } } } // Pipestream GA4 Integration function initializePipestreamGA4() { try { XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function (method, url) { if (url.indexOf("https://run-server-side-tagging-t3s332nvca-el.a.run.app") !== -1) { this._originalURL = url; this._originalMethod = method; const modifiedUrl = url.replace( 'https://run-server-side-tagging-t3s332nvca-el.a.run.app', "https://pubqueue-bajaj-dot-bajaj-finserv-pipestream.el.r.appspot.com" ); this._modifiedUrl = modifiedUrl; } this.realOpen(method, url); }; XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function (data) { if (this._modifiedUrl !== undefined) { if (data) { this._modifiedUrl += (this._modifiedUrl.indexOf('?') === -1 ? '?' : '&') + data; } const modifiedXHR = new XMLHttpRequest(); modifiedXHR.open(this._originalMethod, this._modifiedUrl); modifiedXHR.setRequestHeader('Content-type', 'text/plain'); modifiedXHR.send(data); this.realSend(data); } else { this.realSend(data); } }; } catch (e) { } } // Additional Utility Functions function getClientId() { const gaCookie = getCookie('_ga'); return gaCookie ? gaCookie.slice(6) : null; } function getContentBucket() { const metaTag = document.querySelector('meta[name="tag-4"]'); return metaTag ? metaTag.content : 'NA'; } function getPageDates() { const createdTag = document.querySelector('meta[name="tag-5"]'); const updatedTag = document.querySelector('meta[name="tag-6"]'); return { created: createdTag ? createdTag.content : 'NA', updated: updatedTag ? updatedTag.content : 'NA' }; } function getFormStageName() { const activeStage = document.querySelectorAll('.active.ng-star-inserted')[0]; return activeStage ? activeStage.textContent.trim() : 'NA'; } function getScrollableRatio() { const heightOfPage = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); const heightOfViewport = Math.max( document.documentElement.clientHeight, window.innerHeight ); const ratio = heightOfViewport / heightOfPage; const maximumRatio = 0.25; return ratio < maximumRatio ? 'is_scrollable' : 'non_scrollable'; } // Initialize everything function initialize() { if (!getCookie('tvc_location_details') || !getCookie('tvc_device_details')) { initializeUserDetails(); } initializeClevertap(); setupClevertapNotifications(); initializeCampaignTracking(); // Initialize Decibel initializeDecibel(); // Initialize Adobe Target if (window.location.pathname.includes('/insights/')) { initializeAdobeTarget(); } // Setup customer data in dataLayer window.dataLayer = window.dataLayer || []; dataLayer.push({ 'bfl_cust_id': getCustomerId() }); dataLayer.push({ 'bfl_cust_tag': getCustomerTag() }); // Initialize Medallia based on environment if (window.location.hostname === 'www.bajajfinserv.in') { initializeMedallia('production'); } else if (window.location.hostname.includes('cont-sites.bajajfinserv.in')) { initializeMedallia('development'); } // Initialize Pipestream GA4 initializePipestreamGA4(); // Setup popup close handler if (document.readyState === 'complete') { handlePopupClose(); } else { window.addEventListener('load', handlePopupClose); } } // Execute initialization when DOM is ready window.addEventListener("load", initialize); // Export functions for external use window.tvcGtm = { setCookie, getCookie, initializeUserDetails, initializeClevertap, setupClevertapNotifications, initializeCampaignTracking, trackCustomEvent, updateUserProfile, getPageType, getProductName, getProductCategory, getCustomerTag, getCustomerId, isWebView, trackEcommercePurchase, handlePopupClose, initializeMedallia, setEmiCardIdentity, initializePipestreamGA4, getClientId, getContentBucket, getPageDates, getFormStageName, getScrollableRatio };