//7th May 2019
var Preposition={};
var Utils = {};
Utils.Path='';
Utils.mobileDeviceFlag=false;
Preposition.loadmetaDataFlag=false;
Preposition.recordClickFlag=false;
Preposition.questionAudio;
Preposition.counter=0;
Preposition.skipCount=0;
Preposition.seconds=0;
Preposition.answer="";
Preposition.tempArr=[];
Preposition.punctArr=['.',',','?','!'];
Preposition.wordsToBeChecked="";
Preposition.wrongCnt=0;
Preposition.timeOut=null;
Preposition.correctCnt=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("Preposition");   */
	setTimeout(function()
	{
		Preposition.init();
		Preposition.setImages();
		Preposition.createStars();
		Preposition.harcodedData();
	},100);
},200);
Preposition.init=function()
{
	$('#gamePage,#endPage').hide();
};
Preposition.harcodedData=function()
{
	$("#gameOverText").text(Preposition.hardcodedData.gameover);
	$("#questionMsg").text(Preposition.hardcodedData.modalMsg);
	$("#Yes").text("Yes");
	$("#No").text("No");
	$('#conceptBy').text(Preposition.hardcodedData.concept_by);
	$('#artWork').text(Preposition.hardcodedData.art_work);
	$('#audioEditing').text(Preposition.hardcodedData.audio_editing);
	$('#music').text(Preposition.hardcodedData.music);
	$('#developerName').text(Preposition.hardcodedData.developed_by);
	$('#date').text(Preposition.hardcodedData.date);
}
// set Images//
Preposition.setImages=function()
{
	document.getElementById('play').src=Utils.Path+"images/Play.png";
	document.getElementById('homeImage').src=Utils.Path+"images/Home.png";
	document.getElementById('logoImage').src=Utils.Path+"images/logo.png";
	document.getElementById('soundImg').src=Utils.Path+"images/Sound.png";
	document.getElementById('recordImg').src=Utils.Path+"images/Record.png";
	document.getElementById('nextImg').src=Utils.Path+"images/Next.png";
	document.getElementById('nextGameDiv').src=Utils.Path+"images/Next.png";
	document.body.style.backgroundImage="url("+Utils.Path+"images/Cover.png)";
};
//function which executes on play button click
Preposition.playGame=function()
{
	$('#coverPage').hide();
	$('#homeImage,#imageDiv,#questionText').css('visibility','visible');
	$('#logoImage,#gamePage').show();
	Preposition.tempArr=populate(Preposition.data,Preposition.tempArr,5);
	console.log(Preposition.tempArr);
	Preposition.showQuestion();
	document.body.style.backgroundImage="url("+Utils.Path+"images/Background.png)";
};
//function which executes on play button click
Preposition.showQuestion=function()
{
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	Preposition.startTimer();
	questionId=Preposition.tempArr[Preposition.counter].questionId;
	console.log(questionId);
	$("#questionText").text(Preposition.tempArr[Preposition.counter].question);
	
	if(Preposition.tempArr[Preposition.counter].image==null)
		$("#imageOuterDiv").css('visibility','hidden');
	else
		$("#imageOuterDiv").css('visibility','visible');
	
	$("#imageOuterDiv").prop('src',Utils.Path+"images/"+Preposition.tempArr[Preposition.counter].image);
	Preposition.questionAudio=Preposition.tempArr[Preposition.counter].questionSound;
	Preposition.playQuestion();
	//$("#answerDiv").data('answerAudio',Preposition.tempArr[Preposition.counter].answerSound);
	$("#answerDiv").css('pointer-events','none');
	Preposition.wordsToBeChecked=Preposition.tempArr[Preposition.counter].wordstobechecked;
	Preposition.highlightPreposition(Preposition.tempArr[Preposition.counter].answer);
};
Preposition.playQuestion=function()
{
	document.getElementById('playSound').pause();
	sound=Utils.Path+"sounds/"+Preposition.questionAudio;
	Preposition.loadmetaDataFlag=true;
	callback=Preposition.playInstruction;
	Preposition.getAudioDuration(sound,callback);		
};
Preposition.playInstruction=function(duration)
{	
	document.getElementById('playSound').play();
	if(Preposition.instructionTimer)
	{
		clearTimeout(Preposition.instructionTimer);
		Preposition.instructionTimer=null;
	}
	Preposition.instructionTimer=setTimeout(function()
	{
		document.getElementById('playSound').src=Utils.Path+"sounds/Now_your_turn.mp3";
		document.getElementById('playSound').play();	
	},duration*1000);	
};
Preposition.playAnswerAudio=function()
{
	document.getElementById('playSound').pause();
	document.getElementById('playSound').src=Utils.Path+"sounds/"+$("#answerDiv").data('answerAudio');
	document.getElementById('playSound').play();
};
//function which highlights preposition in answer string
Preposition.highlightPreposition=function(str)
{
	var index=0,span,highlightStr="",word,preposition=[];
	str=str.trim();
	arr=str.split(' ');
	preposition=Preposition.tempArr[Preposition.counter].preposition.split(' ');
	index=arr.indexOf(preposition[0].toLowerCase());
	for(var i=0;i<index;i++)
	{
		word = document.createTextNode(" "+arr[i]);
		document.getElementById('answerText').appendChild(word);
	}
	for(var i=index;i<arr.length;i++)
	{
		highlightStr=highlightStr+" "+arr[i];
	}
	span = document.createElement("span");
	span.setAttribute('id','highlight');
	$(span).css('color','green');	
	span.innerHTML=highlightStr;
	document.getElementById('answerText').appendChild(span);
};
//function which records the answer 
Preposition.record=function()
{
	$('#soundImg').css('pointer-events','none');
	if(Preposition.instructionTimer)
	{
		clearTimeout(Preposition.instructionTimer);
		Preposition.instructionTimer=null;
	}	
	document.getElementById('playSound').pause();
	Preposition.ansString="";
	if(Preposition.recordClickFlag==false)
	{
		Preposition.recordClickFlag=true;
		if(Utils.mobileDeviceFlag)
		Android.startSttArray("eng");
		$("#recordImg").prop('src',Utils.Path+"images/Stop.png");
		$("#recordImg").addClass("blink_me");
		if(Preposition.checkStatus)
		{
		   clearInterval(Preposition.checkStatus);
		   Preposition.checkStatus = null;
		}
		Preposition.checkStatus = setInterval(function() 
		{
			if (Utils.mobileDeviceFlag)
			Preposition.sttString = Android.getSttResult();
			console.log(Preposition.sttString);
			if('$$$'!== Preposition.sttString)
			{ 
				clearInterval(Preposition.checkStatus);
				if(Preposition.sttString !== "###" && Preposition.sttString !== "")
					Preposition.checkAnswer();
				else
				{
					console.log('Stops');
					$('#soundImg').css('pointer-events','auto');
				}
				Preposition.recordClickFlag = false;
				$("#recordImg").prop('src',Utils.Path+"images/Record.png");
				$('#recordImg').removeClass('blink_me');
			}
		},500);
	}
	else
	{
		Preposition.recordClickFlag = false;
		if(Utils.mobileDeviceFlag)
			Android.stopStt();
		Preposition.sttString="";
		clearInterval(Preposition.checkStatus);
		$("#recordImg").prop('src',Utils.Path+"images/Record.png");
		$("#recordImg").removeClass("blink_me");
	}
};
//function which checks answer
Preposition.checkAnswer=function()
{
	$('#soundImg').css('pointer-events','none');
	var arr=[],wordTocheck=[],answerArr=[],indexArr=[]
	var flag=0,index=0;
	Preposition.noOfTimesQuestionAnswered++;
	$("#recordImg").prop('src',Utils.Path+"images/Record.png");
	arr=Preposition.sttString.split(' ');
	for(var i=0;i<arr.length;i++)
		arr[i]=arr[i].toLowerCase(); // converting sttStringArr words to lowercase
	Preposition.wordsToBeChecked=Preposition.wordsToBeChecked.replace(/\s\s+/g, ' ');//replace multiple spaces in wordsToBeChecked with single space 
	Preposition.wordsToBeChecked=Preposition.wordsToBeChecked.toLowerCase();// converting wordsToBeChecked words to lowercase
	console.log(arr);
	arr=Preposition.removePunctuation(arr); //remove punctuations from sttStringArr as well as from wordsToBeChecked 
	/*alert(wordTocheck); */
	if(Preposition.wordsToBeChecked[Preposition.wordsToBeChecked.length-1]=="." || Preposition.wordsToBeChecked[Preposition.wordsToBeChecked.length-1]=="," || Preposition.wordsToBeChecked[Preposition.wordsToBeChecked.length-1]=="!")
		Preposition.wordsToBeChecked=Preposition.wordsToBeChecked.slice(0,Preposition.wordsToBeChecked.length-1);	
	alert(Preposition.wordsToBeChecked);
	wordTocheck=Preposition.wordsToBeChecked.split(' ');
	for(var i=0;i<wordTocheck.length;i++)
	{
		index=arr.indexOf(wordTocheck[i]); //here indexes are pushed of the words which includes in sttStringArr
		if(index>=0)
			indexArr.push(index);
	}
	for(var i=0;i<indexArr.length;i++)
	{	//here sequence of words are checked weather there are in correct sequence according to wordsToBeChecked
		if(indexArr[i]>indexArr[i+1]) 
		{
			flag=1;
			break;
		}
	}
	if(flag==1 || indexArr.length<wordTocheck.length)
	{
		alert("wrong"+arr+'\n'+wordTocheck+'\n'+indexArr+"\n"+indexArr.length+"\n"+wordTocheck.length);	
		//alert("wrong"+arr+'\n'+wordTocheck);
		scoredMarks=0;
		Preposition.calculateScore();
		document.getElementById("playSound").pause();
		if(Preposition.nextQueTimer)
		{
			clearTimeout(Preposition.nextQueTimer);
			Preposition.nextQueTimer=null;
		}
		Preposition.nextQueTimer=setTimeout(function(){
			Preposition.nextQuestion();
		},1500); 	
	}	
	else
	{
		alert("correct"+arr+'\n'+wordTocheck+'\n'+indexArr+"\n"+indexArr.length+"\n"+wordTocheck.length);
		console.log(Preposition.tempArr[Preposition.counter].answer+""+Preposition.data.length+" "+"sentence")
		/*  if(Utils.mobileDeviceFlag)
			Android.addLearntData(Preposition.tempArr[Preposition.counter].answer,Preposition.data.length,"sentence");  */
		//alert("correct"+arr+'\n'+wordTocheck);
		scoredMarks=10;
		Preposition.correctCnt++;
		Preposition.calculateScore();
		$('#recordImg').css('pointer-events','none');
		document.getElementById("playSound").pause(); 
		document.getElementById("playSound").src=Utils.Path+"sounds/correct.mp3";
		document.getElementById("playSound").play(); 
		if(Preposition.nextQueTimer)
		{
			clearTimeout(Preposition.nextQueTimer);
			Preposition.nextQueTimer=null;
		}
		Preposition.nextQueTimer=setTimeout(function(){
			Preposition.nextQuestion();
		},1500); 	
	}	
	Preposition.tempArr.splice(Preposition.counter,1);
};
Preposition.skipQuestion=function()
{
	Preposition.skipCount++;
	Preposition.counter++;
	if(Preposition.tempArr.length==Preposition.counter)
	{
		document.getElementById('playSound').pause();
		if(Preposition.instructionTimer)
		{
			clearTimeout(Preposition.instructionTimer);
			Preposition.instructionTimer=null;
		}
		$("#responseBoxDiv").show();
	}
	else
	{
		Preposition.nextQuestion();	
	}
};
Preposition.showSkippedQuestions=function()
{
	document.getElementById('playSound').pause();
	Preposition.counter=0;
	Preposition.skipCount=0;
	$("#responseBoxDiv").hide();
	Preposition.showQuestion();	
};
//function which removes punctuation
Preposition.removePunctuation=function(arr)
{
	var str="";
	str=arr[arr.length-1];
	for(var j=0;j<Preposition.punctArr.length;j++)
	{
		if(str.indexOf(Preposition.punctArr[j])!= -1)
		{
			str=str.replace(Preposition.punctArr[j],"");
			arr.splice(arr.length-1,1);
			arr.push(str);
		}
	}
	return arr;
};
//function which calculates score 
Preposition.calculateScore=function()
{
	console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
};
//function which executes on next button click
Preposition.nextQuestion=function()
{
	if(Preposition.noResponseTimer)
	{
		clearInterval(Preposition.noResponseTimer);
		Preposition.noResponseTimer=null;
		Preposition.seconds=0;
	}
	if(Preposition.instructionTimer)
	{
		clearTimeout(Preposition.instructionTimer);
		Preposition.instructionTimer=null;
	}	
	$("#recordImg").removeClass("blink_me");
	$("#recordImg").prop('src',Utils.Path+"images/Record.png");
	 if(Preposition.nextQueTimer)
	{
		clearTimeout(Preposition.nextQueTimer);
		Preposition.nextQueTimer=null;
	} 
	if(Preposition.counter<Preposition.tempArr.length)
	{
		if(Utils.mobileDeviceFlag)
			Android.stopStt();
		Preposition.recordClickFlag = false;
		$('#soundImg').css('pointer-events','auto');
		$('#recordImg').css('pointer-events','auto');
		$("#answerText").empty();
		Preposition.ansString="";
		Preposition.answer="";
		questionId=0,scoredMarks=0;
		clearInterval(Preposition.checkStatus);
		Preposition.showQuestion();	
	}
	else if(Preposition.tempArr.length==Preposition.counter && Preposition.tempArr !=0)
		$("#responseBoxDiv").show();
	else
		Preposition.showEndPage();
};
//function which shows last page of game
Preposition.showEndPage=function()
{
	if(Preposition.noResponseTimer)
	{
		clearInterval(Preposition.noResponseTimer);
		Preposition.noResponseTimer=null;
		Preposition.seconds=0;
	}
	Preposition.giveStars();
	$("#responseBoxDiv").hide();
	$("#gamePage").hide();
	$("#endPage").show();
};	
//function which executes on home button click
Preposition.goToHome=function()
{
	if(Preposition.noResponseTimer)
	{
		clearInterval(Preposition.noResponseTimer);
		Preposition.noResponseTimer=null;
		Preposition.seconds=0;
	}
	location.reload(true);	
};
//function which plays the NoResponse audio
Preposition.startTimer=function()
{
	if(Preposition.noResponseTimer)
	{
		clearInterval(Preposition.noResponseTimer);
		Preposition.noResponseTimer=null;
		Preposition.seconds=0;
	}	
	Preposition.noResponseTimer=setInterval(function() 
	{
		Preposition.seconds++;
		if(Preposition.seconds>=7)
		{
			document.getElementById("playSound").src=Utils.Path+"sounds/please_ans_the_ques.mp3";
			document.getElementById("playSound").play(); 
			clearInterval(Preposition.noResponseTimer)
			if(Preposition.timeOut)
			{
				clearTimeout(Preposition.timeOut);
				Preposition.timeOut=null;
			}
			Preposition.timeOut=setTimeout(function()
			{
				Preposition.seconds=0;
				Preposition.startTimer();
			},2000);
		}
	},1000);
}; 
//function which creates star divs
Preposition.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=5;
	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/star1.png");
		$(newDiv).append(newImage);
		$("#starsDiv").append(newDiv);
	}
};
//function which calculate's star count
Preposition.giveStars=function()
{
	var numberOfStars=0,temp; 
	temp=Preposition.correctCnt/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/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/"+"star"+numberOfStars+".mp3";
		document.getElementById("playSound").play();
	} 
};
//function getting audio duration
Preposition.getAudioDuration=function(sound,callback)
{
	var duration=0;
	$('#playSound').prop('src',sound);
	if(Preposition.loadmetaDataFlag)
	{
		$('#playSound').on("loadedmetadata", function()
		{
			duration=$('#playSound').prop('duration');
			Preposition.loadmetaDataFlag=false;
			$('#playSound').unbind("loadedmetadata");
			callback(duration);
		});	
	}
    else
		$('#playSound').unbind("loadedmetadata");
};	
