//4th May 2019
var RhymingWords = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 10, levelNumber=1,totalLength=0,type="word",correctCnt=0;
RhymingWords.skipedQ = 0;
RhymingWords.homeFlag = null;
RhymingWords.alreadyShownObject = [];
RhymingWords.tempArr = [];								//json data
RhymingWords.objPointerFlag = true;						//text clicked flag
RhymingWords.optionCnt = 0;								//counter for playing option in sequence
RhymingWords.seconds=0;
RhymingWords.skipFlag=true;	
RhymingWords.mainArr=[];	
queCnt=0;
RhymingWords.uniqueTextArr = [];
RhymingWords.skipCnt=0;
							//skipped Que flag
//function for loader
$(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;
	/* if(Utils.mobileDeviceFlag)
		Utils.Path=Android.getMediaPath("ChitraVichitra");  */
	setTimeout(function () {
		$("#gamepage,#endpage,#responseBoxDiv").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 + ")";
	$("#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/Skip.png");
	$("#nextGameImage").prop("src", Utils.Path + "images/skin/Next.png");
	$("#sound").prop('src', Utils.Path + "images/skin/Sound.png");
}
RhymingWords.playGame = function () {						//onclick of play button
	var uniqueLevels;
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
	$("#gamepage,#gameParlourDiv").show();
	$("#coverpage").hide();
	RhymingWords.createDivs();
	$(".textClass").css("margin-top", "1vh");
	RhymingWords.skipedQ = 0;
	RhymingWords.alreadyShownObject = [];
	$("#gameOverDiv").css("visibility", "hidden");
	$("#soundDiv").css("visibility", "visible");
	while(RhymingWords.tempArr.length!=5)
	{
		uniqueLevels = Math.floor(Math.random() * RhymingWords.data.length);
		while (RhymingWords.data[uniqueLevels].list.length < 3 || $.inArray(uniqueLevels, RhymingWords.alreadyShownObject) !== -1)		//if list length is < 3 calculate new level
		uniqueLevels = Math.floor(Math.random() * RhymingWords.data.length);
		RhymingWords.tempArr.push(RhymingWords.data[uniqueLevels]);
		RhymingWords.alreadyShownObject.push(uniqueLevels);
	}
	
	for(var i=0;i<5;i++)
	{
		var queObj={};
		queObj['combineQue']=[];
		RhymingWords.uniqueTextArr=[];
		queObj['suffix']=RhymingWords.tempArr[i].suffix;
		RhymingWords.uniqueTextArr = populate(RhymingWords.tempArr[i].list, RhymingWords.uniqueTextArr, RhymingWords.hardcoded.number);
		queObj['ques']=RhymingWords.uniqueTextArr[0];
		queObj['combineQue'].push(RhymingWords.uniqueTextArr[0]);
		queObj['options']=[];
		for(var j=0;j<2;j++)
		{
			queObj['options'].push(RhymingWords.uniqueTextArr[j+1]);
			queObj['combineQue'].push(RhymingWords.uniqueTextArr[j+1]);
		}
		RhymingWords.mainArr.push(queObj);
	}
	RhymingWords.createStars();
	RhymingWords.showObjects();
}
RhymingWords.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=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 noPadding col-sm-12 col-lg-12 col-md-12 col-xs-12"); 
		newImage.setAttribute("src",Utils.Path+"images/skin/star1.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
	$("#starDiv").css("visibility","hidden");
};
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 pointerClass 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)";
		$(gameMachineDiv).click(function(e) {
			RhymingWords.checkAnswer(this);
		 });
		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  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)";
		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);

		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/plain_Sound.png");
		$(wordSoundDiv).data("ans", j);
		$(wordSoundDiv).click(function(e) {
			e.stopImmediatePropagation();
			RhymingWords.playOptions(this);
		 });
		wordSoundDiv.appendChild(wordSoundimg);
	} 
}
RhymingWords.showObjects = function () {							//display objects on screen
	var d;
	RhymingWords.optionCnt = 0;
	RhymingWords.skipFlag=true;
	RhymingWords.objPointerFlag = true;
	shuffleArray(RhymingWords.mainArr[queCnt].combineQue);
	$("#nextImage").css({ "pointer-events": "none" });
	$(".pointerClass").css({ "pointer-events": "none" });
	$("#gamepage").show();
	RhymingWords.homeFlag = "showlevel";
	$(".textFontClass").text('');
	$("#gameOverDiv").css("visibility", "hidden");
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
		
	for (var j = 0; j < 3; j++) {			//display text & set data to text
		var index=0;
		$("#gameMachineDiv" + j).data("ans", RhymingWords.mainArr[queCnt].combineQue[j].word);
		for(var k=0;k<RhymingWords.mainArr[queCnt].combineQue[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.mainArr[queCnt].combineQue[j].word[k]);
			$("#spanDiv" + j).append(spanEle);
		}
		index=RhymingWords.mainArr[queCnt].combineQue[j].word.lastIndexOf(RhymingWords.mainArr[queCnt].suffix);
		for(;index<RhymingWords.mainArr[queCnt].combineQue[j].word.length;index++)
			$("#spanEle"+index+j).css("color","rgb(243, 42, 10)");			//suffix in red color
	}
	questionId = parseInt(RhymingWords.mainArr[queCnt].ques.questionId);
	RhymingWords.playInstruction();
}
RhymingWords.playInstruction = function () {				// plays instruction/option sounds
	RhymingWords.soundFlag = true;
	RhymingWords.seconds=0;
	clearTimeout(RhymingWords.timeOut);
	clearInterval(RhymingWords.noResponseTimer);
	$("#nextImage").css({ "pointer-events": "auto" });
	if (RhymingWords.objPointerFlag)
		$(".pointerClass").css({ "pointer-events": "none" });
	getDuration(Utils.Path + 'sounds/instruction/' + RhymingWords.hardcoded.instruction);
}
function getDuration(src) {			//gets duration of sound 
	var duration = 0;
	if (RhymingWords.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			RhymingWords.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
				RhymingWords.playNextSound(duration);
		});
		$('#playSound').prop('src', src);
	}
}
RhymingWords.playNextSound = function (duration)								//function for instruction
{
	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.mainArr[queCnt].ques.sound
		document.getElementById('playSound').play();
		setTimeout(function () {
			if (RhymingWords.objPointerFlag) {
				RhymingWords.objPointerFlag = false;
				$(".pointerClass").css({ "pointer-events": "auto" });
			}
		}, duration * 800);
		RhymingWords.startTimer();
	}, duration * 1000);
}
RhymingWords.startTimer=function()
{
	clearTimeout(RhymingWords.instructionTimer);
	$("#nextImage").css({ "pointer-events": "auto" });
	if(RhymingWords.noResponseTimer)
	{
		clearInterval(RhymingWords.noResponseTimer);
		RhymingWords.noResponseTimer=null;
		RhymingWords.seconds=0;
	}	
	RhymingWords.noResponseTimer=setInterval(function() 
	{
		RhymingWords.seconds++;
		if(RhymingWords.seconds>=7)
		{
			clearTimeout(RhymingWords.soundTimer);
			RhymingWords.soundTimer=null;
			document.getElementById("playSound").src=Utils.Path+"sounds/instruction/"+RhymingWords.hardcoded.noResponce;
			document.getElementById("playSound").play();
			$(".pointerClass").css("pointer-events","auto");
			clearInterval(RhymingWords.noResponseTimer)
			if(RhymingWords.timeOut)
			{
				clearTimeout(RhymingWords.timeOut);
				RhymingWords.timeOut=null;
			}
			RhymingWords.timeOut=setTimeout(function()
			{
				RhymingWords.seconds=0;
				RhymingWords.startTimer();
			},2000);
		}
	},1000);
} 
RhymingWords.checkAnswer = function (element) {						//Check Answer
	var randomSound;
	RhymingWords.skipFlag=false;
	clearTimeout(RhymingWords.instructionTimer);
	clearInterval(RhymingWords.noResponseTimer);
	
	$(".pointerClass,#soundDiv").css({ "pointer-events": "none" });
	if ($(element).data('ans') ==RhymingWords.mainArr[queCnt].ques.word) {
		scoredMarks = 10;
		correctCnt++;
		$(element).addClass("animated zoomIn");
		randomSound = Math.floor(Math.random() * (RhymingWords.correctAns.length));
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + RhymingWords.correctAns[randomSound];
		document.getElementById('playSound').play();
		
		console.log(RhymingWords.mainArr[queCnt].ques.word,totalLength,type);
		if(Utils.mobileDeviceFlag)
			Android.addLearntData(RhymingWords.mainArr[queCnt].ques.word,totalLength,type);
	}
	else {
		scoredMarks = 0;
		$(element).css({ "opacity":"0.7"});
		$("#spanDiv"+$($(element).children()[1].children).data("ans")).addClass("animated shake");
		randomSound = Math.floor(Math.random() * (RhymingWords.wrongAns.length));
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + RhymingWords.wrongAns[randomSound];
		document.getElementById('playSound').play();
	}
	RhymingWords.calculateScore();
	RhymingWords.mainArr.splice(queCnt,1);
	if (RhymingWords.nextQ) {
		clearTimeout(RhymingWords.nextQ);
		RhymingWords.nextQ = null;
	}
	RhymingWords.nextQ = setTimeout(function () {
		$(element).children().removeClass("animated zoomIn shake");
		RhymingWords.nextQuestion();
	}, 3000);
}
RhymingWords.nextQuestion = function () {						//Loads Next Question
	
	RhymingWords.skipCnt++;
	if(RhymingWords.skipFlag)
		queCnt++;
	clearTimeout(RhymingWords.nextQ);
	clearTimeout(RhymingWords.instructionTimer);
	clearInterval(RhymingWords.noResponseTimer);
	clearTimeout(RhymingWords.timeOut);
	$(".gameMachineClass,.textFontClass").removeClass("animated zoomIn spaceInUp shake");
	document.getElementById('playSound').pause();
	$(".pointerClass").css({"pointer-events": "auto","opacity":"1"});
	if(RhymingWords.mainArr.length==0)
		RhymingWords.lastPage();
	else if ( queCnt == RhymingWords.mainArr.length ) {
		$('#responseBoxDiv').show();
		$("#soundDiv").css("visibility", "hidden");
		$('#questionMsg').text(RhymingWords.hardcoded.message);
	}
	else
		RhymingWords.showObjects();
}
RhymingWords.showNext=function(element)
{
	if($(element).text()=="No")
		RhymingWords.lastPage();
	else
		RhymingWords.showRemaining();
}
RhymingWords.lastPage=function()
{
	clearInterval(RhymingWords.noResponseTimer);
	$('#responseBoxDiv,#gamepage').hide();
	$('#endpage').show();
	$("#gameOverDiv").text(RhymingWords.hardcoded.gameOver);
	$("#gameOverDiv").css("visibility", "visible");
	$("#soundDiv").css("visibility", "hidden");
	RhymingWords.giveStars();
	console.log(correctCnt,RhymingWords.skipCnt);
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(correctCnt,RhymingWords.skipCnt,"7");
}
RhymingWords.giveStars=function()
{
	var i,numberOfStars=correctCnt;
	for(i=1;i<=numberOfStars;i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/skin/star2.png");
	$("#starDiv").css("visibility","visible");
	if(correctCnt!=0)
	{
		document.getElementById('playSound').src=Utils.Path + 'sounds/instruction/'+'Star'+correctCnt+'.mp3';
		document.getElementById('playSound').play();
	}
};
RhymingWords.showRemaining=function()
{
	queCnt=0;
	$('#responseBoxDiv').hide();
	$('#gamepage').show();
	$("#soundDiv").css("visibility", "visible");
	RhymingWords.showObjects();
}
RhymingWords.calculateScore = function () {
	console.log(resId, questionId, scoredMarks, totalMarks,levelNumber, startTime, RhymingWords.mainArr[queCnt].ques.word);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks,levelNumber, startTime, RhymingWords.mainArr[queCnt].ques.word);
}
RhymingWords.nextGame=function()
{
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}