// 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 "";
}


// 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('../../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) {
		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('installBut');
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);
});

/*function showInst(){
	let cururl = window.location.href;
	if (strstr(cururl, '/gp/', true)) {
		$('.install').show();
	}
}
setTimeout(showInst, 3000);*/


// Language Auto Change
var blang = navigator.language || navigator.userLanguage;
blang = blang.substr(0, 2);
var curloc = window.location.href;
var letsChange = false;

var langs = ["ar", "es", "fr", "hi", "id", "pl", "pt", "ro", "ru", "tr", "uk", "vi", "zh", "az", "uz", "th", "km", "mn", "ka", "bg", "it", "sq", "gu", "hr", "lo", "fa", "cs", "da", "hu", "fi", "nl", "ko", "ja", "el", "de", "be", "kk", "et", "hy", "bn", "kn"];
langs.forEach(function(elem) {
	if (blang == elem) {letsChange = true;}
});
langs.forEach(function(elem) {
	if (strstr(curloc, "/"+elem+"/")) {letsChange = false;}
});
if (getCookie("langChanged") == 'true') {letsChange = false;}

if (letsChange) {
	var toloc = curloc.replace(".com/", ".com/"+blang+"/");
	setCookie("langChanged", true, 1);
	window.location.href = toloc;
}

// Rate this app
function norate() {
	document.getElementById('popup').style.display = "none";
}
function rateApp() {
	var votes = getCookie('votes');
	var playsToday = getCookie('playsToday');
	var rateshowed = getCookie('rateshowed');
	if ((votes > 1 || playsToday > 4) && rateshowed != 'true') {
		document.getElementById('popup').style.display = "flex";
		setCookie('rateshowed', true, 30);
	}
}

// Load More Games
var loadingGames = false;
var enough = false;
var alreadyLoaded = 0;
function loadGames(start, amount) { //alert('+');
	if (!enough) {  //alert(root);
	$("#loadani").css({"display":"block"});
		loadingGames=true;
		$.ajax({
			url: root+"script/loadGames.php?q="+encodeURIComponent(loadGamesQuery)+"&start="+Math.round(start+alreadyLoaded)+"&amount="+amount,
			success: function(data) {    //alert(data);
				loadingGames=false;
				alreadyLoaded += amount;
				//console.log(alreadyLoaded+' - '+amount);
				if (data=="" || Math.round(alreadyLoaded+onPage) >= gamesTotal) {
					enough=true;
					$("#loadmoregames").css({"display":"none"});
				}
				$("#loadani").css({"display":"none"});
				$("#games").append(data);
			}
		});
	}
}
// Get Element By ID No Error
function getE(elmId) {
	var elem = document.getElementById(elmId);
	if(typeof elem !== 'undefined' && elem !== null) {
		return elem;
	}
}
// Characters Scroll
function scrocha() {
	let menu = document.getElementById("chars");
	let pos = 0;
	//console.log(document.documentElement.scrollTop);
	function ss() {
		if (document.documentElement.scrollTop < 200) {
			if (pos != menu.scrollLeft || pos == 0) {
				pos = menu.scrollLeft;
				menu.scrollLeft += 1;
			}
			else {
				menu.scrollLeft -= 1;
				pos = menu.scrollLeft;
			}
			if (pos == 0) {
			    clearInterval(i);
			    setTimeout(scrocha, 1000);
			}
		}

		//console.log(menu.scrollLeft);
	}
	var i = setInterval(ss, 10);
}
// Remove language, back to English
function ren() {
	console.log(1);
	setCookie('lang', '', 1);
}

// LOAD
try {scrocha();} catch{}
try {rateApp();} catch{} // Rate App Popup