if (typeof console === "undefined" || typeof console.log === "undefined") {
	console = {log: function() {}};
}
if(typeof __twingleMessageListener !== "function"){
	window.__twingleMessageListener = function(event) {
		if(event.data && event.data.type && event.data.cid) {
			var __twWidgetIframe = document.getElementById("twingleframe-" + event.data.cid);
			if (__twWidgetIframe) {
				switch (event.data.type) {
					case "size":
						__twWidgetIframe.style.height = event.data.value + "px";
						break;
					case "geturl":
						__twWidgetIframe.contentWindow.postMessage({
							"type": "seturl",
							"value": window.location.href,
							"scroll": window.scrollY
						}, "*");
						break;
					case "retriggerScrollHandler":
						if (window.__twingleScrollHandler) window.__twingleScrollHandler(__twWidgetIframe);
						break;
					case "scrollToTop":
						if(window.scrollTo) {
							// in some cases we need some offset, the iframe will tell us
							var offset = event.data.value? event.data.value : 0;
							// scroll 80px more to avoid sticky headers
							offset -= 80;
							var top = window.scrollY + __twWidgetIframe.getBoundingClientRect().top + offset;
							window.scrollTo({
								top: top,
								behavior: "smooth"
							});
						}
						else if(typeof __twWidgetIframe.scrollIntoView !== "undefined") {
							__twWidgetIframe.scrollIntoView(true);
						}
            break;
				}
			}
		}
	}
}
if(typeof __twingleFindGetParameter !== "function"){
	window.__twingleFindGetParameter = function() {
		var result = "",
			tmp = [];
		var items = location.search.substr(1).split("&");
		for (var index = 0; index < items.length; index++) {
			tmp = items[index].split("=");
			if (tmp[0].indexOf("tw_") === 0 || tmp[0] === 'tr'){
				result += tmp[0] + "=" + decodeURIComponent(tmp[1]) + "&"
			}
		}
		return result;
	}
}
if(typeof __twingleGetBrowsersLocale !== "function"){
	window.__twingleGetBrowsersLocale = function() {
		if (navigator["browserLanguage"]) {
			return navigator["browserLanguage"].substr(0, 2).toLowerCase();
		}
		else if (navigator.language) {
			return navigator.language.substr(0, 2).toLowerCase();
		}
	}
}

if(typeof __twingleScrollHandler !== "function"){
	window.__twingleScrollHandler = function(__twIframe) {
		if(__twIframe && __twIframe.contentWindow && __twIframe.contentWindow.postMessage) {
			__twIframe.contentWindow.postMessage({
				"type": "scroll",
				"scrollY": window.scrollY,
				"innerHeight": window.innerHeight,
				"iFrameOffset": __twIframe.getBoundingClientRect().top,
				"iFrameHeight": __twIframe.getBoundingClientRect().height
			}, "*");
		}
	}
}

(function () {
	// check if there is already a wrapper defined
	var __twWidgetWrapper = null;
	var __twContainerScroll = false;

	var __twContainerId = null;
	if(document.currentScript) {
		if(document.currentScript.id) {
			var idmatch = document.currentScript.id.match(/tw-([a-zA-z0-9]+)$/);
			if(idmatch) {
				__twContainerId = idmatch[1];
			}
		}

		if(__twContainerId === null) {
			var matches = document.currentScript.src.match(/\/(_?[a-zA-z0-9]+)$/);
			if (matches) {
				__twContainerId = matches[1];
			}
		}
	}
	else {
		// fallback for browsers that do not support document.currentScript (<=IE11), use the first element
		__twContainerId = document.querySelector('[id^="twingle-public-embed-"]').id.replace("twingle-public-embed-", "");
		__twContainerScroll = document.querySelectorAll('[id^="twingle-public-embed-"]').length > 1;
	}

	// find the wrapper element that we want to use
	if(document.getElementById("twingle-public-embed-" + __twContainerId)) {
		// the wrapper has a unique id or the type set
		__twWidgetWrapper = document.getElementById("twingle-public-embed-" + __twContainerId);
	}

	// start the embedding
	if(!__twWidgetWrapper) {
		// wrapper was not found
		if(console && console.error) {
			console.error("Wrapper not found");
		}
	}
	else {
		// wrapper was found, create iframe and embed it in page

		// css for loading message
		var css = '@keyframes spin {0% { transform: rotate(0deg); }100% { transform: rotate(360deg); }}',
			head = document.head || document.getElementsByTagName('head')[0],
			style = document.createElement('style');

		style.type = 'text/css';
		if (style.styleSheet){
			style.styleSheet.cssText = css;
		} else {
			style.appendChild(document.createTextNode(css));
		}
		head.appendChild(style);

		// embed loading message
		var __twLoading = document.createElement('div');
		__twLoading.id = "twingleLoading-" + __twContainerId;
		var __twLoadingMsg = __twingleGetBrowsersLocale() === "de"? "Gleich geht es weiter ..." : "just one moment ...";
		__twLoading.innerHTML = '<div style="position:absolute;top:0;left:0;width:100%;height:100%;text-align:center;"><span style="display:block;border:16px solid #f3f3f3;border-top:16px solid #666; border-radius: 50%; width: 120px;height: 120px;animation: spin 500ms linear infinite;position: absolute;top: 50%;left: 50%;margin-left: -60px;margin-top: -60px;"></span><div style="font-family:sans-serif;max-width:500px; color:#666; padding:0; margin:auto; position:relative;top:20px;text-align:center;font-size:18px;">' + __twLoadingMsg + '</div></div>';
		__twWidgetWrapper.appendChild(__twLoading);

		// append iframe
		var __twIframe = document.createElement("iframe");
		__twIframe.style.zIndex = "2";
		var overflow = __twContainerScroll? 'auto' : 'hidden';
		__twIframe.setAttribute("style", "width:100%;border:none;overflow:"+overflow+";height:400px;position:relative;");
		__twIframe.scrolling = __twContainerScroll? "yes" : "no";
		__twIframe.id = "twingleframe-" + __twContainerId;
		__twIframe.src = "https://spenden.twingle.de/papilio-ggmbh/allgemeine-spende/tw61a3e192c8b66/widget/CID".replace(/CID/, __twContainerId);
		__twIframe.loading = "lazy";
		__twIframe.allow = "payment";
		__twIframe.title = "Donation\u0020form";

		// show debug message when the widget was loaded
		__twIframe.onload = function() {
			// remove loading message (object still exists)
			if(__twLoading && __twLoading.parentNode) {
				__twLoading.parentNode.removeChild(__twLoading);
			}
		};

		// add some parameter to the iframe URL
		var parameters = __twingleFindGetParameter();
		if(parameters) {
			__twIframe.src += (__twIframe.src.search(/\?/) === -1)? "?" : "&";
			__twIframe.src += parameters;
		}

		// append the iframe
		__twWidgetWrapper.style.position = "relative";
		__twWidgetWrapper.appendChild(__twIframe);

		// attach the listener
		if (window.addEventListener){
			window.addEventListener("message", __twingleMessageListener, false)
			window.addEventListener("scroll", function() {
				__twingleScrollHandler(__twIframe);
			}, false)
		} else {
			window.attachEvent("onmessage", __twingleMessageListener)
			window.attachEvent("onscroll", function () {
				__twingleScrollHandler(__twIframe);
			})
		}
	}
}());
