




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 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);
				} else {
    				document.addEventListener('DOMContentLoaded', function () {
        				captureLeadFormData(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 params = 'widgetId=12644';

	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(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();
   		});
	}

})();


