//september 2019
var Tense = {};
var Utils = {};
Utils.path = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 0, resId = 0, label, scoreFlag = false;
 Utils.mobileDeviceFlag = false;
$(document).ready(function () {
	if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag = true;
	/* if(Utils.mobileDeviceFlag)
	{
		Utils.path=Android.getMediaPath('makeRhymeWord');
	} */
	$(".se-pre-con").fadeOut("slow");
	setTimeout(function () {
		Tense.setImageSource();
		Tense.Init();
	}, 100);
});

Tense.setImageSource = function () {
		document.body.style.backgroundImage = Utils.path + "url('images/cover_page.png')";
	document.getElementById("queDiv").style.background=Utils.path+"url('images/text_box.png')";
	document.getElementById("logo").src = Utils.path + "images/logo.png";
	document.getElementById("playbutton").src = Utils.path + "images/Play.png";
	document.getElementById("next").src = Utils.path + "images/skip.png";
	document.getElementById("sound").src = Utils.path + "images/sound.png";
	document.getElementById("creditbtn").src=Utils.path+"images/Next.png";
	document.getElementById("check").src=Utils.path+"images/Check.png";
	if(Tense.hardcodedData.languageFont!=null)
	setFontFamilyForLang(Tense.hardcodedData.languageFont);
}
setFontFamilyForLang = function (fontFilePath) {
var newStyle = "<style>" +
	"@font-face { " +
	"font-family: 'CustomFontFamily';" +
	"src: url('" + fontFilePath + "') format('truetype');" +
	"} </style>";
$("head").append(newStyle);
$("body").css("font-family", "CustomFontFamily");
}

Tense.Init = function () {
//	document.getElementById("home").style.display = "none";
	document.getElementById("gamePage").style.display = "none";
	document.getElementById("finalPage").style.display="none";
}
//Initialize variables
Tense.initVariables = function ()
{
	$(".bgStyle").css({"background-size":"100% 100%" });
	Tense.tensDataArray=["Past","Present","Future"];
	Tense.type="learn";
	Tense.queCnt=0;
	Tense.practice=false;
	Tense.seconds=0;
	Tense.total_No_of_Questions=5;
	Tense.correctCounter=0;
}
Tense.playGame = function () {
	Tense.initVariables();
	if(Utils.mobileDeviceFlag)
	Tense.practice=Android.isPractice();
	if(Tense.practice)
		$("#help").hide();
	else
		$("#help").show();
		document.body.style.backgroundImage = Utils.path + "url('images/background.png')";
	document.getElementById("gamePage").style.display = "block";
	document.getElementById("coverPage").style.display = "none";
	//document.getElementById("home").style.display = "block";
	document.getElementById("finalPage").style.display="none";
	Tense.populateQue();
	Tense.createOptions();
	Tense.showQuestion();
	Tense.playInstruction();
}
// Populate 10 random questions from json
Tense.populateQue = function ()
{
	var noOfQue=5;
	Tense.queArr=[];
	for(var i=0;i<noOfQue;i++)
	{
		Tense.randomQue=Math.floor(Math.random()*Tense.data.length);
		while(Tense.queArr.includes(Tense.data[Tense.randomQue]))
			Tense.randomQue=Math.floor(Math.random()*Tense.data.length);
		Tense.queArr.push(Tense.data[Tense.randomQue]);
	}
	console.log(Tense.queArr);
}
//create three options as past present and future
Tense.createOptions = function ()
{
	document.getElementById("optionsDiv").innerHTML="";
	document.getElementById("optionsNamesDiv").innerHTML="";
	var noOfTense=3;
	for(var i=0;i<noOfTense;i++)
	{
	var optionDiv = document.createElement("div");
	optionDiv.setAttribute("id","outerDiv"+i);
	optionDiv.setAttribute("class","style bgStyle nopadding col-sm-3 col-lg-3 col-md-3 col-xs-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
	document.getElementById('optionsDiv').appendChild(optionDiv);
	
	//document.getElementById("outerDiv"+i).style.background=Utils.path+"url('images/'+Tense.tensDataArray[i]+'.png')";

	var optionNameDiv = document.createElement("div");
	optionNameDiv.setAttribute("id","outerNameDiv"+i);
	optionNameDiv.setAttribute("class","tensNameStyle nopadding col-sm-3 col-lg-3 col-md-3 col-xs-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
	document.getElementById('optionsNamesDiv').appendChild(optionNameDiv);
	document.getElementById("outerNameDiv"+i).innerHTML=Tense.tensDataArray_h[i];

	var options = document.createElement("div");
	options.setAttribute("id","option"+i);
	options.setAttribute("class","style1 Drop nopadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
	document.getElementById("outerDiv"+i).appendChild(options);
	$("#option"+i).data("tensData",Tense.tensDataArray[i]);
	//document.getElementById("option"+i).setAttribute("soundData",Tense.tensDataArray[i]);
	}
	document.getElementById("outerDiv0").style.background=Utils.path+"url('images/Past.png')";
	document.getElementById("outerDiv1").style.background=Utils.path+"url('images/Present.png')";
	document.getElementById("outerDiv2").style.background=Utils.path+"url('images/Future.png')";
	$(".bgStyle").css({"background-size":"100% 100%" });
		
}
//to display Question
Tense.showQuestion = function ()
 {
	var tensArray=[];
	scoreFlag = false;
	Tense.ansClicked=false;
	Tense.attemptCnt=0;				//how many times attempt the que.
	totalMarks=10;
	$("#check").hide();
	Tense.startTimer();
	d = new Date();  //date object
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();  //to get the current date
	tensArray.push(Tense.queArr[Tense.queCnt].tense);
	Tense.randOpt=Math.floor(Math.random()*Tense.tensDataArray.length);
	while(tensArray.includes(Tense.tensDataArray[Tense.randOpt]))
		Tense.randOpt=Math.floor(Math.random()*Tense.tensDataArray.length);
document.getElementById("queDiv").innerHTML="";
	var insideOption = document.createElement("div");
	 insideOption.setAttribute("id","innerOption");
	 insideOption.setAttribute("class","style2 Drag animation nopadding col-sm-5 col-lg-5 col-md-5 col-xs-5 col-sm-offset-0 col-lg-offset-0 col-md-offset-0 col-xs-offset-0");
	document.getElementById("option"+Tense.randOpt).appendChild(insideOption);

	var insideOptionPara = document.createElement("img");
	insideOptionPara.setAttribute("id","innerOptionPara");
	insideOptionPara.setAttribute("class","img-responsive nopadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
	document.getElementById("innerOption").appendChild(insideOptionPara);
	document.getElementById("innerOptionPara").src = Utils.path + "images/queMark.png";
	
		$("#innerOption").addClass('wobble');
	$( ".drag" ).draggable(
		{
			create: function( event, ui ) {},
			revert: 'invalid',
			start: function (event, ui) {
				document.getElementById("audio").pause();
				clearInterval(Tense.noResponseTimer);
				clearTimeout(Tense.timeOut);
				Tense.seconds=0;
				Tense.startTimer();
			},
			 axis : "x",
			 containment : "#optionsDiv",
			drag: function (event, ui){
				$("#innerOption").removeClass('wobble');
			
				Tense.ansClicked=true;
			}
		});
	$(".drop").droppable(
	{
		drop:function(event,ui){
			
			$("#innerOption").removeClass('animation');
			//Tense.checkAns(this.id);
			Tense.Data=$(this).data("tensData");
			document.getElementById("audio").src=Utils.path+'sounds/'+Tense.Data+'.mp3';
			document.getElementById("audio").play();
			$(this).append(ui.draggable);
			$(ui.draggable).css({'top':0,'left':'4.5vw'});
			$("#check").show();	
		}
	});
	document.getElementById("queDiv").innerHTML=Tense.queArr[Tense.queCnt].Sentence;
	questionId=Tense.queArr[Tense.queCnt].questionId;
}
//check ans is right or wrong
Tense.checkAns = function (object) {
	Tense.ansClicked=true;
	Tense.attemptCnt++;
	scoreFlag=true;
	clearInterval(Tense.noResponseTimer);
	$("#innerOption").removeClass('wobble');
	document.getElementById("sound").style.pointerEvents="none";
	console.log(Tense.queArr[Tense.queCnt].tense);
	if(Tense.Data==Tense.queArr[Tense.queCnt].tense)
	{
		document.getElementById("innerOptionPara").src = Utils.path + "images/correct.png";
		document.getElementById("audio").src=Utils.path+'sounds/Instructions/Right_answer__Aditi.mp3';
		document.getElementById("innerOption").style.pointerEvents="none";
		scoredMarks=10;
		Tense.scoreFunction ();
		Tense.ansClicked=false;
		$("#check").hide();
	//	scoreFlag=false;
		Tense.correctCounter++;
	}
	else
	{
		scoredMarks=0;
		Tense.scoreFunction ();
		Tense.ansClicked = false;
		document.getElementById("innerOption").style.pointerEvents="none";
		document.getElementById("audio").src=Utils.path+'sounds/Instructions/wrong_answer!_Aditi.mp3';
		document.getElementById("innerOptionPara").src = Utils.path + "images/wrong.png";
	}
	if (Tense.nextQueTimer) {
		clearTimeout(Tense.nextQueTimer);
		Tense.nextQueTimer = null;
	}
	Tense.nextQueTimer = setTimeout(function () {
		
		Tense.nextQue();
	}, 2000);
	document.getElementById("audio").play();
	Tense.queArr.splice(Tense.queCnt,1);
	console.log(Tense.queArr);
}
//to show next question
Tense.nextQue = function () {
		clearInterval(Tense.noResponseTimer);
	clearTimeout(Tense.nextQueTimer);
	document.getElementById("sound").style.pointerEvents="auto";
	$("#check").show();
	$("#next").removeClass("blink_me");
	clearInterval(Tense.setTimeToQue);
	document.getElementById("audio").pause(); 
	
	document.getElementById("option"+Tense.randOpt).innerHTML="";
	
		Tense.optionArr=[];
		
		if(scoreFlag!=true)
		{
			Tense.queCnt++;
		}
		if(Tense.queArr.length==0)
		{
			Tense.gameOver();
		}
		else if(Tense.queCnt==Tense.queArr.length)
		{
			clearInterval(Tense.noResponseTimer);
		document.getElementById("responseBoxDiv").style.display="block";
		document.getElementById("No").innerHTML=Tense.modalData.no;
		document.getElementById("Yes").innerHTML=Tense.modalData.yes;
		document.getElementById("questionMsg").innerHTML=Tense.modalData.responseMsg;
		}
		else
		{
			Tense.createOptions();
			Tense.showQuestion();
		}
}

Tense.gameOver = function () {
	document.getElementById("audio").pause(); 
	clearInterval(Tense.noResponseTimer);
	document.getElementById("gamePage").style.display = "none";
	document.getElementById("finalPage").style.display="block";
	document.getElementById("responseBoxDiv").style.display="none";
	document.getElementById('gameOver').innerHTML=Tense.hardcodedData.message2;
	document.getElementById("audio").pause(); 
	for(i=0;i<Object.keys(Tense.AcknowledgementPageData).length;i++)
	{
		div=document.createElement('div');
		div.className="fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML=Object.keys(Tense.AcknowledgementPageData)[i]+" : "+Object.values(Tense.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div=document.createElement('div');
	div.className="fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=Tense.hardcodedData['createdOn'];
	acknowledgementDiv.appendChild(div);
	document.getElementById("acknowledgementDiv").style.display="none";
	Tense.createStars();
	Tense.giveStars();
}

Tense.scoreFunction=function()					//score Function
{
	console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
	if(Utils.mobileDeviceFlag)
	{
		Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}
} 
/* Tense.returnback = function () {
	if(Tense.ansClicked)
	{
		scoredMarks = 0;
		Tense.ansClicked = false;
		Tense.createOptions();
		Tense.showQuestion();
	}
	location.reload();
} */
Tense.showCredits=function()			//show credits on click credit button
{
	document.getElementById("acknowledgementDiv").style.display="block";
}
Tense.shuffle = function (alphaArray)	//suffle the letterArray
{
	for (var i = 0; i < alphaArray.length; i++) {
		var j = Math.floor(Math.random() * (alphaArray.length - 1));
		var temp = alphaArray[i];
		alphaArray[i] = alphaArray[j];
		alphaArray[j] = temp;
	}
	return alphaArray;
}
//animation-iteration-count:infinite;

Tense.showSkippedQuestions=function()
{
	document.getElementById("responseBoxDiv").style.display="none";
	Tense.queCnt=0;
	Tense.createOptions();
	Tense.showQuestion();
}

//function which creates star divs
Tense.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);
	}
};

Tense.giveStars=function()
{
	var fractionVar,i,temp; 
	var numberOfStars=0;
	ans=Tense.total_No_of_Questions/5;
	temp=Tense.correctCounter/ans;
	numberOfStars=Math.floor(temp);
	temp=Math.round(temp);
	console.log(numberOfStars);
	console.log(temp);
	for(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("audio").src=Utils.path+"sounds/Instructions/"+"Star"+numberOfStars+".mp3";
	document.getElementById("audio").play();
	}
	if(Utils.mobileDeviceFlag)
	Android.StudentCertification(Tense.correctCounter,Tense.total_No_of_Questions,"8");
};

Tense.goNext=function()
{
	clearInterval(Tense.skipTimer);
	if(Utils.mobileDeviceFlag)
	Android.GotoNextGame();
}

Tense.startTimer=function()
{
	if(Tense.noResponseTimer)
	{
		clearInterval(Tense.noResponseTimer);
		Tense.noResponseTimer=null;
		Tense.seconds=0;
	}	
	Tense.noResponseTimer=setInterval(function() 
	{
		Tense.seconds++;
		if(Tense.seconds>=7)
		{
			document.getElementById("audio").src=Utils.path+"sounds/instructions/please_ans_the_ques.mp3";
			document.getElementById("audio").play(); 
			clearInterval(Tense.noResponseTimer);
			if(Tense.timeOut)
			{
				clearTimeout(Tense.timeOut);
				Tense.timeOut=null;
			}
				Tense.timeOut=setTimeout(function()
			{
				Tense.seconds=0;
				Tense.startTimer();
			},2000);
		}
	},1000);
};
Tense.playInstruction = function () {								//play instruction
	Tense.seconds = 0;
	clearInterval(Tense.noResponseTimer);
	clearTimeout(Tense.timeOut);
	getDuration(Utils.path + 'sounds/Instructions/' + Tense.hardcodedData.instruction);
}
function getDuration(src) {
	var duration = 0;
	//if (ShowMe.soundFlag) {
	$('#audio').on("loadedmetadata", function () {
		duration = $('#audio').prop('duration');
		$('#audio').unbind("loadedmetadata");
		Tense.playNextSound(duration);
	});
	$('#audio').prop('src', src);
}
Tense.playNextSound = function (duration)								//function for instruction
{
	document.getElementById('audio').play();
	if (Tense.instructionTimer) {
		clearTimeout(Tense.instructionTimer);
		Tense.instructionTimer = null;
	}
	Tense.instructionTimer = setTimeout(function () {
		Tense.startTimer();
	}, duration * 1000);
}