
var myAlpha;
var myTimer;

function $(tagId) { 
	return document.getElementById(tagId); 
}


function isNarrowWidth() { 
	return (	(document.all)
		?	(	(document.compatMode == 'CSS1Compat')
			 ?	(document.documentElement.clientWidth 	< 800)
			 :	(document.body.clientWidth 				< 800)
			 )
		:	(window.innerWidth 							< 800)
		);
}


function homeLinkClick() { 
	if (isNarrowWidth() == true) { 	openmenu(); 			} 
	else { 							location.href = "/"; 	}
}


function openmenu() { 
	var nav = document.getElementsByTagName("nav")[0];
	if (nav.style.left === "0%") { 
		nav.style.left    = "-100%";
	} else {
		nav.style.opacity = 0.0;
		nav.style.left    = "0%";
		myAlpha = 0;
		myTimer = setInterval("doOpacity(1)", 5);
	}
}


function doOpacity(a) { 
	var nav = document.getElementsByTagName("nav")[0];
	if (a > 0) { 
		myAlpha += 1;
		nav.style.opacity = (myAlpha / 10);
		if (myAlpha >= 10) { 
			clearInterval(myTimer); 
		}
	}
}

// ----------------------------------------------------------

const scrollLmt = 300;
var topTopBtn;

const easingEquations = {
	easeOutSine:    function (pos) { return Math.sin(pos * (Math.PI / 2));  },
	easeInOutSine:  function (pos) { return (-0.5 * (Math.cos(Math.PI * pos) - 1)); },
	easeInOutQuint: function (pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 5); } return 0.5 * (Math.pow((pos - 2), 5) + 2); }
};

window.addEventListener("load",function() {
	if ($("topTopBtn")) { 
		topTopBtn = $("topTopBtn");
		topTopBtn.style.visibility = "hidden";
		topTopBtn.onclick = function() { scrollToY(0, 5000, 'easeInOutSine'); }
		window.onscroll = scrollFunction;
		window.setTimeout(scrollFunction, 1000);
	}
}, false);

function scrollFunction() {
	const scrollY = document.body.scrollTop | document.documentElement.scrollTop;
	const vb = topTopBtn.style.visibility;
	let flag = 0;
	if      ((scrollY >  scrollLmt) && (vb === "hidden")) { flag =  1; } 
	else if ((scrollY <= scrollLmt) && (vb !== "hidden")) { flag = -1; }
	if (flag != 0) { 
		if (flag > 0) { 
			topTopBtn.style.visibility = "visible";
		}
		topTopBtn.classList.remove("show", "hide");
		topTopBtn.classList.toggle((flag > 0) ? "show" : "hide");
		if (flag < 0) { 
			window.setTimeout(function(){ topTopBtn.style.visibility = "hidden"; }, 250); // equal to hide animation
		}
	}
}

function scrollToY(scrollTargetY, speed, easing) {
	const scrollY = window.scrollY || document.documentElement.scrollTop;
	let currentTime = 0;
	const time = Math.max(.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, .8));
	
	+function tick() {
		currentTime += (1 / 60);
		const p = currentTime / time;
		const t = easingEquations[easing](p);
		if (p < 1) {
			requestAnimationFrame(tick);
			window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t));
		} else {
			window.scrollTo(0, scrollTargetY);
		}
	}();
}