//April 10th 2019
'use strict'
var ThikThak={};
var Utils = {};
Utils.Path='';
Utils.mobileDeviceFlag=false;
ThikThak.loadmetaDataFlag=false;
ThikThak.wordsBreakFlag=false;
ThikThak.skipFlag=true;
ThikThak.attemptFlag=false;
ThikThak.showCreditFlag=false;
ThikThak.punctArr=['.',',','?','!'];
ThikThak.indexOfWords=[];
ThikThak.hideIndex=[];
ThikThak.highlightIndex=[];
ThikThak.sentenceArr=[];
ThikThak.tempArr=[];
ThikThak.queCounter=0;
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))
		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.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/Next.png"; 
	document.getElementById('replayImg').src=Utils.Path+"images/skin/Replay.png"; 
	document.getElementById('creditImg').src=Utils.Path+"images/skin/credits.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);
	$('#conceptBy').text(ThikThak.hardcodedData.concept_by);
	$('#mediacontent').text(ThikThak.hardcodedData.mediacontent);
	$('#artWork').text(ThikThak.hardcodedData.art_work);
	$('#animations').text(ThikThak.hardcodedData.animation);
	$('#music').text(ThikThak.hardcodedData.music);
	$('#developerName').text(ThikThak.hardcodedData.developed_by);
	$('#date').text(ThikThak.hardcodedData.date);
};
//function which executes on play button click
ThikThak.playGame=function()
{	
	$('#coverPage,#animalsCard,#Card').hide();
	$('#homeImage').css('visibility','visible');
	$('#logoImage,#gamePage').show();
	ThikThak.tempArr=populate(ThikThak.data,ThikThak.tempArr,5);
	console.log(ThikThak.tempArr);
	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();
	ThikThak.skipFlag=true;
	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=[];
	console.log(ThikThak.queCounter);
	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()
	{
		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){
				ThikThak.attemptFlag=true;
			}
		});
		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; 
	ThikThak.attemptFlag=true;
	ThikThak.skipFlag=false;
	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.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);
	}
		
	$(dstSpan).data('dropFlag','on');
};
//function which calls on next btn click
ThikThak.nextQuestion=function()
{	
	ThikThak.queCounter++;
	clearTimeout(ThikThak.pauseStoryAudio);
	clearTimeout(ThikThak.highlightTimer);
	clearTimeout(ThikThak.nextQueTimer);
	if(ThikThak.attemptFlag)
	{
		ThikThak.attemptFlag=false;
		ThikThak.calculateScore();
	}
	if(ThikThak.skipFlag)
	{
		ThikThak.correctCnt=-1;
		ThikThak.calculateScore();
	}
	if(ThikThak.queCounter<5)
	{
		ThikThak.resetVariables();
		$("#dragWords").css('visibility','hidden');
		$("#soundDiv").show();
		$("#storyDiv").empty();
		ThikThak.showQuestion();
		ThikThak.playStanza();
	}
	else
		ThikThak.showEndPage();
};
//function which shows last page of game
ThikThak.showEndPage=function()
{
	document.getElementById('playSound').pause();
	if(ThikThak.pauseStoryAudio)
	{
		clearTimeout(ThikThak.pauseStoryAudio);
		ThikThak.pauseStoryAudio=null;
	}	
	$("#gamePage").hide();
	$("#endPage").show();
};
//function which restart game again
ThikThak.replay=function()
{
	$("#gamePage").show();
	$("#endPage").hide();
	$("#storyDiv").empty();
	ThikThak.resetVariables();
	ThikThak.queCounter=0;
	ThikThak.skipFlag=true;
	ThikThak.attemptFlag=false;
	ThikThak.showCreditFlag=false;
	ThikThak.tempArr=[];
	ThikThak.tempArr=populate(ThikThak.data,ThikThak.tempArr,5);
	ThikThak.showQuestion();	
	ThikThak.playStanza();
};
ThikThak.resetVariables=function()
{
	ThikThak.wordsBreakFlag=false;
	$('.spanClass').css('pointer-events','auto');
	$('#dragWords').empty();
	$('#breakImg').css('pointer-events','auto');
	ThikThak.indexOfWords=[],ThikThak.hideIndex=[],ThikThak.sentenceArr=[],ThikThak.highlightIndex=[],ThikThak.correctCnt=0,ThikThak.counter=0,ThikThak.filledBlanksCnt=0;
};
//function which shows credits
ThikThak.showCredits=function()
{
	if(ThikThak.showCreditFlag)
	{
		$("#gameOverText").show();
		$("#acknowledgementDiv").css('visibility','hidden');	
		ThikThak.showCreditFlag=false;
	}	
	else if(ThikThak.showCreditFlag==false)
	{
		ThikThak.showCreditFlag=true;
		$("#gameOverText").hide();
		$("#acknowledgementDiv").css('visibility','visible');	
	}	
};	
ThikThak.calculateScore=function()
{
	ThikThak.attemptFlag=false;
	console.log(resId,questionId,ThikThak.correctCnt,ThikThak.hideIndex.length,1,startTime);
	 if(Utils.mobileDeviceFlag)
		Android.addScore(resId,parseInt(questionId),ThikThak.correctCnt,ThikThak.hideIndex.length,1,startTime); 
};
//function which executes on home button click
ThikThak.goToHome=function()
{
	if(ThikThak.attemptFlag)
	{
		ThikThak.attemptFlag=false;
		ThikThak.calculateScore();
	}
	location.reload(true);	
};	


