//4th May 2019
var RhymingWords = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 10, wrongCnt = 0,levelNumber=2,totalLength=0,type="word";
RhymingWords.skipedQ = 0;
RhymingWords.homeFlag = null;
RhymingWords.alreadyShownObject = [];
RhymingWords.tempArr = [];								//json data
RhymingWords.skipFlag = true;
RhymingWords.attemptFlag = false;
RhymingWords.objPointerFlag = true;						//text clicked flag
RhymingWords.optionCnt = 0;								//counter for playing option in sequence
RhymingWords.levelName = "Learn";
//function for loader
$(document).ready(function () {
	$(".se-pre-con").fadeOut("slow");
	if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag = true;
	if(Utils.mobileDeviceFlag)
		Utils.Path=Android.getMediaPath("ChitraVichitra"); 
	setTimeout(function () {
		$("#gamepage,#endpage,#homeImg").hide();
		$("#coverpage").show();
		RhymingWords.init();
		RhymingWords.setImages();
	}, 300);
});
RhymingWords.init=function()
{
	for(var i=0;i<RhymingWords.data.length;i++)
		totalLength += RhymingWords.data[i].list.length;
	console.log(totalLength+" "+type);
}
RhymingWords.setImages = function () {						//set images 
	document.body.style.backgroundImage = "url(" + Utils.Path + RhymingWords.coverImage + ")";
	$("#homeImg").prop("src", Utils.Path + "images/skin/Home.png");
	$("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
	$("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
	$("#nextImage").prop("src", Utils.Path + "images/skin/Next.png");
	$("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
	$("#credit").prop("src", Utils.Path + "images/skin/credits.png");
	$("#sound").prop('src', Utils.Path + "images/skin/Sound.png");
	//$("#optionDiv1,#optionDiv2,#optionDiv3").prop('src', Utils.Path + "images/skin/Sound_M.png");
}
RhymingWords.playGame = function () {						//onclick of play button
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
	$("#homeImg,#gamepage,#gameParlourDiv").show();
	//$("#homeImg,#gamepage").show();
	$("#coverpage").hide();
	RhymingWords.createDivs();
	$(".textClass").css("margin-top", "1vh");
	RhymingWords.skipedQ = 0;
	RhymingWords.alreadyShownObject = [];
	$("#gameOverDiv").css("visibility", "hidden");
	$("#soundDiv").css("visibility", "visible");
	RhymingWords.tempArr = RhymingWords.data.slice();
	RhymingWords.showObjects();
}
RhymingWords.createDivs = function () { 			//create Divs for text node
	var  spanDiv,gameMachineDiv,screenDiv,displayDiv,buttonDiv,wordSoundDiv,wordSoundimg,spanDiv;
	for (var j = 0; j < RhymingWords.hardcoded.number; j++) {
		gameMachineDiv=document.createElement("div");
		gameMachineDiv.setAttribute("id","gameMachineDiv"+j);
		gameMachineDiv.setAttribute("class","gameMachineClass bgClass noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		gameMachineDiv.style.backgroundImage="url("+Utils.Path+"images/skin/machinBg.png)";
		gameParlourDiv.appendChild(gameMachineDiv);

		screenDiv=document.createElement("div");
		screenDiv.setAttribute("id","screenDiv"+j);
		screenDiv.setAttribute("class","screenClass noPadding bgClass col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		screenDiv.style.backgroundImage="url("+Utils.Path+"images/skin/screenBg.png)";
		gameMachineDiv.appendChild(screenDiv);

		displayDiv=document.createElement("div");
		displayDiv.setAttribute("id","displayDiv"+j);
		displayDiv.setAttribute("class","bgClass marginClass pointerClass  noPadding displayClass col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		displayDiv.style.backgroundImage="url("+Utils.Path+"images/skin/Display.png)";
		displayDiv.setAttribute("onclick", "RhymingWords.checkAnswer(this)");
		screenDiv.appendChild(displayDiv);
		
		spanDiv=document.createElement("div");
		spanDiv.setAttribute("id","spanDiv"+j);
		spanDiv.setAttribute("class","textFontClass noPadding noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
		displayDiv.appendChild(spanDiv);

		buttonDiv=document.createElement("div");
		buttonDiv.setAttribute("id","buttonDiv"+j);
		buttonDiv.setAttribute("class","borderClass buttonClass bgClass noPadding col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		buttonDiv.style.backgroundImage="url("+Utils.Path+"images/skin/buttonBg.png)";
		gameMachineDiv.appendChild(buttonDiv);
		

		if (RhymingWords.levelName == "Learn") {
			wordSoundDiv = document.createElement("div");
			wordSoundDiv.setAttribute("class", "optionClass col-lg-6 col-md-6 col-xs-6 col-sm-6 col-sm-offset-5 col-lg-offset-5 col-md-offset-5 col-xs-offset-5");
			buttonDiv.appendChild(wordSoundDiv);

			wordSoundimg = document.createElement('img');
			wordSoundimg.setAttribute("class", "img-responsive noPadding col-xs-12 col-sm-12 col-lg-12 col-md-12");
			wordSoundimg.setAttribute("src", Utils.Path + "images/skin/Sound_M.png");
			$(wordSoundimg).data("ans", j);
			wordSoundimg.setAttribute("onclick", "RhymingWords.playOptions(this)");
			wordSoundDiv.appendChild(wordSoundimg);
		}
		/* wordSoundDiv=document.createElement("div");
		buttonDiv.setAttribute("id","wordSoundDiv"+j);
		buttonDiv.setAttribute("class","col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		buttonDiv.style.backgroundImage="url("+Utils.Path+"iamges/skin/buttonBg.png)";
		gameMachineDiv.appendChild(buttonDiv);



		pictureDiv = document.createElement("div");
		pictureDiv.setAttribute("id", "textDiv" + j);
		if (j < 2) {
			pictureDiv.setAttribute("class", "pointerClass pointers noPadding col-md-5 col-xs-5 col-lg-5 col-sm-5 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
			buttonDiv1.appendChild(pictureDiv);
		}
		else {
			pictureDiv.setAttribute("class", "pointerClass pointers noPadding col-md-5 col-xs-5 col-lg-5 col-sm-5 col-sm-offset-4 col-lg-offset-4 col-md-offset-4 col-xs-offset-4");
			buttonDiv2.appendChild(pictureDiv);
		}
		spanDiv = document.createElement('div');
		spanDiv.setAttribute("id", "spanDiv" + j);
		spanDiv.setAttribute("class", " textFontClass noPadding img-responsive col-lg-12 col-md-12 col-xs-12 col-sm-12");
		spanDiv.setAttribute("onclick", "RhymingWords.checkAnswer(this)");
		pictureDiv.appendChild(spanDiv);
		if (RhymingWords.levelName == "Learn") {
			soundimgDiv = document.createElement("div");
			soundimgDiv.setAttribute("class", "optionClass noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
			pictureDiv.appendChild(soundimgDiv);

			soundimg = document.createElement('img');
			soundimg.setAttribute("class", "img-responsive noPadding col-lg-5 col-md-5 col-xs-5 col-sm-5 col-sm-offset-6 col-lg-offset-6 col-md-offset-6 col-xs-offset-6");
			soundimg.setAttribute("src", Utils.Path + "images/skin/Sound_M.png");
			$(soundimg).data("ans", j);
			soundimg.setAttribute("onclick", "RhymingWords.playOptions(this)");
			soundimgDiv.appendChild(soundimg);
		}*/
	} 
}
RhymingWords.showObjects = function () {							//display objects on screen
	var d;
	RhymingWords.optionCnt = 0;
	RhymingWords.skipFlag = true;
	RhymingWords.objPointerFlag = true;
	$("#nextImage").css({ "pointer-events": "none" });
	$(".pointerClass").css({ "pointer-events": "none" });
	$("#gameParlourDiv").addClass("animated fadeInLeft");
	//document.getElementById("screenDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/thinking.gif)";
	$("#gamepage").show();
	RhymingWords.homeFlag = "showlevel";
	$("#acknowledgementDiv,.textFontClass").text('');
	$("#gameOverDiv").css("visibility", "hidden");
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	RhymingWords.randomLevel = Math.floor(Math.random() * RhymingWords.tempArr.length);
	while (RhymingWords.tempArr[RhymingWords.randomLevel].list.length < 3)		//if list length is < 3 calculate new level
		RhymingWords.randomLevel = Math.floor(Math.random() * RhymingWords.tempArr.length);
	console.log(RhymingWords.tempArr[RhymingWords.randomLevel].list.length);
	RhymingWords.uniqueTextArr = [];
	RhymingWords.uniqueTextArr = populate(RhymingWords.tempArr[RhymingWords.randomLevel].list, RhymingWords.uniqueTextArr, RhymingWords.hardcoded.number);
	
	for (var j = 0; j < 3; j++) {			//display text & set data to text
		var index=0;
		$("#displayDiv" + j).data("ans", RhymingWords.uniqueTextArr[j].word);
		for(var k=0;k<RhymingWords.uniqueTextArr[j].word.length;k++)			//create span for each letter
		{
			var spanEle;
			spanEle=document.createElement("span");
			spanEle.setAttribute("id","spanEle"+k+j);
			spanEle.setAttribute("class","spanClass");
			$(spanEle).text(RhymingWords.uniqueTextArr[j].word[k]);
			$("#spanDiv" + j).append(spanEle);
		}
		index=RhymingWords.uniqueTextArr[j].word.lastIndexOf(RhymingWords.tempArr[RhymingWords.randomLevel].suffix);
		for(;index<RhymingWords.uniqueTextArr[j].word.length;index++)
			$("#spanEle"+index+j).css("color","rgb(243, 42, 10)");			//suffix in red color
	}
	RhymingWords.uniqueQue = Math.floor(Math.random() * (RhymingWords.uniqueTextArr.length));	//get unique Question
	while ($.inArray(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word, RhymingWords.alreadyShownObject) !== -1)
		RhymingWords.uniqueQue = Math.floor(Math.random() * (RhymingWords.uniqueTextArr.length));
	RhymingWords.alreadyShownObject.push(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word);
	console.log(RhymingWords.alreadyShownObject);
	questionId = parseInt(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].questionId);
	if (RhymingWords.instructionTimer) {
		clearTimeout(RhymingWords.instructionTimer);
		RhymingWords.instructionTimer = null;
	}
	RhymingWords.instructionTimer = setTimeout(function () {
		$("#gameParlourDiv").removeClass("animated fadeInLeft");
		$("#nextImage").css({ "pointer-events": "auto" });
		RhymingWords.playInstruction();
	}, 800);
}
RhymingWords.playOptions = function (element) {		//plays particular sound for text
	clearTimeout(RhymingWords.instructionTimer);
	clearTimeout(RhymingWords.optionTimer);
	$("#soundDiv").css({ "pointer-events": "auto" });
	$(".textFontClass").removeClass("animated zoomIn");
	var data = $(element).data("ans");
	document.getElementById('playSound').pause();
	document.getElementById('playSound').src = Utils.Path + 'sounds/' + RhymingWords.uniqueTextArr[data].sound;
	document.getElementById('playSound').play();
}
RhymingWords.playInstruction = function () {				// plays instruction/option sounds
	RhymingWords.soundFlag = true;
	$(".optionClass").css("pointer-events", "none");
	$("#nextImage").css({ "pointer-events": "auto" });
	if (RhymingWords.objPointerFlag)
		$(".pointerClass").css({ "pointer-events": "none" });
	if (RhymingWords.levelName == "Learn") {
		if (RhymingWords.optionCnt < 3)
			getDuration(Utils.Path + 'sounds/' + RhymingWords.uniqueTextArr[RhymingWords.optionCnt].sound, "play");
		else
			getDuration(Utils.Path + 'sounds/instruction/' + RhymingWords.hardcoded.instruction, "playInstruction");
	}
	else
		getDuration(Utils.Path + 'sounds/instruction/' + RhymingWords.hardcoded.instruction, "playInstruction");
}
function getDuration(src, functionName) {			//gets duration of sound 
	var duration = 0;
	if (RhymingWords.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			RhymingWords.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			if (functionName == "playInstruction")
				RhymingWords.playNextSound(duration);
			else
				RhymingWords.playOptionsInLoop(duration);
		});
		$('#playSound').prop('src', src);
	}
}
RhymingWords.playOptionsInLoop = function (duration)						//play option sounds in a loop
{
	$("#spanDiv" + RhymingWords.optionCnt).addClass("animated spaceInUp");
	clearTimeout(RhymingWords.instructionTimer);
	document.getElementById('playSound').play();
	if (RhymingWords.optionTimer) {
		clearTimeout(RhymingWords.optionTimer);
		RhymingWords.optionTimer = null;
	}
	RhymingWords.optionTimer = setTimeout(function () {
		$("#spanDiv" + RhymingWords.optionCnt).removeClass("animated spaceInUp");
		RhymingWords.optionCnt++;
		if (RhymingWords.optionCnt > 2) {
			clearTimeout(RhymingWords.optionTimer);
			setTimeout(function () { RhymingWords.playInstruction(); }, 1000);
		}
		else
			RhymingWords.playInstruction();
	}, duration * 2000);
}

RhymingWords.playNextSound = function (duration)								//function for instruction
{
	$(".optionClass").css("pointer-events", "auto");
	document.getElementById('playSound').play();
	if (RhymingWords.instructionTimer) {
		clearTimeout(RhymingWords.instructionTimer);
		RhymingWords.instructionTimer = null;
	}
	RhymingWords.instructionTimer = setTimeout(function () {
		document.getElementById('playSound').pause();
		document.getElementById('playSound').src = Utils.Path + 'sounds/' + RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].sound;
		document.getElementById('playSound').play();
		setTimeout(function () {
			if (RhymingWords.objPointerFlag) {
				RhymingWords.objPointerFlag = false;
				$(".pointerClass").css({ "pointer-events": "auto" });
			}
		}, duration * 800);
	}, duration * 1000);
}
RhymingWords.checkAnswer = function (element) {						//Check Answer
	var randomSound;
	clearTimeout(RhymingWords.wrongAnsTimer);
	RhymingWords.skipFlag = false;
	clearTimeout(RhymingWords.instructionTimer);
	if (wrongCnt == 0)
		scoredMarks = 10;
	else if (wrongCnt == 1)
		scoredMarks = 5;
	else
		scoredMarks = 1;
	if (($(element).data('ans') == RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word)) {
		$(".pointerClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
		$(element).children().addClass("animated zoomIn");
		//document.getElementById("screenDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/dancing.gif)";
		randomSound = Math.floor(Math.random() * (RhymingWords.correctAns.length));
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + RhymingWords.correctAns[randomSound];
		document.getElementById('playSound').play();
		if (RhymingWords.nextQ) {
			clearTimeout(RhymingWords.nextQ);
			RhymingWords.nextQ = null;
		}
		RhymingWords.nextQ = setTimeout(function () {
			$(element).children().removeClass("animated zoomIn");
			$("#gameParlourDiv").removeClass("animated fadeInLeft");
			RhymingWords.nextQuestion();
		}, 2000);
		console.log(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word,totalLength,type);
		if(Utils.mobileDeviceFlag)
			Android.addLearntData(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word,totalLength,type);

		RhymingWords.calculateScore();
	}
	else {
		wrongCnt++;
		$(element).css({ "pointer-events": "none" ,"opacity":"0.5"});
		$(element).children().addClass("animated shake");
		//document.getElementById("screenDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/wrong.gif)";
		RhymingWords.attemptFlag = true;
		randomSound = Math.floor(Math.random() * (RhymingWords.wrongAns.length));
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + RhymingWords.wrongAns[randomSound];
		document.getElementById('playSound').play();
		if (RhymingWords.wrongAnsTimer) {
			clearTimeout(RhymingWords.wrongAnsTimer);
			RhymingWords.wrongAnsTimer = null;
		}
		RhymingWords.wrongAnsTimer = setTimeout(function () {
			$(element).children().removeClass("animated shake");
			//document.getElementById("screenDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/thinking.gif)";
		}, 2000);
	}
}
RhymingWords.nextQuestion = function () {						//Loads Next Question
	RhymingWords.skipedQ++;
	clearTimeout(RhymingWords.nextQ);
	clearTimeout(RhymingWords.wrongAnsTimer);
	clearTimeout(RhymingWords.instructionTimer);
	clearTimeout(RhymingWords.optionTimer);
	$(".textFontClass").removeClass("animated zoomIn spaceInUp shake");
	$("#gameParlourDiv").removeClass("animated fadeInLeft");
	if (RhymingWords.attemptFlag) {
		scoredMarks = 0;
		RhymingWords.attemptFlag = false;
		RhymingWords.calculateScore();
	}
	if (RhymingWords.skipFlag) {
		scoredMarks = -1;
		RhymingWords.calculateScore();
	}
	wrongCnt = 0;
	document.getElementById('playSound').pause();
	$(".pointerClass").css({"pointer-events": "auto","opacity":"1"});
	RhymingWords.tempArr.splice(RhymingWords.tempArr.indexOf(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue]));
	if (RhymingWords.skipedQ == 5) {
		$('#endpage').show();
		$('#gamepage,#acknowledgementDiv').hide();
		$("#soundDiv").css("visibility", "hidden");
		$("#gameOverDiv").text(RhymingWords.hardcoded.gameOver);
		$("#gameOverDiv").css("visibility", "visible");
		RhymingWords.createHardcodeddivs();
	}
	else
		RhymingWords.showObjects();
}
RhymingWords.createHardcodeddivs = function () {
	var ackDiv;
	for (var i = 0; i < Object.keys(RhymingWords.acknowledgementData).length; i++) {
		ackDiv = document.createElement("div");
		ackDiv.setAttribute("id", "ack" + i);
		ackDiv.setAttribute("class", "noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
		ackDiv.innerHTML = Object.keys(RhymingWords.acknowledgementData)[i] + " : " + Object.values(RhymingWords.acknowledgementData)[i];
		document.getElementById("acknowledgementDiv").appendChild(ackDiv);
	}
	div = document.createElement('div');
	div.className = "noPadding fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML = RhymingWords.hardcoded['createdOn'];
	document.getElementById("acknowledgementDiv").appendChild(div);
}
RhymingWords.callHome = function () {
	if (RhymingWords.attemptFlag) {
		scoredMarks = 0;
		RhymingWords.attemptFlag = false;
		RhymingWords.calculateScore();
	}
	location.reload(true);
}
RhymingWords.playAgain = function () {
	document.getElementById('playSound').pause();
	$(".textFontClass").removeClass("animated zoomIn shake");
	$("#gameOverDiv,#soundDiv").css("visibility", "visible");
	$("#endpage").hide();
	RhymingWords.skipedQ = 0;
	wrongCnt = 0;
	RhymingWords.optionCnt = 0;
	RhymingWords.skipFlag = true;
	clearTimeout(RhymingWords.nextQ);
	clearTimeout(RhymingWords.instructionTimer);
	clearTimeout(RhymingWords.optionTimer);
	RhymingWords.alreadyShownObject = [];
	RhymingWords.tempArr = [];
	RhymingWords.tempArr = RhymingWords.data.slice();
	RhymingWords.showObjects();
}
RhymingWords.calculateScore = function () {
	RhymingWords.attemptFlag = false;
	console.log(resId, questionId, scoredMarks, totalMarks,levelNumber, startTime, RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks,levelNumber, startTime, RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word);
}
RhymingWords.showCredit = function () {
	$("#acknowledgementDiv").show();
}