//April 10th 2019
'use strict'
var ThikThak={};
var Utils = {};
Utils.Path='';
Utils.mobileDeviceFlag=false;
ThikThak.loadmetaDataFlag=false;
ThikThak.wordsBreakFlag=false;
ThikThak.punctArr=['.',',','?','!'];
ThikThak.indexOfWords=[];
ThikThak.hideIndex=[];
ThikThak.highlightIndex=[];
ThikThak.sentenceArr=[];
ThikThak.tempArr=[];
ThikThak.Quecounter=0;
ThikThak.skipCount=0;
ThikThak.seconds=0;
ThikThak.correct=0;
ThikThak.correctAnswers=0;
ThikThak.totalQuestions=2;
ThikThak.counter=0,ThikThak.correctCnt=0,ThikThak.noOfWords=0,ThikThak.filledBlanksCnt=0;
var questionId=0,startTime=0,scoredMarks=0,resId=0,totalMarks=10;
$(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("ThikThak");   */
	setTimeout(function()
	{
		ThikThak.init();
	},100);
},200);
ThikThak.init=function()
{
	$('#gamePage,#endPage').hide();
	ThikThak.setImages();
	ThikThak.setFonts();
	ThikThak.createStars();
	ThikThak.setHardcodedData();
};
// set Images//
ThikThak.setImages=function()
{
	document.getElementById('play').src=Utils.Path+"images/skin/Play.png";
	document.getElementById('homeImage').src=Utils.Path+"images/skin/Home.png";
	document.getElementById('logoImage').src=Utils.Path+"images/skin/logo.png";
	document.getElementById('soundImg').src=Utils.Path+"images/skin/Sound.png";
	document.getElementById('breakImg').src=Utils.Path+"images/skin/Hammer.png";
	document.getElementById('nextImg').src=Utils.Path+"images/skin/Skip.png"; 
	document.getElementById('nextGameImg').src=Utils.Path+"images/skin/Next.png"; 
	document.body.style.backgroundImage="url("+Utils.Path+"images/skin/cover.jpg)";
	document.getElementById('storyDiv').style.backgroundImage="url("+Utils.Path+"images/skin/Wood-Frame.png)";
};
//function which sets font family
ThikThak.setFonts=function()
{
	var newStyle = "<style>"+
			"@font-face {  "+
			  "font-family: 'Roboto';"  +
				"src: url('fonts/Roboto-BoldItalic.ttf') format('truetype');"+
				"}  </style>";
	$("head").append(newStyle);    
	$("#storyDiv,#dragWords").css("font-family","Roboto");  
};
//set hardcoded data
ThikThak.setHardcodedData=function()
{
	$("#gameOverText").text(ThikThak.hardcodedData.gameover);
	$("#questionMsg").text(ThikThak.hardcodedData.modalMsg);
	$("#Yes").text("Yes");
	$("#No").text("No");
};
//function which executes on play button click
ThikThak.playGame=function()
{
	$('#coverPage').hide();
	$('#logoImage,#gamePage').show();
	ThikThak.tempArr=populate(ThikThak.data,ThikThak.tempArr,2);
	ThikThak.showQuestion();
	setTimeout(function(){ThikThak.playStanza();},700);
	document.body.style.backgroundImage="url("+Utils.Path+"images/skin/bg.png)";
};
//function which sets question
ThikThak.showQuestion=function()
{
	var sentenceArr=[],rowCount=1,index=0,row;
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	ThikThak.sentenceArr=ThikThak.removePunctuation();
	row=document.createElement('div');
	row.id="row"+rowCount;
	row.className="text-center nopadding rowclass col-sm-12 col-md-12 col-lg-12 col-xs-12";
	row.style.backgroundImage="url("+Utils.Path+"images/skin/Wood_pati_1.png)";
	document.getElementById('storyDiv').appendChild(row);
	
	for(var i=0;i<ThikThak.sentenceArr.length;i++)
	{
		var span=document.createElement('span');
		span.className="nopadding text-center text-bold spanClass";
		span.id="span"+i;
		span.innerHTML=ThikThak.sentenceArr[i].replace(/(\r\n|\n|\r)/gm, "");
		span.setAttribute('onclick','ThikThak.playWord(this.id)');
		document.getElementById('row'+rowCount).appendChild(span);
		if(ThikThak.punctArr.includes(ThikThak.sentenceArr[i]))
		{
			$(span).addClass('punctuation');
			if(i!=(ThikThak.sentenceArr.length-1))
			{
				rowCount++;
				row=document.createElement('div');
				row.id="row"+rowCount;
				row.className="text-center nopadding rowclass col-sm-12 col-md-12 col-lg-12 col-xs-12";
				row.style.backgroundImage="url("+Utils.Path+"images/skin/Wood_pati_1.png)";
				document.getElementById('storyDiv').appendChild(row);	
			}
		}	
		else
		{
			span.setAttribute('index',index);
			$(span).data('dropFlag',"off");
			span.setAttribute('duration',ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[index].wordDuration);
			span.setAttribute('from',ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[index].wordFrom);
			span.setAttribute('to',ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[index].wordTo);
			$(span).css('margin-left','2vw');
			$(span).css('border-bottom','0.3vw dashed white');	
			index++;
		}
	}
	ThikThak.noOfWords=index;
	$("#breakDiv").addClass('blink_me');
};
//function which seperates punctuations from words 
ThikThak.removePunctuation=function()
{
	var flag=0,str,sentenceArr=[],tempArr=[];
	questionId=ThikThak.tempArr[ThikThak.Quecounter].questionId;
	ThikThak.sentenceArr=ThikThak.tempArr[ThikThak.Quecounter].pageList[0].paraText.split(' ');
	ThikThak.getFirstFourSentences();
	for(var i=0;i<ThikThak.sentenceArr.length;i++)
	{
		flag=0;
		str=ThikThak.sentenceArr[i];
		str=str.trim();
		for(var j=0;j<ThikThak.punctArr.length;j++)
		{
			// here we remove punctuation from word & put word and punctuation at seperate index in array
			if(ThikThak.sentenceArr[i].indexOf(ThikThak.punctArr[j])!= -1)
			{	
				str = str.replace(ThikThak.punctArr[j],"");
				tempArr.push(str);
				if(str.length>3)
				ThikThak.indexOfWords.push(tempArr.length-1); 
				ThikThak.highlightIndex.push(tempArr.length-1);
				tempArr.push(ThikThak.punctArr[j]);
				flag=1;
				break;	
			}
		}
		if(flag!=1){
			tempArr.push(str);
			if(str.length>1)
			ThikThak.indexOfWords.push(tempArr.length-1);
			ThikThak.highlightIndex.push(tempArr.length-1);
			flag=0;
		}		
	}
	return tempArr;
};
//function which gets first four sentences of text 
ThikThak.getFirstFourSentences=function()
{
	var counter=0; 
	for(var i=0;i<ThikThak.sentenceArr.length;i++)
	{ 
		if(ThikThak.sentenceArr[i].includes('.') || ThikThak.sentenceArr[i].includes('?'))
		{
			counter++;
			if(counter==4)
			 ThikThak.sentenceArr.splice(i+1,ThikThak.sentenceArr.length-1) // remove remaining sentences in paragraphs 
		}
	}	
};
ThikThak.playParaOnClick=function()
{
	var playTime=0;
	if(ThikThak.pauseStoryAudio)
	{
		clearTimeout(ThikThak.pauseStoryAudio);
		ThikThak.pauseStoryAudio=null;
	}
	if(ThikThak.highlightTimer)
	{
		clearTimeout(ThikThak.highlightTimer);
		ThikThak.highlightTimer=null;
		ThikThak.counter=0;
	}
	$('.scaleClass').removeClass('scaleClass');
	document.getElementById('playSound').src=Utils.Path+"sounds/"+ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readPageAudio;
	playTime=ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[ThikThak.noOfWords-1].wordTo-ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[0].wordFrom;
	document.getElementById('playSound').currentTime=ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[0].wordFrom;
	document.getElementById("playSound").play();
	ThikThak.pauseStoryAudio=setTimeout(function()
	{
		ThikThak.startTimer();
		document.getElementById("playSound").pause();	
		if(ThikThak.wordsBreakFlag==false)
			ThikThak.breakWords();
	},playTime*1000);
};
//function which plays stanza audio
ThikThak.playStanza=function()
{
	ThikThak.playParaOnClick();
	ThikThak.playWordsOnebyOne();
};
//function which plays words one by one
ThikThak.playWordsOnebyOne=function()
{ 
	$('.scaleClass').removeClass('scaleClass');
	ThikThak.playTime=ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[ThikThak.counter].wordDuration;
	$("#span"+ThikThak.highlightIndex[ThikThak.counter]).addClass('scaleClass');
	if(ThikThak.highlightTimer){
		clearTimeout(ThikThak.highlightTimer);
		ThikThak.highlightTimer=null;
	}
	ThikThak.highlightTimer=setTimeout(function()
	{
		if(ThikThak.counter<ThikThak.noOfWords-1)
		{
			ThikThak.counter++;
			ThikThak.playWordsOnebyOne();
			return 0;
		}
		else
		{
			$('.scaleClass').removeClass('scaleClass');
			ThikThak.counter=0;
			$('.spanClass').css('pointer-events','auto');
			document.getElementById('playSound').pause();
		}	
	},ThikThak.playTime*1000);
};
//function which play word audio on word click
ThikThak.playWord=function(obj)
{
	document.getElementById("playSound").pause();
	document.getElementById("playSound").src=Utils.Path+"sounds/"+ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readPageAudio;
	ThikThak.playTime=document.getElementById(obj).getAttribute('duration');
	document.getElementById('playSound').currentTime=document.getElementById(obj).getAttribute('from');
	document.getElementById("playSound").play();
	ThikThak.pauseWordAudio=setTimeout(function()
	{
		document.getElementById('playSound').pause();
	},ThikThak.playTime*1000);
};
//function which drops words down 
ThikThak.breakWords=function()
{
	document.getElementById('playSound').pause();
	if(ThikThak.highlightTimer){
		clearTimeout(ThikThak.highlightTimer);
		ThikThak.highlightTimer=null;
	}
	ThikThak.wordsBreakFlag=true;
	$('.spanClass').css('pointer-events','auto');
	$('.scaleClass').removeClass('scaleClass');
	$("#dragWords").css('visibility','visible');
	$("#breakDiv").removeClass('blink_me');
	$('#breakImg').css('pointer-events','none');
	ThikThak.getWordsToHide();
	ThikThak.createSpansToDrag();
	document.getElementById("playSound").src=Utils.Path+"sounds/glassBreak.wav";
	document.getElementById("playSound").play();
};
//function which hides the words 
ThikThak.getWordsToHide=function()
{	
	var random;
	for(var i=0;i<8;i++)
	{
		random=Math.floor(Math.random()*ThikThak.indexOfWords.length);
		while($.inArray(ThikThak.indexOfWords[random],ThikThak.hideIndex)!=-1)
			random=Math.floor(Math.random()*ThikThak.indexOfWords.length);
		ThikThak.hideIndex.push(ThikThak.indexOfWords[random]);
	}	
	for(var i=0;i<ThikThak.hideIndex.length;i++)
	{
		$("#span"+ThikThak.hideIndex[i]).css('color','transparent');
		$("#span"+ThikThak.hideIndex[i]).addClass('dropClass');
	}	
	$('.dropClass').droppable({
		drop:ThikThak.handleDrop
	});
};
//function create option spans
ThikThak.createSpansToDrag=function(event,ui)
{  var span,div,index;
	for(var i=0;i<ThikThak.hideIndex.length;i++)
	{
		div=document.createElement('div');
		div.className="nopadding col-sm-1 col-md-1 col-lg-1 col-xs-1 col-xs-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-offset-1";
		div.style.height="3vh";
		div.style.marginTop="3vh";
		span=document.createElement('span');
		span.className="nopadding text-center text-bold spanClass";
		span.id="word"+i;
		$(span).draggable(
		{	
			revert:'invalid',
			start: function(event, ui){
				if(ThikThak.noResponseTimer)
				{
					clearInterval(ThikThak.noResponseTimer);
					ThikThak.noResponseTimer=null;
					ThikThak.seconds=0;
					ThikThak.startTimer();
				}
				if(ThikThak.timeOut)
				{
					clearTimeout(ThikThak.timeOut);
					ThikThak.timeOut=null;
				}
			}
		});
		index=document.getElementById('span'+ThikThak.hideIndex[i]).getAttribute('index');
		span.setAttribute('duration',ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[index].wordDuration);
		span.setAttribute('from',ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[index].wordFrom);
		span.setAttribute('to',ThikThak.tempArr[ThikThak.Quecounter].pageList[0].readList[index].wordTo);
		span.innerHTML=ThikThak.sentenceArr[ThikThak.hideIndex[i]].replace(/(\r\n|\n|\r)/gm,"");
		span.setAttribute('onclick','ThikThak.playWord(this.id)');
		div.appendChild(span);
		document.getElementById('dragWords').appendChild(div);
	}
	$('.spanClass').css('pointer-events','auto');
	$('.spanClass').addClass('tracking-in-expand');
};
//function which calls on drop
ThikThak.handleDrop=function(event,ui)
{
	var src,dstSpan,destId; 
	src=ui.draggable;	
	dstSpan=$(this);
	if($(src).text().toLowerCase()==$(dstSpan).text().toLowerCase())
	{
		ThikThak.filledBlanksCnt++;
		 if($(dstSpan).data('dropFlag')=="off")
			ThikThak.correctCnt++; 
		$(this).css('color','');
		$(src).remove();
		$(dstSpan).addClass('greenColor');
		setTimeout(function(){
			$(dstSpan).removeClass('greenColor');
		},800);
		document.getElementById('playSound').src=Utils.Path+"sounds/instructions/ting.mp3";
		document.getElementById('playSound').play();
		if(ThikThak.filledBlanksCnt==ThikThak.hideIndex.length)
		{
			 if(Utils.mobileDeviceFlag)
				Android.addLearntData(ThikThak.tempArr[ThikThak.Quecounter].paraTitle,ThikThak.data.length,"paragraph"); 
			document.getElementById('playSound').src=Utils.Path+"sounds/instructions/Weldone.mp3";
			document.getElementById('playSound').play();
			ThikThak.calculateScore();
			ThikThak.tempArr.splice(ThikThak.Quecounter,1);
			ThikThak.nextQueTimer=setTimeout(function(){ThikThak.nextQuestion();},2000);
		}
	}
	else
	{
		document.getElementById('playSound').pause();
		document.getElementById('playSound').src=Utils.Path+"sounds/instructions/No__that's_wrong__Aditi.mp3";
		document.getElementById('playSound').play();
		$(src).draggable("option", "revert", true);
	}	
	if(ThikThak.noResponseTimer)
	{
		clearInterval(ThikThak.noResponseTimer);
		ThikThak.noResponseTimer=null;
		ThikThak.seconds=0;
	}
	if(ThikThak.timeOut)
	{
		clearTimeout(ThikThak.timeOut);
		ThikThak.timeOut=null;
	}
	ThikThak.startTimer();
	$(dstSpan).data('dropFlag','on');
};
ThikThak.skipQuestion=function()
{
	ThikThak.skipCount++;
	ThikThak.Quecounter++;
	if(ThikThak.tempArr.length==ThikThak.Quecounter)
	{
		if(ThikThak.pauseStoryAudio)
		{
			clearTimeout(ThikThak.pauseStoryAudio);
			ThikThak.pauseStoryAudio=null;
		}
		if(ThikThak.highlightTimer)
		{
			clearTimeout(ThikThak.highlightTimer);
			ThikThak.highlightTimer=null;
			ThikThak.counter=0;
		}
		if(ThikThak.noResponseTimer)
		{
			clearInterval(ThikThak.noResponseTimer);
			ThikThak.noResponseTimer=null;
			ThikThak.seconds=0;
		}
		if(ThikThak.timeOut)
		{
			clearTimeout(ThikThak.timeOut);
			ThikThak.timeOut=null;
		}
		document.getElementById('playSound').pause();
		$("#responseBoxDiv").show();
	}
	else
		ThikThak.nextQuestion();	
};
ThikThak.showSkippedQuestions=function()
{
	document.getElementById('playSound').pause();
	ThikThak.skipCount=0;
	ThikThak.Quecounter=0;
	ThikThak.indexOfWords=[],ThikThak.hideIndex=[],ThikThak.sentenceArr=[],ThikThak.highlightIndex=[],ThikThak.correctCnt=0,ThikThak.counter=0,ThikThak.filledBlanksCnt=0;
	$("#responseBoxDiv").hide();
	$("#storyDiv").empty();
	$('#dragWords').empty();
	ThikThak.showQuestion();
	ThikThak.playStanza();
	$('#breakImg').css('pointer-events','auto');
};
//function which calls on next btn click
ThikThak.nextQuestion=function()
{	
	if(ThikThak.noResponseTimer)
	{
		clearInterval(ThikThak.noResponseTimer);
		ThikThak.noResponseTimer=null;
		ThikThak.seconds=0;
	}
	if(ThikThak.pauseStoryAudio)
	{
		clearTimeout(ThikThak.pauseStoryAudio);
		ThikThak.pauseStoryAudio=null;
	}	
	if(ThikThak.nextQueTimer)
	{
		clearTimeout(ThikThak.nextQueTimer);
		ThikThak.nextQueTimer=null;
	}
	
	if(ThikThak.Quecounter<ThikThak.tempArr.length)
	{
		$("#dragWords").css('visibility','hidden');
		ThikThak.indexOfWords=[],ThikThak.hideIndex=[],ThikThak.sentenceArr=[],ThikThak.highlightIndex=[],ThikThak.correctCnt=0,ThikThak.counter=0,ThikThak.filledBlanksCnt=0;
		ThikThak.wordsBreakFlag=false;
		$("#soundDiv").show();
		$("#storyDiv").empty();
		$('.spanClass').css('pointer-events','auto');
		$('#dragWords').empty();
		$('#breakImg').css('pointer-events','auto');
		ThikThak.showQuestion();
		ThikThak.playStanza();
	}
	else if(ThikThak.tempArr.length==ThikThak.Quecounter && ThikThak.tempArr!=0)
		$("#responseBoxDiv").show();
	else
		ThikThak.showEndPage();
};
ThikThak.showEndPage=function()
{
	document.getElementById('playSound').pause();
	if(ThikThak.noResponseTimer)
	{
		clearInterval(ThikThak.noResponseTimer);
		ThikThak.noResponseTimer=null;
		ThikThak.seconds=0;
	}
	if(ThikThak.timeOut)
	{
		clearTimeout(ThikThak.timeOut);
		ThikThak.timeOut=null;
	}

	ThikThak.giveStars();
	$("#responseBoxDiv").hide();
	$("#gamePage").hide();
	$("#endPage").show();
};
ThikThak.resetVariables=function()
{
	ThikThak.Quecounter=0;
	ThikThak.wordsBreakFlag=false;
	ThikThak.indexOfWords=[],ThikThak.hideIndex=[],ThikThak.sentenceArr=[],ThikThak.highlightIndex=[],ThikThak.correctCnt=0,ThikThak.counter=0,ThikThak.filledBlanksCnt=0;
};
ThikThak.calculateScore=function()
{
	if(ThikThak.hideIndex.length==ThikThak.correctCnt)
	{
		ThikThak.correctAnswers++;
		ThikThak.correct=8;
	}	
	console.log(resId,questionId,ThikThak.hideIndex.length,ThikThak.correct,1,startTime);
	 if(Utils.mobileDeviceFlag)
		Android.addScore(resId,parseInt(questionId),ThikThak.hideIndex.length,ThikThak.correct,1,startTime); 
};
//function which executes on home button click
ThikThak.goToHome=function()
{
	if(ThikThak.noResponseTimer)
	{
		clearInterval(ThikThak.noResponseTimer);
		ThikThak.noResponseTimer=null;
		ThikThak.seconds=0;
	}
	if(ThikThak.timeOut)
	{
		clearTimeout(ThikThak.timeOut);
		ThikThak.timeOut=null;
	}
	location.reload(true);	
};	
//function android call to the next game
ThikThak.nextGame=function()
{
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame(); 
};
//function which plays the NoResponse audio
ThikThak.startTimer=function()
{
	if(ThikThak.noResponseTimer)
	{
		clearInterval(ThikThak.noResponseTimer);
		ThikThak.noResponseTimer=null;
		ThikThak.seconds=0;
	}	
	ThikThak.noResponseTimer=setInterval(function() 
	{
		ThikThak.seconds++;
		if(ThikThak.seconds>=7)
		{
			document.getElementById("playSound").src=Utils.Path+"sounds/please_ans_the_ques.mp3";
			document.getElementById("playSound").play(); 
			clearInterval(ThikThak.noResponseTimer)
			if(ThikThak.timeOut)
			{
				clearTimeout(ThikThak.timeOut);
				ThikThak.timeOut=null;
			}
			ThikThak.timeOut=setTimeout(function()
			{
				ThikThak.seconds=0;
				ThikThak.startTimer();
			},2000);
		}
	},1000);
}; 
//function which creates star divs
ThikThak.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=2;
	for(i=1;i<=Math.floor(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);
		$("#starsDiv").append(newDiv);
	}
};
//function which calculate's star count
ThikThak.giveStars=function()
{
	var numberOfStars=0,temp; 
	temp=ThikThak.correctAnswers/1;
	numberOfStars=Math.floor(temp);
	temp=Math.round(temp);
	console.log(numberOfStars);
	console.log(temp);
	for(var i=1;i<=Math.floor(numberOfStars);i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/skin/star2.png");
	/* if(temp>numberOfStars)
	document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/halfStar.png"); */
	$("#starsDiv").css("visibility","visible");
	if(numberOfStars!=0)
	{
		document.getElementById("playSound").src=Utils.Path+"sounds/instructions/"+"star"+numberOfStars+".mp3";
		document.getElementById("playSound").play();
	} 
	console.log(ThikThak.correctAnswers,ThikThak.totalQuestions,"2");
	if(Utils.mobileDeviceFlag) 
		Android.StudentCertification(ThikThak.correctAnswers,ThikThak.totalQuestions,"9");
};

