// Service Worker


// COOKIE
function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays*24*60*60*1000));
	var expires = "expires="+ d.toUTCString();
	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
	var name = cname + "=";
	var decodedCookie = decodeURIComponent(document.cookie);
	var ca = decodedCookie.split(';');
	for(var i = 0; i <ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}
// HIDE OVERLAY
function hideOverlay() {
	var overlay = document.getElementById("overlay");
	overlay.innerHTML = '';
	overlay.style.display = 'none';
}
// MY OVERLAY
var countsec = 5;
function countdown(){
	if (countsec != 1){
		countsec -= 1;
		document.getElementById("sec").innerHTML = countsec;
	}
	else {
		document.getElementById("skip2").style.display = "block";
		document.getElementById("skip1").style.display = "none";
		return;
	}
	setTimeout("countdown()",1000);
}

function showw(tit) {
	var overlay = document.getElementById("overlay");
	var overwhite = document.getElementById("overwhite");
	var finlink = document.getElementById("finlink");
	overlay.style.display = 'block';
	overwhite.style.top = '15%';
	finlink.href = root+'game/'+tit;
	countdown();
}
// MESSAGE
function message(mes) {
	$("body").append('<div class=message>'+mes+'</div>');
}
// DROP MENU
function dropMenu(item) {
	if (item.style.visibility != "visible") {
		document.getElementById("dropmenu").style.visibility = "hidden";
		document.getElementById("droplang").style.visibility = "hidden";
		item.style.visibility = "visible";
	}
	else {
		item.style.visibility = "hidden";
	}
}
// Check Inputs
function isEmail(email) {
	var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return re.test(String(email).toLowerCase());
}
function isCommentLength(value) {
	if (value == null || typeof value == 'undefined' ) return false;
	return (value.length > 2 && value.length < 512 && value != "Comment");
}
function isLogin(value) {
	if (value == null || typeof value == 'undefined' ) return false;

	if (value.length > 3 && value.length < 64 && value != "Login") {
		var regex = new RegExp("^[a-zA-Z0-9 ]+$");
		return regex.test(value);
	}
	else return false
}
function isLoginNew(value) {
	if (value.indexOf('User') == -1) {return true;}
	else return false
}
// CONTACTS
function sendContact() {
	var fields = {};

	fields.name = document.getElementById('name').value;
	fields.email = document.getElementById('email').value;
	fields.txt = document.getElementById('txt').value;
	fields.recaptchaResponse = document.getElementById('g-recaptcha-response').value;

	if (!isEmail(fields.email)) {
		message(LANG[0]);
	}
	else if (!isLogin(fields.name)) {
		message(LANG[1]);
	}
	else if (!isCommentLength(fields.txt)) {
		message(LANG[2]);
	}
	else {
		$.ajax({
			url: root+"script/contact.php?name="+fields.name+'&email='+fields.email+'&txt='+fields.txt+'&answer='+fields.answer+'&g-recaptcha-response='+fields.recaptchaResponse,
			success: function(respond) {
				message(respond);
				document.getElementById("contactForm").innerHTML = '<big><p>'+LANG[4]+'</p></big>';
			}
		});
	}

}
// EARN COINS
function earnCoins(amount, goal) {
	var current = Math.floor(document.getElementById("usercoins").innerHTML);
	var now = current;
	function addCoins() {
		if (now != amount+current) {
			now += 1;
			document.getElementById("usercoins").innerHTML = now;
			$("body").append('<div class=coin_moves></div>');
			setTimeout(addCoins, 100);
			var audio = new Audio(root+'images/sound/coin.mp3');
			try {audio.play();} catch {}
		}
		else {
			$('.coin_moves').remove();
			document.getElementById("pop_coins").classList.add('fade');
			setTimeout(function(){$('#pop_coins').remove();}, 3000);
		}
	}
	setTimeout(addCoins, 500);
	$("body").append('<div id=pop_coins><div>'+goal+'</div><p>'+amount+'</p></div>');

	//var iframe = document.getElementById("capthaframe");
	//recaptchaResponse = iframe.contentWindow.document.getElementById('g-recaptcha-response').value;
	//$.ajax({url: root+"script/earnCoins.php?amount="+amount+'&g-recaptcha-response='+recaptchaResponse, success: function(respond) {}});
	$.ajax({url: root+"script/earnCoins.php?amount="+amount, success: function(respond) {}});

    var audio = new Audio('../../images/sound/award.mp3');
	audio.play();
}

// STRSTR Function
function strstr(haystack, needle, bool) {
    var pos = 0;
    haystack += "";
    pos = haystack.indexOf(needle); if (pos == -1) {
        return false;
    } else {
        if (bool) {
            return haystack.substr(0, pos);
        } else {
            return haystack.slice(pos);
        }
    }
}

// INSTALL APP
var installed = getCookie(installed);
//if (installed == '') {installed = isThisDeviceRunningiOS();}
if (installed == '') {installed = false;}

// IF USER IN APP MOSE RIGHT NOW
window.onload = function() {
	if (window.navigator.standAlone || window.fullScreen || ( !window.screenTop && !window.screenY )) {
		setCookie('thisIsApp', true, 1);
		installed = true;
     	setCookie('installed', true, 30);
	}
}
/*window.addEventListener('DOMContentLoaded', function(){
   if (navigator.standalone || window.matchMedia('(display-mode: standalone)').matches || window.matchMedia('(display-mode: fullscreen)').matches || window.matchMedia('(display-mode: minimal-ui)').matches) {
     installed = true;
     setCookie('installed', true, 60);
     setCookie('thisIsApp', true, 60);
    }
});*/

let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
    deferredPrompt = e;
    if (!installed) {
		$('.install').show();
	}
});
const installApp = document.getElementById('installApp');
installApp.addEventListener('click', async () => {
    if (deferredPrompt != undefined) {
        deferredPrompt.prompt();
        const { outcome } = await deferredPrompt.userChoice;
        if (outcome === 'accepted') {
            deferredPrompt = null;
        }
    }
    else {
    	window.location.replace(root);
    }
});
window.addEventListener('appinstalled', async function(e) {
	installApp.style.display = "none";
	setCookie('installed', true, 30);
	// Redirect
	let cururl = window.location.href;
	if (strstr(cururl, '/gp/', true)) {
		window.location.replace(root);
	}
});

// Rate this app
var votes = getCookie('votes');
var playsToday = getCookie('playsToday');
var rateshowed = getCookie('rateshowed');
if ((votes > 1 || playsToday > 2) && rateshowed != 'true') {
	if (!strstr(window.location.href, 'ios.') && !strstr(window.location.href, 'games.')) {
		document.getElementById('popup').style.display = "flex";
		setCookie('rateshowed', true, 10);
	}
}
function norate() {
	document.getElementById('popup').style.display = "none";
}
function rate() {
	if (strstr(window.location.href, 'ios.')) {
		var url = 'https://apps.apple.com/us/app/fynsy/id1667127287';
	}
	else if (strstr(window.location.href, 'app.')) {
		var url = 'https://play.google.com/store/apps/details?id=com.fynsy.app';
	}
	//else if (strstr(window.location.href, 'games.')) {
		//var url = 'https://play.google.com/store/apps/details?id=com.fynsy.app';
	//}
	norate();
	window.open(url, '_blank').focus();
}


function t() {
	setCookie('iamtest', true, 30);
	let cururl = window.location.href;
	if (strstr(cururl, '/gp/', true)) {
		alert(window.location.href);
	}
}
