




(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
						});
					});
				}
			}
		}
	});

	function getUrlParamValue(url, param){
	
		var paramName = param + "=";
		var paramValue = '';
		
	
		var plen = paramName.length, pos1 = url.indexOf(paramName);
		if(pos1 == -1){
			paramValue = '';
		}
		else{
			var indexOfCheckChar = url.indexOf('&', (pos1+plen));
			
			if(indexOfCheckChar == -1){
				paramValue = url.substring(pos1+plen);
			}
			else{
				paramValue = url.substring((pos1+plen), indexOfCheckChar);
			}
		}
		return paramValue;
		
	}
	
    //Based on the size param, find width and height of the iframe, for Banner widget
    //By default, the size will be 300x250
	function setIframeSize(size, bannerSize){
        if(size){
            if (size == "size_A") {
                val_width = 320;
                val_height = 50;
            } else if (size == "size_B") {
                val_width = 468;
                val_height = 60;
            } else if (size == "size_C") {
                val_width = 728;
                val_height = 90;
            } else {
	            try{
		            if(bannerSize.indexOf("x")> 0){
		            	val_width = bannerSize.substring(0,bannerSize.indexOf("x"));
						val_height = bannerSize.substring(bannerSize.indexOf("x")+1);
		            }
		            else{
			            val_width = 300;
	                	val_height = 250;
		            }
	            }
	            catch(err){
		            val_width = 300;
	                val_height = 250;
	            }
			}
        }
    }
	var _checkVisibilityImpr = function(_iframeWinRef){
		var iframeWinRef = _iframeWinRef;
		return function checkVisibilityImpr(){
			var per = check_visibilty(iframeWinRef);
			try{
				console.log(e);
			}catch(e){}		
			iframeWinRef.contentWindow.postMessage(per, protocol_scheme+"://"+kzhost);		
		};
	};
	var url = location.href;
	var pname= 'kwgoto';
	var cname= 'kwcname';
	var tname= 'kwthirdpartyuid';
	var kzhost = 'ads.kwanzoo.com';
	var wid = '9006';
	var protocol_scheme = 'https';
	var finalUrl = '';
	var isMouseOnOver = "false";
	
  	var isIE = false;
	var ua = navigator.userAgent.toLowerCase(); 	
	if (ua.indexOf( "msie" ) !== -1) {
		isIE = true;
	}
	
	if( protocol_scheme != 'https'){
		protocol_scheme = 'http';
	}
	
    //By default, the size will be 300x250
    var val_width = 300, val_height = 250;
        
    //Get the iframe size in case of banner widget.
    setIframeSize('null', "1x01");
    	
	var kwgotoValue = getUrlParamValue(url, pname);
	var kwcnameValue = getUrlParamValue(url, cname);	
	var kwthirdpartyuidValue = getUrlParamValue(url, tname);
	
	var scripts = document.getElementsByTagName('script');
	var script = scripts[scripts.length - 1];
	var scriptSrc = script.src;
	
	if(kwgotoValue === "" && kwcnameValue === "" && kwthirdpartyuidValue === ""){
		finalUrl = protocol_scheme+'://' + kzhost + '/widget/customized/'+ wid + '/' + kwcnameValue + ((kwgotoValue === '') ? 'load' : kwgotoValue);;
	}
	else if(kwgotoValue !== "" && kwcnameValue === "" && kwthirdpartyuidValue === ""){
		finalUrl = protocol_scheme+'://' + kzhost + '/widget/customized/'+ wid + '/' + ((kwgotoValue === '') ? 'load' : kwgotoValue);	
	}	
	else if(kwgotoValue !== "" && kwcnameValue !== "" && kwthirdpartyuidValue === ""){
		kwcnameValue = kwcnameValue + "/";
		finalUrl = protocol_scheme+'://' + kzhost + '/widget/customized/'+ wid + '/' + kwcnameValue + ((kwgotoValue === '') ? 'load' : kwgotoValue);	
	}
	else if(kwgotoValue !== "" && kwcnameValue !== "" && kwthirdpartyuidValue !== ""){
		finalUrl = protocol_scheme+'://' + kzhost + '/widget/customized/'+ wid + '/' + ((kwgotoValue === '') ? 'load' : kwgotoValue + '/' + kwthirdpartyuidValue);;	
	}
	else if(kwgotoValue !== "" && kwcnameValue === "" && kwthirdpartyuidValue !== ""){
		finalUrl = protocol_scheme+'://' + kzhost + '/widget/customized/'+ wid + '/' + ((kwgotoValue === '') ? 'load' : kwgotoValue + '/' + kwthirdpartyuidValue);;	
	}
	
	if(scriptSrc.indexOf("?") != -1){ //append get parameters of script src to iframe src 
		finalUrl += '?'+ scriptSrc.slice(scriptSrc.indexOf('?') + 1);
	}
	finalUrl = unescape(finalUrl);	
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "kwcWidgetFrame");
	iframe.setAttribute("name", "kwcWidgetFrame");
	iframe.setAttribute("frameborder", "0");
	iframe.setAttribute("scrolling", "no");
	iframe.setAttribute("marginwidth", "0");
	iframe.setAttribute("marginheight", "0");
	iframe.setAttribute("width", val_width);
	iframe.setAttribute("height", val_height);
	iframe.setAttribute("src", finalUrl);
	iframe.frameBorder = 0;
	
    iframe.setAttribute("style", "display:none;");
    
	
	if(kzhost==='ads.kwanzoo.com' && (wid==='6254' || wid==='6341' || wid==='6436' || wid==='9074')){
		iframe.setAttribute("style", "display:none");
	}
	
	if(kzhost==='localhost' && wid==='7377'){
		iframe.setAttribute("style", "display:none");
	}
	
	if(kzhost==='qa.kwanzoo.com' && wid==='8493'){
		iframe.setAttribute("style", "display:none");
	}
	
	//if(window.location.host !== kzhost){ //do this for different host only
		iframe.onload = function (){		
			setTimeout(_checkVisibilityImpr(this), 1000);			
		};
	//}
	
	var enableOnBannerOverlay = "false";
	if(enableOnBannerOverlay !== 'null' && enableOnBannerOverlay ==='true'){
	    iframe.addEventListener('mouseover', function() {
          if(isMouseOnOver =="false"){
           	isMouseOnOver = "true";
		    document.getElementById("overlayFrame").style.display="";
		    document.getElementById("overlayFrameCloseImage").style.display="";
          }
		});
		
		var overlay_iframe = document.createElement("iframe");
		overlay_iframe.setAttribute("id", "overlayFrame");
		overlay_iframe.setAttribute("src", decodeURIComponent(""));
		overlay_iframe.setAttribute("target",  decodeURIComponent(""));
		overlay_iframe.setAttribute("name", "overlayFrame");
		overlay_iframe.setAttribute("frameborder", "0");
		//overlay_iframe.setAttribute("scrolling", "no");
		overlay_iframe.setAttribute("marginwidth", "0");
		overlay_iframe.setAttribute("marginheight", "0");
		overlay_iframe.setAttribute("width",  window.outerWidth/2);
		overlay_iframe.setAttribute("height",  window.outerHeight/2);
		overlay_iframe.frameBorder = 0;
		overlay_iframe.style.position="absolute";
		overlay_iframe.style.display="none";
		var position = getPosition(document.getElementById("kwcWidgetFrame"));
		overlay_iframe.style.top = position.x;
		overlay_iframe.style.left = position.y;
		
		var image = document.createElement('img');
		image.setAttribute("id", "overlayFrameCloseImage");
		image.src="/images/close.jpg";
		image.style.top = position.x;
		image.style.left = position.y;
		image.style.position="absolute";
		image.style.display="none";
		image.addEventListener('click', function() {
         	document.getElementById("overlayFrame").style.display="none";
		    document.getElementById("overlayFrameCloseImage").style.display="none";
		});
	}
	
	// this fix was done coz: one of our customer had uploaded a transparent image which was showing as white background in IE. 
	//the other fix for this is in poll_static_js.jsp where the body (background-color:transparent)
	
	if(isIE){
		//document.getElementById('kwcWidgetFrame').setAttribute('allowTransparency','allowTransparency');
		iframe.setAttribute("allowTransparency", 'allowTransparency');		
	}
	
	/*
	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);
    if (enableOnBannerOverlay !== 'null' && enableOnBannerOverlay === 'true') {
        currScript.parentNode.insertBefore(overlay_iframe, currScript);
        currScript.parentNode.insertBefore(image, currScript);
    }

		
	function getPosition(element) {
   	    var xPosition = 0;
  		var yPosition = 0;
 
  		 while(element) {
      	 	xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
         	yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
         	element = element.offsetParent;
 	  	}
  	 	return { x: xPosition, y: yPosition };
    }
	
	// visibility detector code
	function check_visibilty(iframeId)
	{
		var topWindow = window.top;		
		if(iframeId==null)
			{			
				return -1;
			}
		var myWidth = 0, myHeight = 0;
		if( typeof( topWindow.innerWidth ) == 'number' ) 
		{
			//Non-IE
		    myWidth = topWindow.innerWidth;
		    myHeight = topWindow.innerHeight;
		}	
		else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
		{
		    //IE 6+ in 'standards compliant mode'
		    myWidth = topWindow.document.documentElement.clientWidth;
		    myHeight = topWindow.document.documentElement.clientHeight;
		}else
		{
			myWidth=topWindow.document.body.clientWidth;
			myHeight=topWindow.document.body.clientHeight;
		}	
		//width and height of viewport
		var widthOfWindow=parseInt(myWidth);	
		var heightOfWindow=parseInt(myHeight);
		//x and y co-ordinates of viewport.
		var xOffset=topWindow.pageXOffset;
		var yOffset=topWindow.pageYOffset;		
		
		if(document.body.style.scrollbar3dLightColor!=undefined)
		{		
			xOffset=topWindow.document.documentElement.scrollLeft;
			yOffset=topWindow.document.documentElement.scrollTop;
		}	
		//x and y co-ordinates of element(/iframe).		
		var iframeLeft=iframeId.offsetLeft;
		var iframeTop=iframeId.offsetTop;
		//alert("top="+iframeTop);
		
		//width and height of element(/iframe)
		var iframeWidth=parseInt(iframeId.width);
		var iframeHeight=parseInt(iframeId.height);	
		if(!iframeWidth)
		{		
			iframeWidth=parseInt(iframeId.clientWidth);
			iframeHeight=parseInt(iframeId.clientHeight);
			if(iframeWidth==0 && iframeHeight==0 && document.body.style.scrollbar3dLightColor!=undefined)
			{
				iframeWidth=parseInt(iframeId.offsetWidth);
				iframeHeight=parseInt(iframeId.offsetHeight);
			}
		}		
		
		//For invisible.
		if((xOffset>=iframeLeft+iframeWidth) ||(yOffset>=iframeTop+iframeHeight) || (iframeLeft>=xOffset+widthOfWindow) || (iframeTop>=yOffset+heightOfWindow))
		{	
			return 0;	
		}
		else//For visible
		{
			var x=xOffset;
			var y=yOffset;
			var l=widthOfWindow;
			var h=heightOfWindow;
			var x1=iframeLeft;
			var y1=iframeTop;
			var l1=iframeWidth;
			var h1=iframeHeight;
			var X=0,Y=0,H=0,L=0;
			(x<x1)?X=x1:X=x;
			(y<y1)?Y=y1:Y=y;
			(x+l<x1+l1)?L=x+l:L=x1+l1;
			(y+h<y1+h1)?H=y+h:H=y1+h1;
			L=L-X;
			H=H-Y;			
			var per=((L*H)/(iframeWidth*iframeHeight))*100;
			per=per.toFixed(2);					
			return per;		
		}
	}
})();


