// Game Started 8/11/2018
var FindIt = {};
var Utils = {};
Utils.Path = '';
FindIt.seconds = 0;
var questionId = 0, startTime = 0, scoredMarks = 0, totalMark = 10, resId = 0, level = 2, attempt = "", newQuestionLoad = true;
Utils.mobileDeviceFlag = false; FindIt.totalQue = 0; FindIt.skippedCnt = 0;
var askedQue = [], gameAllQueArr = [[], [], [], [], []], skipQue = []; FindIt.skipFlag = false, scoreSubmit = false;
var currentWord, totalLength, questionType = "word"; FindIt.totalCorrectCnt = 0;
$(document).ready(function () {
	$(".se-pre-con").fadeOut("slow");
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
		Utils.mobileDeviceFlag = true;
	setTimeout(function () {
		document.body.style.backgroundImage = "url(" + Utils.Path + "images/find-the-word_Cover.png)";
		FindIt.setImages();
		FindIt.setEvents();
		if (FindIt.hardCodedData['languageFont'] != null)
			setFontFamilyForLang("fonts/" + FindIt.hardCodedData['languageFont']);
	}, 200);
	FindIt.level = 1;//Math.floor(Math.random()*3);
	console.log("Level " + FindIt.level);
});

setFontFamilyForLang = function (fontFilePath) {
	var newStyle = "<style>" +
		"@font-face {  " +
		"font-family: 'CustomFontFamily';" +
		"src: url('" + fontFilePath + "') format('truetype');" +
		"}  </style>";
	$("head").append(newStyle);
	$("body").css("font-family", "CustomFontFamily");
}

FindIt.setImages = function () {
	document.getElementById('leftDiv').style.backgroundImage = "url(" + Utils.Path + "images/bg_1.png)";
	document.getElementById('rightDiv').style.backgroundImage = "url(" + Utils.Path + "images/bg_2.png)";
	document.getElementById('home').src = Utils.Path + "images/home.png";
	document.getElementById('logo').src = Utils.Path + "images/logo.png";
	document.getElementById('playImage').src = Utils.Path + "images/Play.png";
	document.getElementById('nextQueBtn').src = Utils.Path + "images/Skip.png";
	document.getElementById('soundBtn').src = Utils.Path + "images/Sound.png";
	document.getElementById('nextGame').src = Utils.Path + "images/next.png";
	document.getElementById('column').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy-wall.png)";

	FindIt.imgArr = ["Boy_1_get", "Boy_3_wall", "Girl_3_wall", "Girl_2_tree", "Boy_2_troli", "Girl_1_tank"];
	for (var i = 0; i < FindIt.imgArr.length; i++)
		document.getElementById('object' + i).style.backgroundImage = "url(" + Utils.Path + "images/" + FindIt.imgArr[i] + ".png)";
	document.getElementById('questionDiv').style.backgroundImage = "url(" + Utils.Path + "images/Boy_1_get_Board.png)";
	FindIt.setAnswerWiseImages("");
	var tilesArr = ["Boy_1_get_Board.png", "wall_Board.png", "Girl_3_wall_Board.png", "Girl_2_tree_Board.png", "Boy_2_troli_Board.png", "Girl_1_tank_Board.png"]
	//document.getElementById('boyImg').src=Utils.Path+"images/Main-boy.png";
	for (var i = 0; i < tilesArr.length; i++)
		document.getElementById('optionTile' + i).src = Utils.Path + "images/" + tilesArr[i];

	/* document.getElementById('replayImg').src = Utils.Path + "images/replay.png"; */
	//document.getElementById('creditImg').src = Utils.Path + "images/credits.png";
}

FindIt.setEvents = function () {
	$("#home").click(function () {
		FindIt.callHome();
	});
	$("#playImage").click(function () {
		FindIt.playgame();
	});
	$("#sound").click(function () {
		FindIt.playSound();
	});
	$("#nextBtn").click(function () {
		FindIt.nextQue("skip");
	});
	$("#nextGameDiv").click(function () {
		clearInterval(FindIt.noResponseTimer);
		FindIt.noResponseTimer = null;
		if (Utils.mobileDeviceFlag)
			Android.GotoNextGame();
	});
	/* $("#replayImg").click(function () {
		$("#acknowledgementDiv").empty();
		$("#endPage").hide();
		FindIt.playgame();
		//location.reload();
	}); */
	$("#Yes").click(function () {
		FindIt.skippedCnt = 0;
		FindIt.showSkippedQuestions();
	});
	$("#No").click(function () {
		FindIt.showEndPage();
	});
	$('.tileDiv').click(function (event) {
		event.stopPropagation();
		FindIt.checkAnswer(this.id);
	});
	$('.tileSpan').click(function (event) {
		event.stopPropagation();
		FindIt.checkAnswer(this.id);
	});
	/* 	$("#credits").click(function () {
			$("#acknowledgementDiv").css("visibility", "visible");
		}); */
}

FindIt.createStars = function () {
	var newImage, newDiv, i, numberOfStars = 5;//(correctCnt/FindIt.totalAttmptCnt)*5;
	for (i = 1; i <= numberOfStars; i++) {
		newDiv = document.createElement("div");
		newDiv.setAttribute("id", "starDiv" + i);
		newDiv.setAttribute("class", "noPadding stars col-xs-2 col-md-2 col-lg-2 col-sm-2 ");

		newImage = document.createElement("img");
		newImage.setAttribute("id", "starImg" + i);
		newImage.setAttribute("class", "img-responsive");
		newImage.setAttribute("src", Utils.Path + "images/star5.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
	$("#starDiv").hide();
};

FindIt.startTimer = function () {
	if (FindIt.noResponseTimer) {
		clearInterval(FindIt.noResponseTimer);
		FindIt.noResponseTimer = null;
		FindIt.seconds = 0;
	}
	FindIt.noResponseTimer = setInterval(function () {
		FindIt.seconds++;
		if (FindIt.seconds >= 5) {
			document.getElementById("playSound").src = Utils.Path + "sounds/instruction/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(FindIt.noResponseTimer);
			FindIt.timeOut = setTimeout(function () {
				FindIt.seconds = 0;
				FindIt.startTimer();
			}, 2000);
		}
	}, 1000);
}
// set suffix and sound
FindIt.playgame = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/bg.png)";
	$("#logo").css("visibility", "hidden");
	FindIt.correct = 0;
	FindIt.wrong = 0;
	FindIt.reset();
	FindIt.createStars();
	//document.body.style.backgroundImage = "url(images/back.png)";
	//document.getElementById("home").style.visibility = "visible";
	document.getElementById("coverPage").style.display = "none";
	document.getElementById("gamePage").style.display = "block";
	document.getElementById('endPage').style.display = "none";
	FindIt.copyJson = JSON.parse(JSON.stringify(FindIt.wordsData[FindIt.level].levelData));
	totalLength = FindIt.copyJson.length;
	getData();
}

FindIt.reset = function () {
	FindIt.isLetterSelected = false;
	FindIt.questionArr = [];
	FindIt.attemptCnt = 0;
	FindIt.questionAttemptCnt = 0;
	FindIt.optionCnt = 6;
	FindIt.questionArr = [];
}

function getData() {
	var d, cnt = 0; scoreSubmit = false;
	$('.wordSpan').text('');
	clearTimeout(FindIt.answerAudio);
	FindIt.answerAudio = null;
	FindIt.questionArr = [];
	d = new Date();
	FindIt.startTimer();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	if (!FindIt.skipFlag) {
		getUniqueValArr(FindIt.copyJson, FindIt.questionArr, FindIt.optionCnt);
		FindIt.question = Math.floor(Math.random() * FindIt.questionArr.length);
		while ($.inArray(FindIt.questionArr[FindIt.question].word, askedQue) != -1)
			FindIt.question = Math.floor(Math.random() * FindIt.questionArr.length);

		currentWord = FindIt.questionArr[FindIt.question].langWord;
		FindIt.answer = FindIt.questionArr[FindIt.question].word;
		questionId = FindIt.questionArr[FindIt.question].questionId;
		askedQue.push(FindIt.answer);
		//console.log(FindIt.questionArr);
		console.log(FindIt.answer);
	}
	else {
		FindIt.questionArr = gameAllQueArr[FindIt.skippedCnt][0];
		FindIt.question = skipQue[FindIt.skippedCnt];
		currentWord = gameAllQueArr[FindIt.skippedCnt][0][skipQue[FindIt.skippedCnt]].langWord;
		FindIt.answer = gameAllQueArr[FindIt.skippedCnt][0][skipQue[FindIt.skippedCnt]].word;
		questionId = gameAllQueArr[FindIt.skippedCnt][0][skipQue[FindIt.skippedCnt]].questionId;

	}



	FindIt.setQuestionAndOption();
}

function getUniqueValArr(inputArr, outputArr, length) {
	for (var i = 0; i < length; i++) {
		var randNum = Math.floor(Math.random() * inputArr.length);
		if (outputArr.includes(inputArr[randNum])) {
			i--;
			continue;
		}
		else {
			outputArr.push(inputArr[randNum]);
		}
	}
}

FindIt.setQuestionAndOption = function () {
	for (var i = 0; i < FindIt.optionCnt; i++) {
		$("#option" + i).text(FindIt.questionArr[i].word);
		$("#option" + i).data("setWord", FindIt.questionArr[i].word);
	}
	//if(i==6)
	//{
	$("#question").text(FindIt.questionArr[FindIt.question].langWord);
	$("#question").data("setWord", FindIt.questionArr[FindIt.question].word);
	//}	
	FindIt.playSound();
}

FindIt.playSound = function () {
	document.getElementById("playSound").pause();
	FindIt.answerAudio = setTimeout(function () {
		document.getElementById("playSound").src = Utils.Path + 'sounds/' + FindIt.questionArr[FindIt.question].sound;
		document.getElementById("playSound").play();
	}, 500);
}

FindIt.checkAnswer = function (id) {
	if (id.length == 7)
		id = id.substring(6);
	else
		id = id.substring(10);

	$('.tileSpan').css("pointer-events", "none");
	$('.tileDiv').css("pointer-events", "none");
	$('#sound').css("pointer-events", "none");
	//	alert(id);
	clearInterval(FindIt.noResponseTimer);
	FindIt.noResponseTimer = null;
	clearTimeout(FindIt.timeOut);
	FindIt.timeOut = null;
	FindIt.seconds = 0;
	FindIt.attemptCnt++;
	var getClickedOption;
	getClickedOption = $("#option" + id).text();
	//getClickedOption=document.getElementById(id).nextSibling.innerHTML;
	FindIt.isLetterSelected = true;
	attempt += $("#option" + id).text() + ",";
	//	FindIt.questionAttemptCnt++;

	if (getClickedOption == FindIt.answer) {
		//alert('Correct');

		FindIt.correct = true;
		FindIt.totalCorrectCnt++;
		document.getElementById("playSound").src = Utils.Path + 'sounds/instruction/Anahhh.mp3';
		document.getElementById("playSound").play();
		//if (FindIt.questionAttemptCnt == 1)
		scoredMarks = 10;
		scoreSubmit = true;
		if (Utils.mobileDeviceFlag) {
			Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
			//Android.addLearntData(currentWord, totalLength, questionType);
		}
		console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
		console.log(currentWord, totalLength, questionType);
		FindIt.setAnswerWiseImages("sad");
		setTimeout(function () {
			FindIt.setAnswerWiseImages("");
			$('.tileSpan').css("pointer-events", "auto");
			$('.tileDiv').css("pointer-events", "auto");
			$('#sound').css("pointer-events", "auto");
			//setTimeout(function(){
			FindIt.nextQue("newQue");
			//	},1000); 
		}, 2500);
		//$("#wordSpan"+6).addClass("animated zoomIn");


	}
	else {
		scoredMarks = 0;
		FindIt.correct = false;

		document.getElementById("playSound").src = Utils.Path + 'sounds/instruction/Cheering.mp3';
		document.getElementById("playSound").play();
		scoreSubmit = true;
		if (Utils.mobileDeviceFlag)
			Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
		console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);

		FindIt.setAnswerWiseImages("happy");
		setTimeout(function () {
			FindIt.setAnswerWiseImages("");
			$('.tileSpan').css("pointer-events", "auto");
			$('.tileDiv').css("pointer-events", "auto");
			$('#sound').css("pointer-events", "auto");
		}, 2500);
	}

	if (FindIt.skipFlag) {
		gameAllQueArr.splice(FindIt.skippedCnt, 1);
		skipQue.splice(FindIt.skippedCnt, 1);
	}
	console.log(gameAllQueArr);
	setTimeout(function () {
		if (FindIt.attemptCnt < 5) {
			attempt = ''; FindIt.correct = false;
			FindIt.isLetterSelected = false;
			if ((FindIt.totalQue + FindIt.attemptCnt) == 5 && FindIt.attemptCnt < 5)
				FindIt.showPopup();
			else
				getData();
		}
		else
			FindIt.showEndPage();
	}, 2500);
}

FindIt.setAnswerWiseImages = function (flag) {
	if (flag == "sad")
		document.getElementById('boy').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy_Win.png)";
	else if (flag == "happy")
		document.getElementById('boy').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy_Lose.png)";
	else
		document.getElementById('boy').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy.png)";
	//document.getElementById('boyImg').src=Utils.Path+"images/Main-boy.png";

	for (var i = 0; i < FindIt.imgArr.length; i++) {
		if (flag == "happy" || flag == "sad")
			document.getElementById('object' + i).style.backgroundImage = "url(" + Utils.Path + "images/" + FindIt.imgArr[i] + "_" + flag + ".png)";
		else
			document.getElementById('object' + i).style.backgroundImage = "url(" + Utils.Path + "images/" + FindIt.imgArr[i] + ".png)";

	}
}
FindIt.nextQue = function (attemptType) {

	clearTimeout(FindIt.newQueLoad);
	FindIt.newQueLoad = null;
	//	FindIt.attemptCnt++;
	// skip
	if (attemptType == "skip" && FindIt.isLetterSelected == false) {
		//scoredMarks = -1;
		if (gameAllQueArr[FindIt.skippedCnt].includes(FindIt.questionArr) == false) {
			gameAllQueArr[FindIt.skippedCnt].push(FindIt.questionArr);
			skipQue.push(FindIt.question);
		}
		FindIt.skippedQuestion();
		/* 	if (Utils.mobileDeviceFlag)
			Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
		//Android.addScore(resId,questionId,scoredMarks,totalMark,level,startTime);
		console.log(questionId, scoredMarks, totalMark, level, startTime, attempt); */
	}// option select and skip
	/* 	else if (attemptType != "newQue" && !FindIt.correct) {
			scoredMarks = 0;
			if (Utils.mobileDeviceFlag)
				Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
			//Android.addScore(resId,questionId,scoredMarks,totalMark,level,startTime);
			console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
		} */


	//},1000);
}


FindIt.skippedQuestion = function () {
	FindIt.totalQue++; FindIt.skippedCnt++;
	if ((FindIt.totalQue + FindIt.attemptCnt) == 5 && FindIt.attemptCnt < 5)
		FindIt.showPopup();
	else
		getData();
}

FindIt.showPopup = function () {

	clearInterval(FindIt.noResponseTimer);
	FindIt.noResponseTimer = null;
	clearTimeout(FindIt.timeOut);
	FindIt.timeOut = null;
	clearTimeout(FindIt.answerAudio);
	FindIt.answerAudio = null;
	FindIt.seconds = 0;
	$('#responseBoxDiv').show();
	$('#questionMsg').text(FindIt.modalData.responseMsg);
	$('#Yes').text(FindIt.modalData.yes);
	$('#No').text(FindIt.modalData.no);
	FindIt.skippedCnt = 0;
}

FindIt.showSkippedQuestions = function () {
	$('#responseBoxDiv').hide();
	FindIt.skipFlag = true;
	FindIt.skippedCnt = 0;
	FindIt.totalQue = 0;
	for (var i = 0; i < gameAllQueArr.length; i++) {
		if (gameAllQueArr[i].length == 0)
			gameAllQueArr.pop();
	}
	getData();
}

FindIt.showLastPage = function () {
	var length = 0;
	length = FindIt.attemptCnt + FindIt.skippedCnt;
	$('#coverpage,#gamepage,#responseBoxDiv,#scoreBoard').hide();
	$('#lastPage,#msgDiv').show();
	$('#gamePage').empty();
	if (FindIt.skipFlag == true) {
		length = 5;
	}
}

FindIt.showEndPage = function () {
	askedQue = [];
	clearTimeout(FindIt.answerAudio);
	FindIt.answerAudio = null;
	clearInterval(FindIt.noResponseTimer);
	FindIt.noResponseTimer = null;
	clearTimeout(FindIt.timeOut);
	FindIt.timeOut = null;
	document.getElementById("gamePage").style.display = "none";
	document.getElementById("endPage").style.display = "block";
	$("#home,#acknowledgementDiv").css("visibility", "hidden");
	FindIt.giveStars();
	$("#nextGameDiv").addClass('blink_me');
	//FindIt.AcknowledgementPage();
	$("#gameOver").text(FindIt.hardCodedData.gameOver);
	if (Utils.mobileDeviceFlag)
		Android.StudentCertification(FindIt.totalCorrectCnt, 5, "7");
	console.log(FindIt.totalCorrectCnt, 5, "7");
}

FindIt.giveStars = function () {
	$("#starDiv").show();
	var i, numberOfStars = (FindIt.totalCorrectCnt);
	for (i = 1; i <= numberOfStars; i++) {
		document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/star1.png");
	}
	//document.getElementById('playSound').src=Utils.Path+"sounds/starsound"+totalCorrectCnt;
	if (FindIt.totalCorrectCnt != 0) {
		document.getElementById('playSound').src = Utils.Path + "sounds/instruction/Star" + FindIt.totalCorrectCnt + ".mp3";
		document.getElementById('playSound').play();
	}
};

/* FindIt.AcknowledgementPage = function () {
	var i = 0, div;
	gameOver.innerHTML = FindIt.hardCodedData.gameOver;
	//console.log(Object.keys(FindIt.AcknowledgementPageData).length);
	for (i = 0; i < Object.keys(FindIt.AcknowledgementPageData).length; i++) {
		div = document.createElement('div');
		div.className = "fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML = Object.keys(FindIt.AcknowledgementPageData)[i] + " : " + Object.values(FindIt.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div = document.createElement('div');
	div.className = "fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML = FindIt.hardCodedData['createdOn'];
	acknowledgementDiv.appendChild(div);
} */

FindIt.callHome = function () {
	var attemptedLetter = attempt.split(",").splice(0, attempt.split(",").length - 1);
	attempt = attempt.slice(0, attempt.length - 1);
	console.log(attemptedLetter.length + "**" + attempt);


	if (FindIt.isLetterSelected && !scoreSubmit) {
		if (Utils.mobileDeviceFlag)
			Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
		//Android.addScore(resId,questionId,scoredMarks,totalMark,level,startTime);	
		console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
	}

	FindIt.isLetterSelected = false;
	document.getElementById("playSound").pause();
	location.reload();
}

