//this nofifies the parent on iframe is ready
$(document).ready(function() {	
	
	enableSendingMessages();
	sendPageNavData();	
	sendPageTitle();
	loadFramesetIfChildpage();
	scrollToTop();
	collapseMenu();
	addPopUpToSVG();
	hideFooter();
	setDeviceType();
});

//listen to message from parent and scrollst to the index marker requested
window.addEventListener("message", function (event) {
	if(event.data === "backToTop") {
		backToTop();
	}

	if (event.data.scrollToAnchor) {	
		const anchor = $("#" + event.data.scrollToAnchor.anchor);
		if(typeof anchor.offset() === "undefined"){
			return;
		}
		
	if($($(anchor)[0]).next('button').hasClass('accordion-button')) {
		$($(anchor)[0]).next('button').click();
	} 
	else if(!$($(anchor)[0]).next('button').hasClass('accordion-button') && $($(anchor)[0]).parents('div.accordion').find('button')) {
		$($(anchor)[0]).parents('div.accordion').find('button').click();
	}
		
	setTimeout(function() {
		$("html,body").scrollTop(anchor.offset().top);
	},500);
	
	}
});

//listen to scrollbar and display footer
var timeout;
$(window).scroll(function() {   
clearTimeout(timeout);  
    timeout = setTimeout(function() {
        if(Math.round($(window).scrollTop() + $(window).height() + 5) >= $(document).height()) {
			parent.postMessage({ "displayFooter": { "fadein": "true" } }, "*");
		} else {
			parent.postMessage({ "displayFooter": { "fadein": "false" } }, "*");
		}
    }, 100);
});

//bind message sending to links to notify parent of clicks
function enableSendingMessages() {	
	$('a.schema-iframe-link').click(function (e) {		
		e.preventDefault();
		const nodeId = retrieveDataSetFieldIEWorkaround(e.currentTarget, "nodeId");		
		var anchorSplit = [];
		
		var url = window.location.href;
		var currentNodeId = url.split('/')[url.split('/').length - 1].split('.')[0];
		
		if(typeof e.currentTarget.href.baseVal !== "undefined"){
			anchorSplit = e.currentTarget.href.baseVal.split("#");
		}
		else if(typeof e.currentTarget.href.split !== "undefined"){
			anchorSplit = e.currentTarget.href.split("#");
		}
		/*if(anchorSplit.length > 1 && anchorSplit[1].length > 0){
			parent.postMessage({ "loadAndSyncByIndex": { "nodeId": nodeId, "anchor": anchorSplit[1] } }, "*");
		}*/
		if(anchorSplit.length > 1 && anchorSplit[1].length > 0){
			if(nodeId.indexOf(currentNodeId) == -1) {
				parent.postMessage({ "loadAndSyncByIndex": { "nodeId": nodeId, "anchor": anchorSplit[1] } }, "*");
			} else {
				var top = document.getElementById(anchorSplit[1]).offsetTop;
				window.scrollTo(0, top);
			}
		} else if(currentNodeId === "search" && nodeId.split("#").length > 1) {
			parent.postMessage({ "loadAndSyncByIndex": { "nodeId": nodeId.split("#")[0], "anchor": nodeId.split("#")[1] } }, "*");
		}
		else{
			parent.postMessage({ "loadAndSync": { "nodeId": nodeId } }, "*");
		}
	});
	$('a.schema-index-link').click(function (e) {
		e.preventDefault();		
		parent.postMessage({ "loadAndSyncByIndex": { "nodeId": retrieveDataSetFieldIEWorkaround(e.currentTarget, "nodeId"), "anchor": retrieveDataSetFieldIEWorkaround(e.currentTarget, "nodeAnchor") } }, "*");
	});
}

//Workaround for IE and data parameters on Callout Hotlinks
function retrieveDataSetFieldIEWorkaround(target, dataField)
{	
	if (typeof(target.dataset) !== "undefined" ) {
		return target.dataset[dataField];
	}

	let dataId = dataField.split(/(?=[A-Z])/);
	let dataName = "data-"+dataId.join("-").toLowerCase();

	return target.attributes.getNamedItem(dataName).nodeValue;
}

function sendPageNavData() {
	let meta = document.head.getElementsByTagName("meta");	
	let prev = meta.namedItem("prev");
	if (!prev)
		prev = "";
	else
		prev = prev.content;
	
	let next = meta.namedItem("next");
	if (!next)
		next = "";
	else
		next = next.content;
		
	parent.postMessage({ "pagewieseNavigation": { "prev": prev,
		"next": next }}, "*");
}

function sendPageTitle() {
	var title = $($(document)[0]).find("p.search-page") ? ($($(document)[0]).find("p.search-page").text() + $($(document)[0]).find("span#search-query").text()) : document.querySelector('h1').innerText;
	var contentTitle = ($("h1.heading").first().text() ? $("h1.heading").first().text() : title);
	parent.postMessage({ "contentTitle": { "title": contentTitle }}, "*");
}

function loadFramesetIfChildpage()
{
	// Check if this page is not already loaded inside an iframe, or that the iframe
	// isn't the one from our index.html:
	if(window.location === window.parent.location || window.parent[0].name !== 'framecontent')
	{
		var filename = document.location.href.split('/').pop();
		var nodeId = filename.substring(0, filename.indexOf('.'));
		
		document.location = "index.html#" + nodeId;
	}
}

function scrollToTop() {
	// When the user scrolls down 20px from the top of the document, show the button
	window.onscroll = function () {
  		scrollFunction();
	};
}

function scrollFunction() {
 	if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
		parent.postMessage({ "topBtn": { "scrollToTop": "true" } }, "*");
  	} else {
		parent.postMessage({ "topBtn": { "scrollToTop": "false" } }, "*");
  	}
}

// When the user clicks on the button, scroll to the top of the document
function backToTop() {
  	document.body.scrollTop = 0;
  	document.documentElement.scrollTop = 0;
}

function collapseMenu() {
	var menuBtn = document.getElementById("menu");
	if(menuBtn) {
		menuBtn.addEventListener("click", function() {
			parent.postMessage({ "collapseMenu": { "toc": "true" } }, "*");
		});
	}
}

function addPopUpToSVG() {
	var modalviewports = $(".modalviewport");
	
	if(modalviewports.length != 0) {
		$(modalviewports).each(function(index, value) { 
			var siblings = $(value).siblings("svg");
			var id = value.id;
			
			if(siblings) {
				siblings.addClass("data-zoomable");
				siblings.attr("onclick","popup(this,'" + id + "')");
			}
		});
	}
}

function hideFooter() {
	var scrollHeight = $(document)[0].body.scrollHeight;
	
	if((scrollHeight > $(window).height()) && ($(window).scrollTop() == 0)) {
		parent.postMessage({ "displayFooter": { "fadein": "false" } }, "*");
	}
}

function setDeviceType() {
	if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i)) {
  		$($(document)[0].body).addClass('mobile');
	} else {
		//$(document)[0].body.addClass('mobile');
	}
}