




var isAccountLevelIntelligenceEnabled = "false";
var fScriptId = "";
var eUserId = "1383387";
var eKzFpc = "d0ff331f9aa09af6a0b21a33388ac10d";
function captureLeadFormData(serverLocation, loginUserId, puid) {
  const capture = function() {
    let isValidEmail = function(email) {
      const re = /\S+@\S+\.\S+/;
      return re.test(email);
    }

    let sendLeadFormData = function(encodedEmail) {      
      var baseUrl = ("qa.kwanzoo.com" == serverLocation ? "https://kzapi-qa.kwanzoo.com" : "https://api.kwanzoo.com")
      const url = baseUrl + "/capture-lead-form-data/" + loginUserId + "-" + puid + "?email=" + encodedEmail;
      fetch(url)
      .then(function(response) {
        //console.log(response);
      })
      .catch(function(error) {
      	console.log(error);
      });
    }

    let readEmail = function() {
      const emailValue = this.value;
      if (isValidEmail(emailValue)) {
        const encodedEmail = btoa(emailValue);
        sendLeadFormData(encodedEmail);
      }
    }
    // get the email field
    document.querySelectorAll('input[type="text"], input[type="email"]')
    	.forEach(inputField => {
      		inputField.addEventListener('change', readEmail);
    	});
  }

  if (document.readyState === 'complete') {
    capture();
  } else {
    document.addEventListener("readystatechange", (event) => {
      if (event.target.readyState === "complete") {
        capture();
      }
    });
  }
}
function initializeDelivr(serverLocation, loginUserId, fpc) {
    if (document.querySelector('script[data-delivr-ai="true"]')) {
      console.log("Delivr AI script already added, skipping...");
      return;
    }
  
    // Load the DelivrSDK script
    var script = document.createElement('script');
    var pixelUrl =
      serverLocation == "qa.kwanzoo.com"
        ? "https://cdn.delivr.ai/pixels/3b3ec6f2-eedf-436a-9cf7-a238ffd6d0e2/p.js"
        : "https://cdn.delivr.ai/pixels/8beb0260-f017-42a1-81b3-a9da9e542e7f/p.js";
  
    script.id = "delivr-ai";
    script.src = pixelUrl;
    script.defer = true;
    script.setAttribute('data-auto-init', 'false');
    script.setAttribute('data-delivr-ai', 'true'); // Mark script to avoid duplicates
  
    script.onload = function () {
      // Configure DelivrSDK with all the PUID data
      if (window.DelivrSDK) {
        var staticParams = {
          user_id: fpc,
          customer_id: loginUserId,
        };
  
        window.DelivrSDK.configure({
          eventParams: {
            page_view: staticParams,
            click: staticParams,
          },
        }).init();
        console.log("Delivr AI script configured successfully...");
      }
    };
  
    document.body.appendChild(script);
}
  

(function loadIframe(){

	// Messages from Iframe to Parent window
	window.addEventListener('message', function(event) {
		if("ads.kwanzoo.com" === event.origin.substring(event.origin.indexOf("//") + 2)) {
			const eventId = event.data.eventId;
			const data = event.data.data;
			eventId && console.log(eventId, data);  // do not log ping message

			// google analytics integration code
			if("kwanzoo_message_ga" === eventId) {
				window.dataLayer = window.dataLayer || [];
				window.dataLayer.push(data);
			}
			// drift integration code
			else if("kwanzoo_message_drift" === eventId) {
				if(data.isDriftEnabled && typeof drift != "undefined") {
					drift.on('ready', function() {
						drift.api.setUserAttributes({
							kwanzooId: data.sessionUid
						});
					});
				}
			}
			// kwanzoo fpc
			else if("kwanzoo_fpc" === eventId) {
				// for additional validation on the accuracy of the HEMs 5x5 returning for their side
				if (document.readyState !== 'loading') {
    				captureLeadFormData(data.serverLocation, data.loginUserId, data.puid);
    				if (data.isRequestFromConfiguredPages === "true") initializeDelivr(data.serverLocation, data.loginUserId, data.puid);
				} else {
    				document.addEventListener('DOMContentLoaded', function () {
        				captureLeadFormData(data.serverLocation, data.loginUserId, data.puid);
						if (data.isRequestFromConfiguredPages === "true") initializeDelivr(data.serverLocation, data.loginUserId, data.puid);
   					});
				}
			}
		}
	});
	
	var protocol_scheme = 'https';

	if( protocol_scheme != 'https')
		protocol_scheme = 'http';
	
	var finalUrl = protocol_scheme + '://ads.kwanzoo.com/wvt-iframe/load';
	
	function getCookieValue(cookieName){
		var cookieValArr = document.cookie.match(cookieName + "=([^;]*)");
		var value = "";
		if(cookieValArr) value = cookieValArr[1];
		return  value;
	}
	
	function extractToken(str) {
	  const keyValuePairs = str.split("&");
	  for (const pair of keyValuePairs) {
	    const [key, value] = pair.split(":");
	    if (key.toLowerCase() === "token") {
	      return value;
	    }
	  }
	  return str;
	}

	<!-- Marketing Automation Platform (MAP) cookie integration -->

	var marketoCookieName = "";
	var pardotCookieName = "";
	var hubspotCookieName = "";
	var activeCampaignCookieName = "";
	var zohoCookieName = "";
	var rawParams = '';
	var customParams = rawParams ? JSON.parse(rawParams) : "";	

	var params = 'widgetId=12816';

	if(marketoCookieName) {
		var mkCookie = getCookieValue(marketoCookieName);
		params += "&marketo=" + extractToken(mkCookie);
	}
	if(pardotCookieName)
		params += "&pardot=" + getCookieValue(pardotCookieName);

	if(hubspotCookieName) 
		params += "&hubspot=" + getCookieValue(hubspotCookieName);
		
	if(activeCampaignCookieName) 
		params += "&active_campaign=" + getCookieValue(activeCampaignCookieName);

	if(zohoCookieName) 
		params += "&zoho=" + getCookieValue(zohoCookieName);
		
	if(customParams) 
		params += "&d=" + encodeURIComponent(JSON.stringify(customParams));
		
	if(params) finalUrl += "?" + params
	
	finalUrl = unescape(finalUrl);

	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "kwcWidgetFrame");
	iframe.setAttribute("name", "kwcWidgetFrame");
	iframe.setAttribute("src", finalUrl);
    iframe.setAttribute("style", "display:none;");
    // From chrome 85 default referrer policy is updated. (KwanzooNextAPI/#502) 
    iframe.setAttribute("referrerpolicy", "no-referrer-when-downgrade");
    
    
	// The browser runs the code in each script tag immediately, before moving forward in the document. 
	// That is, if there are two script tags as in the sample code in the question, 
	// then when the code in the first one runs, the second script will not yet be part of the DOM
	
	var currScript = document.currentScript;
    if (!currScript) {
        var all_scripts = document.getElementsByTagName("script");
        currScript = all_scripts[all_scripts.length - 1];
    }
    currScript.parentNode.insertBefore(iframe, currScript);
	iframe.contentWindow.KZ_REF_URL = window.location.href;

	function validationTag() { 
    	console.log("Calling trovo metrics endpoint thr script tag");
	    var av = document.createElement('script');
	    av.src = 'https://a.usbrowserspeed.com/metrics.js?pid=b92811d1223bc439179cdad26908fb731d6efd5a5e78bcec5d89bb4590870e06';
		av.type = 'text/javascript';
	   	document.body.appendChild(av);
	   	console.log("Finished trovo metrics endpoint call...");
	}
	
	// for additional validation on the accuracy of the HEMs 5x5 returning for their side
	if (document.readyState !== 'loading') {
    	validationTag();
	} else {
    	document.addEventListener('DOMContentLoaded', function () {
        	validationTag();
   		});
	}

})();
if (isAccountLevelIntelligenceEnabled === "true") {
	console.log("Executing Factors AI script...");
	window.faitracker = window.faitracker
			|| function() {
				this.q = [];
				var t = new CustomEvent("FAITRACKER_QUEUED_EVENT");
				return this.init = function(t, e, a) {
					this.TOKEN = t, this.INIT_PARAMS = e,
							this.INIT_CALLBACK = a, window
									.dispatchEvent(new CustomEvent(
											"FAITRACKER_INIT_EVENT"))
				}, this.call = function() {
					var e = {
						k : "",
						a : []
					};
					if (arguments && arguments.length >= 1) {
						for (var a = 1; a < arguments.length; a++)
							e.a.push(arguments[a]);
						e.k = arguments[0]
					}
					this.q.push(e), window.dispatchEvent(t)
				}, this.message = function() {
					window.addEventListener("message", function(t) {
						"faitracker" === t.data.origin
								&& this.call("message", t.data.type,
										t.data.message)
					})
				}, this.message(), this.init(
						fScriptId, {
							host : "https://api.factors.ai"
						}), this
			}(), function() {
		var t = document.createElement("script");
		t.type = "text/javascript",
				t.src = "https://app.factors.ai/assets/factors.js",
				t.async = !0,
				(d = document.getElementsByTagName("script")[0]).parentNode
						.insertBefore(t, d)
	}();
	console.log("sending custom data to Factors AI script...");
	faitracker.call('track', 'kwanzoo_data', { "kwanzoo_dummy": "dummyValue - Factors", "kwanzoo_user_id": eUserId, "kwanzoo_fpc": eKzFpc })
	faitracker.call('addUserProperties', { "kwanzoo_dummy": "dummyValue - Factors", "kwanzoo_user_id": eUserId, "kwanzoo_fpc": eKzFpc })
	console.log("Finished Factors AI script execution...");
}
