// Disable preloader mandotory
setInterval(function(){document.getElementById("preloader").style.display = "none";}, 5000);

// GLOBAL
var pressed = false;
var genres = getCookie('genres');
if (genres != '') {genres = genres.split(',');} else {genres = Array();}
var sound = getCookie('sound');

// COOKIE
function setCookie(cname, cvalue, exdays, db=true) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays*24*60*60*1000));
	var expires = "expires="+ d.toUTCString();
	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
	// Write cookie to DB
	if (db) {
		$.ajax({ 
			url: root+"script/setCookie.php?cookie="+cname+"&value="+cvalue,
			success: function(data) {
				//console.log(data);
			}
		});
	}
}
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 "";
}

// BUY
const PAYMENT_METHOD = "https://play.google.com/billing";
async function buy(product_id, product_type, domain, user_id) {
	// Change product it for the one in input
	var product_id_input = document.getElementById('jsproduct').value;
	if (product_id_input) {product_id = product_id_input;}
	
	window.product_id = product_id;
	window.product_type = product_type;
	window.domain = domain;
	window.user_id = user_id;
	
	if (window.getDigitalGoodsService) {
		const service = await window.getDigitalGoodsService(PAYMENT_METHOD);
		if (service) {
			//console.log(await service.getDetails([product_id]));
			const itemDetails = await service.getDetails([product_id]);

			for (const item of itemDetails) {
				//displayItem(item.title, item.description, item.price);
	
				const paymentMethods = [{
					supportedMethods: PAYMENT_METHOD,
					data: {
						sku : item.itemId,
					}
				}];

				const request = new PaymentRequest(paymentMethods);

				// Call
				request
				.show()
				.then(handlePaymentResponse)
				.catch(function (e) {
					//setTimeout(function(){window.location.reload(1);}, 500); // Reload Page in 1 seconds
					console.log(e);
					window.location.href = root+'script/stripe.php?product_id='+product_id+'&product_type='+product_type+'&user_id='+user_id+'&maindo='+domain;
				});

			}
		}
	}
	else {
		window.location.href = root+'script/stripe.php?product_id='+product_id+'&product_type='+product_type+'&user_id='+user_id+'&maindo='+domain;
		console.log('Available only in Android APP');
	}
}
function handlePaymentResponse(response) {
	window.setTimeout(function () {
	  response
		.complete('success')
		.then(function () {
		  const {purchaseToken} = response.details;

		  	$.ajax({
				url: root+"script/buy.php?token="+purchaseToken+"&product_id="+window.product_id+"&product_type="+window.product_type,
				success: function(respond) {
					butUnload();
					console.log(respond);
					if (strstr(respond, 'SUCCESS')) {
						setCookie('sale50', 1, 999999999);
						setCookie('sale80', 1, 999999999);
						window.location.href = 'https://'+domain+'/success';
						//reload();
					}
				}
			});

		})
		.catch(function (e) {
			console.log(e.message);
			console.log(JSON.stringify(response, undefined, 2));
			window.location.href = root+'script/stripe.php?product_id='+product_id;
		})
	}, 500);
}
async function getDetails(sku) {
	try {
	  if (window.getDigitalGoodsService) {
		service = await window.getDigitalGoodsService(PAYMENT_METHOD);
		details = await service.getDetails([sku]);
		console.log(JSON.stringify(details, null, 2));
	  } else {
		console.log("window doesn't have getDigitalGoodsService.");

	  }
	} catch (error) {
		console.log(error);
	}
  }

// Cancel Subscription
function cancelSubscription(mode) {
	if (mode == 0) { // Initialize deletion
		$.ajax({
			url: root+"script/stripe_cancel.php?mode="+mode,
			success: function(data) {
				//console.log(data);
				$("body").append(data);
			}
		});
	}
	else {
		$.ajax({
			url: root+"script/stripe_cancel.php?mode="+mode,
			success: function(response) {
				alert(response);
				reload();
			},
			error: function(error) {
				console.error('Error: ', error);
			}
		});
	}
}
// Update URL parametr
function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
        tempArray = additionalURL.split("&");
        for (var i=0; i<tempArray.length; i++){
            if(tempArray[i].split('=')[0] != param){
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    }

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}
// Mobile check
window.mobileCheck = function() {
  let check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
};
// STRSTR Function
function strstr(haystack, needle, bool) {
	haystack = haystack.toLowerCase();
	needle = needle.toLowerCase();

    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);
        }
    }
}
// Rand function
function rand(min, max) {
    return Math.random() * (max - min) + min;
}

// RELOAD
function reload(main=false) {
	if (main) {
		window.location.href = root;
	}
	else {
		window.location.reload(true);
	}
}
// Main menu
function mainMenu() {
	window.location = root;
	let main = document.getElementById('blackscreen');
	if (main.style.display != 'block') {
		main.style.display = 'block';
	}
	else {
		main.style.display = 'none';
	}
}

function back() {
	window.history.go(-1);
}
var audio = new Audio();
function soundPlay(file, mute=false) {
	//console.log(sound);
	if (sound == 1 || mute == false) {
		try {audio.stop();} catch {}
		try {audio.src = root+'files/audio/'+file+'.mp3';} catch {}
		try {audio.play();} catch {}
	}
}
// Lesson result sound
function resultSound(emotion) {
	if (emotion == 'happy') {
		soundPlay('sounds/good', true);
	}
	else {
		soundPlay('sounds/bad', true);
	}
}
function speache(el, num=10) {
	var ss = document.getElementById("speacheState").value;
	if (ss < num) {
		var snext = Number(ss)+1;
		document.getElementById("speacheState").value = snext;
		var pcur = document.getElementById("sp"+ss);
		var pnext = document.getElementById("sp"+snext);
		var cat = document.getElementById("jscat");
		pcur.classList.add('hide');
		pnext.classList.remove('hide');
		var sn = snext;
		// Donate
		if (num == 3) {
			if(ss==1) {sn = 8;}else if(ss==2) {sn = 10;} 
			var dop=10;
			setCookie('donate', 1, 7);
		} 
		else {var dop=0;} // Speache 2 Donate Sound change

		cat.classList.remove('cat-'+ss);
		cat.classList.add('cat-'+sn);
		soundPlay('speache/'+user_lang+'/'+Number(snext+dop));
		el.classList.add('hide2');

		audio.addEventListener('ended', function(){el.classList.remove('hide2');});

		audio.onerror = function() {
			butUnload();
			setTimeout(function(){el.classList.remove('hide2')}, 3000);
		}
	}
	else {
		if (num==3) {
			document.getElementById('jsdonat1').remove();
			document.getElementById('jsdonat2').classList.remove('hide');
		}
		else {reload();}	
	}
}
function donateActivate(el) {
	soundPlay('speache/'+user_lang+'/'+11);
	document.getElementById('jspeachedon').classList.remove('hide');
	el.remove();
}

function find(elem) {
	var q = document.getElementById(elem).value;
	if (!strstr(q, '...') && q != '' && q.length > 1) {
		window.location.href = root+'search/'+q;
	}
}

function closeWords() {
	var els = document.getElementsByClassName("wordadd");
	Array.prototype.forEach.call(els, function(el) {
		el.remove();
	});
}
// Word card in songs
var prevElem = '';
function wordSong(word, elem, artist_id, song_id, own=true) {
	if (!elem) {elem = prevElem;}
	else {prevElem = elem;}
	closeWords();
	// Elem position
	var ww = $(window).width()
	var ex = elem.getBoundingClientRect().left + window.scrollX;
	var ex2 = elem.getBoundingClientRect().right + window.scrollX;
	var ey = elem.getBoundingClientRect().top + window.scrollY;
	var ew = elem.offsetWidth;
	// Loading
	$("body").append('<div id="load" class="loader_small"></div>');
	var loading = document.getElementById('load');
	loading.style.top = ey+'px';
	loading.style.left = ex+(ew/2)+'px';

	$.ajax({
		url: root+"script/wordSong.php?word="+word+"&artist_id="+artist_id+"&song_id="+song_id,
		success: function(data) {
			loading.remove();
			
			$("body").append(data);
			//console.log(data);
			var w = document.getElementById("wordadd");
			w.style.top = ey+'px';

			if (!own) {document.getElementById('jsown').remove();w.style.zIndex = "6";} // Disable own translation

			if (ex2<ww/2) {
				w.style.left = ex+ew+'px';
			}
			else {
				w.style.left = ex-w.offsetWidth+'px';
				if (parseInt(w.style.left) < 0) {
					w.style.left = '0px';
				}
			}
			//console.log(elem);
		}
	});
}
// Select translation variant
function selectVar(el) {
	var els = document.getElementsByClassName("var");
	Array.prototype.forEach.call(els, function(el) {
		el.classList.remove('wact');
	});

	el.classList.add('wact');
	document.getElementById('varschoice').value = el.innerHTML;
}
// Show all translation variants
function showAllVars(el) {
	var vars = document.getElementById('vars');
	vars.style.maxHeight = "none";
	el.style.display = "none";
}
// Add word to mywords
function wordAdd(word_id, word) {
	var myowntrans = document.getElementById('mytransinp').value;
	if (myowntrans == '') {var trans = document.getElementById('varschoice').value;}
	else {var trans = myowntrans;}
	if (trans == '' || trans == '-') {return;}
	
	var artist_id = document.getElementById('artist_id').value;
	var song_id = document.getElementById('song_id').value;

	$.ajax({
		url: root+"script/wordAdd.php?word_id="+word_id+"&trans="+trans+"&artist_id="+artist_id+"&song_id="+song_id,
		success: function(data) {
			closeWords();
			var allwords = document.querySelectorAll('a');
			for (i=0; i<allwords.length; i++) {
				if (strstr(allwords[i].innerHTML, word) && allwords[i].innerHTML.length-word.length <= 2) {
					allwords[i].classList.add('act');
					allwords[i].setAttribute('onclick', 'wordCard('+word_id+')');
				}
			}
			if (strstr(window.location.href, '/mywords')) {reload();}
			console.log(data);
		}
	});
}
// Word card
function wordCard(word_id) {
	try{wordCardClose()}catch{}
	// Loader
	$("body").append('<div id="load" class="overlay"><div class="loader"></div></div>');
	$.ajax({
		url: root+"script/wordCard.php?word_id="+word_id,
		success: function(data) {
			document.getElementById('load').remove();
			$("body").append(data);
			//console.log(data);
		}
	});
}
// Close word card
function wordCardClose() {
	document.getElementById('olwordcard').remove();
}
// Delete word
function wordDelete(word_id, action, decide=false) {
	if (action == 0) {
		$.ajax({
			url: root+"script/wordDelete.php?word_id="+word_id+"&action=0",
			success: function(data) {
				$("body").append(data);
			}
		});
	}
	else if (action == 1) {
		if (decide) {
			$.ajax({
				url: root+"script/wordDelete.php?word_id="+word_id+"&action=1",
				success: function(data) {
					document.getElementById('olprompt').remove();
					try{wordCardClose()}catch{}
					try{document.getElementById('w-'+word_id).remove()}catch{}
					try { // In Song mode, remove highlighted words
						var allwords = document.querySelectorAll('a');
						for (i=0; i<allwords.length; i++) {
							if (strstr(allwords[i].innerHTML, data)) {
								allwords[i].classList.remove('act');
								allwords[i].setAttribute('onclick', 'return');
							}
						}
					}catch{}
					//reload();
				}
			});
		}
		else {
			document.getElementById('olprompt').remove();
		}
	}
}
// Reset word
function wordReset(word_id, action, decide=false) {
	if (action == 0) {
		$.ajax({
			url: root+"script/wordReset.php?word_id="+word_id+"&action=0",
			success: function(data) {
				$("body").append(data);
			}
		});
	}
	else if (action == 1) {
		if (decide) {
			$.ajax({
				url: root+"script/wordReset.php?word_id="+word_id+"&action=1",
				success: function(data) {
					var progs = document.getElementsByClassName('jsprog'+word_id);
					Array.prototype.forEach.call(progs, function(el) {
						el.classList.add('pbred');
						el.children[0].style.width = '0px';
					});
				}
			});
		}
		document.getElementById('olprompt').remove();
	}
}
// Filter words
function wordsFilter(but, param) {
	var els = document.getElementsByClassName("myword");

	// Buttons
	var buts = document.getElementsByClassName("button_pale");
	Array.prototype.forEach.call(buts, function(el) {
		el.classList.remove('bpa');
	});
	but.classList.add('bpa');

	if (param == 'learned') {
		Array.prototype.forEach.call(els, function(el) {
			var prog = el.getElementsByClassName('inprog')[0].value;
			if (prog != 100) {
				el.style.display = "none";
			}
			else {
				el.style.display = "flex";
			}
		});	
	}
	else if (param == 'tolearn') {
		Array.prototype.forEach.call(els, function(el) {
			var prog = el.getElementsByClassName('inprog')[0].value;
			if (prog == 100) {
				el.style.display = "none";
			}
			else {
				el.style.display = "flex";
			}
		});	
	}
	else {
		Array.prototype.forEach.call(els, function(el) {
			el.style.display = "flex";
		});	
	}
}
// Find words
function wordsFind(el) {
	var find = el.value;
	var els = document.getElementsByClassName("myword");

	Array.prototype.forEach.call(els, function(el) {
		var word = el.getElementsByClassName('inword')[0].value;
		if (strstr(word.toLowerCase(), find.toLowerCase())) {
			el.style.display = "flex";
		}
		else {
			el.style.display = "none";
		}
		
	});
}
// Find songs
function songsFind(el) {
	var find = el.value;
	var els = document.getElementsByClassName("artsong");

	Array.prototype.forEach.call(els, function(el) {
		var word = el.getElementsByClassName('inword')[0].value;
		if (strstr(word.toLowerCase(), find.toLowerCase())) {
			el.style.display = "flex";
		}
		else {
			el.style.display = "none";
		}
		
	});
}
// Text to Speach
var voices = window.speechSynthesis.getVoices();
window.speechSynthesis.onvoiceschanged = function() {voices = window.speechSynthesis.getVoices();};
var lastWordSpoken = '';

function speak(word, word_id=false, el='') {

	try{el.classList.add('fadeinout');}catch{}

	let accent = getCookie('accent');
	if (accent == '') {accent = 'us';}
	word=word.toLowerCase();

	//var n = Math.floor(word_id/10000);
	//console.log(word_id+' - '+n);
	//soundPlay('voice/'+accent+'/'+n+'/'+word_id);
	
	soundPlay('synth/'+accent+'/'+word);

	audio.onerror = function() {
		$.ajax({
			url: root+"script/speak.php?word_id="+word_id+"&accent="+accent,
			success: function(data) {
				soundPlay('synth/'+accent+'/'+word);
			}
		});
	}

	/*audio.onerror = function() {
		if ('speechSynthesis' in window) {
			var msg = new SpeechSynthesisUtterance();
			// Accent: 0,1 - US Male | 2,6 - US Female | 8 - UK Male | 7 - UK Female
			if (accent == 'us') {
				for (i=window.voices.length-1; i>=0; i--) {
					if (strstr(window.voices[i].name, 'English') && (strstr(window.voices[i].name, 'US') || strstr(window.voices[i].name, 'United States'))) {
						msg.voice = window.voices[i]; break;
					}
				}  
			}
			else {
				for (i=window.voices.length-1; i>=0; i--) {
					if (strstr(window.voices[i].name, 'English') && strstr(window.voices[i].name, 'UK')) {
						msg.voice = window.voices[i]; break;
					}
				}
			}
			
			if (lastWordSpoken == word) {msg.rate = 0.3;}
			else {msg.rate = 0.8;}
			msg.text = word;
			window.speechSynthesis.cancel();
			window.speechSynthesis.speak(msg);
			lastWordSpoken = word;
		}
	}*/
	//console.log(1);
	// Get all the voices
	//speechSynthesis.getVoices().forEach(function(voice) {
		//console.log(voice.name, voice.default ? voice.default :'');
	//});
}
// Word IMG
function wordImg(el) {
	el.remove();
	document.getElementById('wordimg').style.display = "block";
}

// Cat change emotion 
function catEmotion(emo) {
	var cat = document.getElementById("cat");
	cat.className = '';
	cat.classList.add('cat_'+emo);
}
// Answer
function answer(el, what) {
	if (what) {
		el.classList.add("true");
		document.getElementById('rightAnswer').value = 1;
		catEmotion('happy');
		soundPlay('sounds/right', true);
		var nextBut = document.getElementById('jsbutnext');
		nextBut.classList.remove('hide');
		function next() {nextBut.click();}
		setTimeout(next, 500);
	}
	else if (!what && document.getElementById('rightAnswer').value != 1) {
		el.classList.add("wrong");
		document.getElementById('wrongAnswer').value = 1;
		catEmotion('sad');
		soundPlay('sounds/wrong', true);
	}
}

function answerDone(word_id, el='') {
	try{el.classList.add('butload');}catch{}
	var wrongAnswer = document.getElementById('wrongAnswer').value;
	var rightAnswer = document.getElementById('rightAnswer').value;
	var mode = document.getElementById('mode').value;
	if (!pressed) {
		pressed = true;
		if (mode == 4) { // Mode 4
			var answer = document.getElementById('answerinp');
			var currentWord = document.getElementById('currentWord').value.toLowerCase();
			if (answer.value.toLowerCase().trim() == currentWord) {
				wrongAnswer=0; 
				answer.classList.add('true');
				answer.blur();
				catEmotion('happy');
				soundPlay('sounds/right', true);
			} 
			else {wrongAnswer=1; answer.classList.add('wrong'); catEmotion('sad'); soundPlay('sounds/wrong', true); document.getElementById('jsrightword').innerHTML = currentWord;}
			//console.log(answer.value.toLowerCase()+' == '+document.getElementById('currentWord').value.toLowerCase());
			rightAnswer=1;
		}
		if (rightAnswer != 0) {
			$.ajax({
				url: root+"script/learnAnswer.php?word_id="+word_id+"&wrong="+wrongAnswer,
				success: function(data) {
					//console.log(data);
					if (mode==4) {setTimeout(nextQuestion, 500);} else {nextQuestion();}
				}
			});
		}
		
	}
	//console.log(wrongAnswer);
}
function nextQuestion() {
	//let r = rand(0, 999999999);
	//window.location.href = window.location.href.split('?')[0]+r+'?'+window.location.href.split('?')[1];


	$('head').append('<meta http-equiv="refresh" content="0">');

	//window.location.href += '&r='+r;

	if (!strstr(window.location.href, '&r=')) {
		//window.location.href += '&r='+r;
		
	}
	else {
		//window.location.href = window.location.href.split('&r=')[0]+'&r='+r;
	}
}
function learnAgain() {
	$.ajax({
		url: root+"script/learnAgain.php",
		success: function(data) {
			reload();
		}
	});
}
// Mode 4 oninput change
if (strstr(window.location.href, 'mode=4')) {
	var answer = document.getElementById('answerinp');
	function inputHandler() {
		if (answer.value != '') {
			document.getElementById('jsbutnext').classList.remove('hide');
			document.getElementById('rightAnswer').value = 1;
		}
		else {
			document.getElementById('jsbutnext').classList.add('hide');
			document.getElementById('rightAnswer').value = 0;
		}
	}
	if (answer != null) {answer.addEventListener('input', inputHandler);}
}
// Mode 3 game
function letter(letter, el=false) {
	var word = document.getElementById('currentWord').value;
	word = word.toLowerCase();
	letter = letter.toLowerCase();
	var currentLetter = document.getElementById('currentLetter');
	var cl = Number(currentLetter.value)-1;
	var space = document.getElementById('l'+currentLetter.value);
	var letters = word.split('');
	if (!el) {el = document.getElementById(letter);}
	//console.log(el);
	if (letter == letters[cl]) {
		try{space.classList.remove('wrong')}catch{}
		space.classList.add('true');
		space.innerHTML = letter;
		catEmotion('normal');
		document.getElementById('rightAnswer').value = 1;
		el.remove();
		//console.log(cl+' == '+Number(letters.length-1));
		if (cl == Number(letters.length)-1) {
			document.getElementById('jsbutnext').classList.remove('hide');
			catEmotion('happy');
			soundPlay('sounds/right', true);
			var nextBut = document.getElementById('jsbutnext');
			function next() {nextBut.click();}
			setTimeout(next, 500);
		}
		currentLetter.value = Number(currentLetter.value)+1;
		// Set wrong letters to chose beck to normal
		var els = document.getElementsByClassName("letterchoose");
		Array.prototype.forEach.call(els, function(el2) {
			el2.classList.remove('wrong');
		});
	}
	else {
		space.classList.add('wrong');
		document.getElementById('wrongAnswer').value = 1;
		catEmotion('sad');
		soundPlay('sounds/wrong', true);
		el.classList.add('wrong');
	}
}
// XP bar
function xpbar(curPerc, gainedPerc, nextLevelPerc) {
	var bar = document.getElementById('xpbar');
	var barNum = curPerc;
	//console.log(curPerc, gainedPerc);
	var barInterval = setInterval(function () {
		var newPerc = Math.round(Number(barNum)+1);
		//console.log(curPerc+gainedPerc);
		barNum = bar.style.width.replace('%', '');
		if (barNum <= gainedPerc) {
			bar.style.width = newPerc+'%';
		}
		else if (barNum > 100) { // Next Level
			//console.log('NEW LEVEL');
			barNum = 0;
			bar.style.width = '0%';
			gainedPerc = nextLevelPerc;
			//console.log(barNum <= gainedPerc);
			document.getElementById('star').innerHTML = Number(document.getElementById('star').innerHTML)+1;
			document.getElementById('star').classList.add('wow');
			soundPlay('sounds/levelup', true);
		}
		else {
			//console.log('clearInterval');
			clearInterval(barInterval);
		}
		
	}, 10);
}
// Finish song
function finishSong(state) {
	if (state == 0) {
		document.getElementById('songdoneprompt').classList.remove('hide');
	}
	else if (state == 2) {
		document.getElementById('songdoneprompt').classList.add('hide');
	}
	else {
		window.location.href = window.location.href.replace('/song/', '/songdone/')
	}
}
// Change translation variants
function varsChange(state, el, word_id=0) {
	var curvar = document.getElementById('curvar');
	var varschange = document.getElementById('varschange');
	if (state == 0) {
		curvar.style.display = 'none';
		varschange.style.display = 'block';
		el.style.display = 'none';
	}
	else {
		var myowntrans = document.getElementById('mytransinp').value;
		if (myowntrans == '') {var trans = el.innerHTML;}
		else {var trans = myowntrans;}
		if (trans == 'OK') {return;}
	
		$.ajax({
			url: root+"script/wordChange.php?word_id="+word_id+"&trans="+trans,
			success: function(data) {
				curvar.innerHTML = trans;
				curvar.style.display = 'block';
				varschange.style.display = 'none';
				document.getElementById('changa').style.display = 'inline-block';
				document.getElementById('t-'+word_id).innerHTML = trans;
				// Reset activated variants
				var els = document.getElementsByClassName("var");
				Array.prototype.forEach.call(els, function(el2) {
					el2.classList.remove('wact');
				});
				el.classList.add('wact');
			}
		});
	}
}

// My own translation
function myTrans(state, elem) {
	var inp = document.getElementById('mytrans');
	if (state == 0) {
		elem.remove();
		inp.style.display = 'inline-block';
		document.getElementById('mytransinp').focus();
	}
}

// Keyboard operations in Learning mode
if (strstr(window.location.href, '/learn')) {
document.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
	if (key == 'Enter') {
		if (document.getElementById('rightAnswer')) {
			if (document.getElementById('rightAnswer').value == 1) {
				try{answerDone(document.getElementById('wordID').value)}catch{}
			}
		}
		else if (strstr(document.getElementsByClassName('content-800')[0].innerHTML,'<p class="ph1">')) {
			reload();
		}
	}
	else {
		//var reg = /^[a-zA-Z0-9()*_\-!#$%^&*,."\'\][]+$/;
		var keys = Array('Shift','Space','Alt','Control','Meta','CapsLock','Tab','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Backspace','Delete','End','Escape');
		var reg = /^[a-zA-Z-]*$/;
		if (reg.test(key) && !keys.includes(key)) {
			try{letter(key)}catch{}
		}
	}
	//console.log(key);
});
}

// Dark theme / Light theme
function dark(set='') {
	if (set == 'dark') {
		setCookie('dark', 1, 999999999);
		document.getElementById('jsdark').innerHTML = themeDark;
	}
	else if (set == 'light') {
		setCookie('dark', 0, 999999999);
		document.getElementById('jsdark').innerHTML = '';
	}
	else {
		var dark = getCookie('dark');
		if (dark == 1) {
			setCookie('dark', 0, 999999999);
			document.getElementById('jsdark').innerHTML = '';
		}
		else {
			setCookie('dark', 1, 999999999);
			document.getElementById('jsdark').innerHTML = themeDark;
		}
	}
}

// Favorite artist
function favArt(artist_id, el) {
	$.ajax({
		url: root+"script/favArt.php?artist_id="+artist_id,
		success: function(data) {
			if (el.classList[0] == 'heart_big') {
				el.classList.remove('heart_big');
				el.classList.add('heart_big_on');
				document.getElementById('jsfans').innerHTML = Number(document.getElementById('jsfans').innerHTML)+1;
				if (strstr(data, '<script')) {$("body").append(data);} // Achievement
				soundPlay('sounds/like', true);
			}
			else {
				el.classList.remove('heart_big_on');
				el.classList.add('heart_big');
				document.getElementById('jsfans').innerHTML = Number(document.getElementById('jsfans').innerHTML)-1;
			}
			//console.log(el.classList[0]);
		}
	});
}
// Favorite song
function favSong(artist_id, song_id, el) {
	$.ajax({
		url: root+"script/favSong.php?artist_id="+artist_id+"&song_id="+song_id,
		success: function(data) {
			if (el.classList[0] == 'heart') {
				el.classList.remove('heart');
				el.classList.add('heart_on');
				//document.getElementById('jsfans').innerHTML = Number(document.getElementById('jsfans').innerHTML)+1;
				if (strstr(data, '<script')) {$("body").append(data);} // Achievement
				soundPlay('sounds/like', true);
			}
			else {
				el.classList.remove('heart_on');
				el.classList.add('heart');
				//document.getElementById('jsfans').innerHTML = Number(document.getElementById('jsfans').innerHTML)-1;
			}
			//console.log(data);
		}
	});
}

// Showcase scroll
var scra = 0;
var scpace = 500;
function screell(dir) {
    var elem = document.getElementById("slide");
	var slideWidth = elem.getElementsByTagName('div')[0].scrollWidth;
	if (dir == 'left') {
		if (scra > 0) {scra -= scpace;}
		elem.scrollTo({left: scra,behavior: "smooth"});	
	}
	else {
		if (scra+document.body.clientWidth-40 < slideWidth) {scra += scpace;}
		elem.scrollTo({left: scra,behavior: "smooth"});
	}
	//console.log(scra+document.body.clientWidth-40+' < '+slideWidth);
}

// Achievement
var achqueue = [];
function achievement(id) {
	if (id != 0) {
		if(achqueue.indexOf(id) === -1) {achqueue.push(id);}
		if (achqueue[0] == id) {
			$.ajax({
				url: root+"script/achievement.php?id="+id,
				success: function(data) {
					if (strstr(data, 'achievement')) {
						$("body").append(data);
						achqueue.splice(achqueue.indexOf(id), 1);
						soundPlay('sounds/achievement', true);
					}				
				}
			});
		}
	}
	else {
		document.getElementById('achievement').remove();
		if (achqueue.length > 0) {
			achievement(achqueue[0]);
		}
	}
	//console.log(achqueue);
}

// Check inputs
function isEmail(email) {
	//return true;
	//if (email == LANG[0]) {
		//return true;
	//}
	//else {
		email = email.trim(); email = email.trimRight(); // Remove spaces
		email = email.replace(/\s/g, "");
		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 isPass(value) {
	//return true;
	value = value.trim(); value = value.trimRight(); // Remove spaces
	if (value.length >= 6 || value == LANG[1]) {return true;}
	else return false
}

// Start
function start(state) {
	if (state == 1) { // Depricated genres
		document.getElementById('start'+state).classList.add('hide');
		document.getElementById('start2').classList.remove('hide');
	}
	else if (state == 2) {
		
		
		document.getElementById('start1').classList.add('hide');
		document.getElementById('start3').classList.remove('hide');
		butUnload();
	}
	else if (state == 3) {
		var user_name = document.getElementById('jsmyname').value;
		if (user_name == '' || strstr(user_name, '...')) {
			user_name = LANG[2];	
		}
		setCookie('user_name', user_name, 999999999, false);

		var user_email = document.getElementById('jsuseremail').value;
		var user_password = document.getElementById('jspass').value;
		var jsout = document.getElementById('jsout2');

		// Email check
		if (!isEmail(user_email)) {
			jsout.innerHTML = '<p class="pred">'+LANG[3]+'</p>';
			butUnload();
			return;
		}
		else {
			// Password check
			if (!isPass(user_password)) {
				jsout.innerHTML = '<p class="pred">'+LANG[4]+'</p>';
				butUnload();
				return;
			}
		}
		// New user to DB
		$.ajax({
			url: root+"script/userNew.php?user_email="+user_email+"&user_password="+user_password+"&user_name="+user_name,
			success: function(data) {
				console.log(data);
				
				if (strstr(data, 'email_exists')) {
					jsout.innerHTML = '<p class="pred">'+LANG[5]+'</p>';
					butUnload(); 
					return;
				}
				else {
					document.getElementById('start'+state).classList.add('hide');
					//document.getElementById('start4').classList.remove('hide');
					//soundPlay('speache/'+user_lang+'/'+1);
					document.getElementById('jslangicon').remove();
					document.getElementById('start2').classList.remove('hide');
					//setTimeout(function(){reload()}, 100); // Reload Page in 1 second
				}
			}
		});
	}
}
function startHello() {
	setCookie('hello', 1, 999999999);
	document.getElementById('jshellobut').remove();
	document.getElementById('start4').classList.remove('hide');
	soundPlay('speache/'+user_lang+'/'+1);
}
function startBack(current) {
	if (current == 0) {
		document.getElementById('start3').classList.add('hide');
		document.getElementById('start1').classList.remove('hide');
	}
	else {
		var prev = current-1;
		document.getElementById('start'+current).classList.add('hide');
		document.getElementById('start'+prev).classList.remove('hide');
	}
}
function genresSelect(tit, elem) {
	if (Array.from(elem.classList).includes('selected')) {
		elem.classList.remove('selected');
		genres.splice(genres.indexOf(tit), 1);
	}
	else {
		if (genres.length < 10) {
			elem.classList.add('selected');
			genres.push(tit);
		}
	}
	setCookie('genres', genres, 999999999);
	$.ajax({
		url: root+"script/userGenres.php",
		success: function(data) {
			//console.log(data);
		}
	});
	//console.log(genres);
}
function closeStart() {
	try{document.getElementById('start4').remove();} catch{}
	try{document.getElementById('buynoads').remove();} catch{}
	try{document.getElementById('jsov').remove();} catch{}
	setCookie('sale0', 1, 999999999);
	setCookie('sale80', '', 999999999);
	reload(true);
}
function sub(elem, product_id) {
	for (var i=1; i<=3; i++) {
		document.getElementById('jsub'+i).classList.remove('subact');
		document.getElementById('jsub'+i).classList.add('opa70');
	}
	if (!Array.from(elem.classList).includes('subact')) {
		elem.classList.remove('opa70');
		elem.classList.add('subact');
	}
	// Update link for Stripe
	var link = document.getElementById('jspaylink');
	var newlink = updateURLParameter(link.href, 'product_id', product_id);
	link.href = newlink;
	// Update link for Android
	document.getElementById('jsproduct').value = product_id;
	//console.log(document.getElementById('jsproduct').value);
}
function theme(type, elem, mustbedark=false) {
	elem.classList.add('mensel');
	dark(mustbedark);
	if (type == 0) {
		document.getElementById('butdark').classList.remove('mensel');
	}
	else {
		document.getElementById('butlight').classList.remove('mensel');
	}
}
function dificulty(type, elem) {
	elem.classList.add('mensel');
	if (type == 1) {
		document.getElementById('butnormal').classList.remove('mensel');
		document.getElementById('buthard').classList.remove('mensel');
	}
	else if (type == 2) {
		document.getElementById('buteasy').classList.remove('mensel');
		document.getElementById('buthard').classList.remove('mensel');
	}
	else if (type == 3) {
		document.getElementById('buteasy').classList.remove('mensel');
		document.getElementById('butnormal').classList.remove('mensel');
	}
	setCookie('dificulty', type, 999999999, false);
	$.ajax({
		url: root+"script/userEdit.php?mode=dificulty",
		success: function(data) {}
	});
}
function accent(type, elem) {
	elem.classList.add('mensel');
	if (type == 'uk') {
		document.getElementById('jsus').classList.remove('mensel');
	}
	else if (type == 'us') {
		document.getElementById('jsuk').classList.remove('mensel');
	}
	setCookie('accent', type, 999999999, false);
	$.ajax({
		url: root+"script/userEdit.php?mode=accent",
		success: function(data) {
			
		}
	});
}

function settings(state) {
	var el = document.getElementById('settings');
	if (state == 1) {
		el.classList.remove('hide');
	}
	else {
		el.classList.add('hide');
	}
}
// Sound
function soundOnOff(elem, set) {
	sound = getCookie('sound');
	if (set == 0) {
		setCookie('sound', 0, 999999999);
		document.getElementById('json').classList.remove('mensel');
		document.getElementById('jsoff').classList.add('mensel');
		sound = 0;
	}
	else if (set == 1) {
		setCookie('sound', 1, 999999999);
		document.getElementById('json').classList.add('mensel');
		document.getElementById('jsoff').classList.remove('mensel');
		soundPlay('sounds/right');
	}
	//console.log(getCookie('sound'));
}
// Edit user info
function userEdit() {
	var name = document.getElementById('jsname').value;
	var email = document.getElementById('jsemail').value;
	var pass = document.getElementById('jspass').value;
	$.ajax({
		url: root+"script/userEdit.php?name="+name+"&email="+email+"&password="+pass,
		success: function(data) {
			//console.log(data);
			butUnload();
			document.getElementById('jsout').innerHTML = data;
		}
	});
}
// Rand PHP like function
function rand(min, max) {
	var min = min || 0,
		max = max || Number.MAX_SAFE_INTEGER;
	return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Image Exists
function imageExists(image_url){
	var http = new XMLHttpRequest();
	http.open('HEAD', image_url, false);
	http.send();
	return http.status != 404;
}
// uploadImg
function uploadImg(obj, user_id) {
	let photo = obj.files[0];
	let formData = new FormData();
  
	formData.append("photo", photo);
	formData.append("user_id", user_id);
	fetch(root + 'script/upload.php', { method: "POST", body: formData })
	.then(response => response.text())
	.then(result => {
		console.log("Результат виконання upload.php:", result);
	})
	.catch(error => console.error("Помилка:", error));
  
	let r = Math.random();
  
	document.getElementById('jsava').innerHTML += '<div id="jsloader" class="loader l2"></div>';
	
	function setImg() {
		let path = root+"images/avas/"+user_id+".png?t="+r;
		console.log(path);
		let imgbig = document.getElementById("imgbig");
		if (imageExists(path)) {
			imgbig.src = path;
			document.getElementById('jsloader').remove();
			clearInterval(int);
		}
	}
  
	let int = setInterval(setImg, 1000);
}
// Log Out
function logInOut(mode) {
	if (mode == 0) { // Log Out
		$.ajax({url: root+"script/logInOut.php?mode=0",success: function(data) {
			reload(true);
		}});
	}
	else if (mode == 1) { // Log In
		let email = document.getElementById('jsemail').value;
		let password = document.getElementById('jspassword').value;
		$.ajax({url: root+"script/logInOut.php?mode=1&email="+email+"&password="+password,success: function(data) {
			butUnload();
			document.getElementById('jsout4').innerHTML = data;
			if (strstr(data, 'green')) {
				setTimeout(function(){reload()}, 500); // Reload Page in 1 second
			}
		}});
	}
	else if (mode == 2 || mode == 3) { // Initialize deletion
		$.ajax({
			url: root+"script/logInOut.php?mode="+mode,
			success: function(data) {
				$("body").append(data);
			}
		});
		if (mode == 3) {
			setTimeout(function(){reload()}, 500); // Reload Page in 1 second
		}
	}
}
// Start
function account(state) {
	if (state == 0) {
		document.getElementById('start1').classList.remove('hide');
		document.getElementById('start0').classList.add('hide');
	}
	else if (state == 1) {
		document.getElementById('start1').classList.add('hide');
		document.getElementById('start0').classList.remove('hide');
	}
	else if (state == 2) {
		document.getElementById('start9').classList.add('hide');
		document.getElementById('start0').classList.remove('hide');
	}
	else if (state == 3) {
		document.getElementById('start0').classList.add('hide');
		document.getElementById('start9').classList.remove('hide');
	}
	else if (state == 4) {
		document.getElementById('start1').classList.add('hide');
		document.getElementById('start3').classList.remove('hide');
	}
}
// Forgotten password
var forpressed = false;
function forgot() {
	if (!forpressed) {
	var email = document.getElementById('jsemailforgot').value;
	$.ajax({
		url: root+"script/mail.php?type=forgot&to="+email,
		success: function(data) {
			butUnload();
			if (strstr(data, 'SUCCESS')) {
				document.getElementById('jsout3').innerHTML = '<p class="pgreen">'+LANG[6]+'</p>';
				forpressed = true;
			}
			else {
				document.getElementById('jsout3').innerHTML = '<p class="pred">'+LANG[7]+'</p>';
				console.log(data);
			}
		}
	});
	}
}
// Tutor
function tutor() {
	document.getElementById('jstutor').remove();
	setCookie('tutor', 1, 999999999);
}
// Sale
function sale(type) {
	document.getElementById('jsale'+type).remove();
	if (type == 50) {
		setCookie('sale50', 1, 999999999);
	}
	else if (type == 80) {
		setCookie('sale80', 1, 0.1);
	}
}
// Buy panel
function showBuy(type=1) {
	if (type==1) {
		setCookie('sale80', '', 999999999);
		document.getElementById('start4').classList.remove('hide');
	}
	else if (type==2) {
		document.getElementById('buynoads').classList.remove('hide');
	}
	
	try{document.getElementById('jslimit').remove();}catch{}
}
// Choose language
function langChoose(state, lang=false) {
	if (state == 0) {
		document.getElementById('langs').classList.remove('hide');
	}
	else if (state == 1) {
		document.getElementById('langs').classList.add('hide');
	}
}
// Like
function like(state) {
	var like = document.getElementById('jslike');
	if (state == 0) {
		like.style.display = "none";
	}
	else {
		var text = document.getElementById('revar').value;
		$.ajax({
			url: root+"script/review.php?text="+text,
			success: function(data) {
				var cont = document.getElementsByClassName('table_dark')[0];
				cont.innerHTML = data.split('</p>', 1)[0]+'</p>';
				cont.innerHTML += '<br><a class="button_small" href="javascript: void(0)" onclick="like(0)">OK</a>';
			}
		});
	}
}

// Translate string
function string(text, el) {
	console.log(text);
	el.classList.add('fadeinout');
	el.style.pointerEvents = 'none';
	$.ajax({
		url: root+"script/translate_string.php?text="+text,
		success: function(data) {
			var cont = document.createElement('div');
			cont.classList.add('transtring');
			cont.innerHTML = data.replace(/\\/g, '');
			el.insertAdjacentElement('afterend', cont);
			el.remove();
		}
	});
}

// Artists output AJAX
function artout(perpage=12, more=false, mode='artist') {
	try{var genre = document.getElementById('filter_genres').value;}catch{var genre = '';}
	try{var sort = document.getElementById('filter_sort').value;}catch{var sort = '';}
	if (mode == 'artist') {var find = document.getElementById('searchi').value;}
	else {var find = document.getElementById('searchis').value;}
	var limit = document.getElementById('limit').value;

	setCookie('genre', genre, 999999999);
	setCookie('sort', sort, 999999999);

	if (!more) {
		document.getElementById('out'+mode).innerHTML = '';
		document.getElementById('limit').value = 1;
		try{document.getElementById('jsbutmore').style.display = 'inline-block';}catch{}
	}
	else {
		limit = Number(limit)+1;
		document.getElementById('limit').value = limit;
	}

	document.getElementById('out'+mode).innerHTML += '<div id="jsloader" class="loader mb40"></div>';

	$.ajax({url: root+"script/artout.php?genre="+genre+"&sort="+sort+"&find="+find+"&perpage="+perpage+"&mode="+mode+"&limit="+limit,success: function(data) {
		if (!more) {document.getElementById('out'+mode).innerHTML = '';}
		try{document.getElementById('jsloader').remove();}catch{}
		var ar = data.split('<a');
		if (strstr(data, ':(') || ar.length < perpage) {
			try{document.getElementById('jsbutmore').style.display = 'none';}catch{}
		}
		document.getElementById('out'+mode).innerHTML += data;
	}});

	//console.log(genre+' '+sort+' '+find);
}
function chooseBrowser() {
	document.getElementById('jswebmob').remove();
	setCookie('webmob', 'yes', 1, false);
	$.ajax({url: root+"script/chooseBrowser.php",success: function(data) {}});
}
function showDonate(state=1) {
	if (state == 1) {
		try{document.getElementById('jsdonat2').classList.remove('hide');}catch{}
	}
	else {
		document.getElementById('jsdonat2').classList.add('hide');
	}
}
// Start tutor
function startTutor() {
	setCookie('tutor', 'ready', 1);
	window.location.href = '//'+domain+'/song/7029/142359';
}
// Songs today
function songsToday(current) {
	setTimeout(function(){setCookie('songsToday', Number(current)+1, 0.5);}, 10000)
}
// Rek click
function reclick(type) {
	if (type == 'learn') {setTimeout(function(){setCookie('gamesToday', 0, 0.5); reload();}, 18000);}
	else {setTimeout(function(){setCookie('songsToday', 2, 0.5); reload();}, 18000);}
}


// Main Preloader
document.addEventListener("DOMContentLoaded", function() {
	// Hide the preloader once the page content is loaded
	document.getElementById("preloader").style.display = "none";
 });
 
 // Display the preloader when a link is clicked
 const links = document.querySelectorAll("a");
 links.forEach(link => {
	link.addEventListener("click", function() {
		//console.log(link.href);
		if (link.href != 'javascript: void(0)' && link.target != "_blank") {
			document.getElementById("preloader").style.display = "flex";
		}
		//soundPlay('sounds/click2', true); // Play click sound on every a element
	});
 });

 // On error
function ignoreerror() {
   return true
}
window.onerror=ignoreerror();

// Remove google badge
const observer = new MutationObserver(() => {
	document.querySelector(".google-revocation-link-placeholder")?.remove();
});
  
observer.observe(document.body, {
	childList: true,
});

// Buttons loading animation
function butUnload() {
	function butUnloadDo() {
		document.querySelectorAll('.button_mid, .button_big').forEach(function(button) {
			button.classList.remove('butload');
		});
	}
	setTimeout(butUnloadDo, 100);
}
document.querySelectorAll('.button_mid, .button_big').forEach(function(button) {
		button.addEventListener('click', function() {
		this.classList.add('butload');
	});
});