//starting date:19th october 2018.
var FlipIt={};
var Utils = {};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=100,resId=0,level=0,label;

$(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("FlipIt"); 
	setTimeout(function()
	{
		FlipIt.init();
	},100);
});
//shows coverPage
FlipIt.init=function()
{
	$("#coverPage").show();
	$("#levelPage").hide();
	$("#gamePage").hide();
	$("#lastPage").hide();
	$(".header").not("#logo").css("visibility","hidden");
	$("#gameOver").css("visibility","hidden");
	document.body.style.backgroundImage = "url("+Utils.Path+"images/coverImage.png";
	FlipIt.setAllImages();
	FlipIt.createOptionDivs();
}
//initialization
FlipIt.initializeVariables=function()
{
	FlipIt.levelIndex=0;
	FlipIt.question;
	FlipIt.attemptCounter=0;
	FlipIt.wordLevel=0;
	FlipIt.noOfQuestions=0;
	FlipIt.attemptFlag=false;
	FlipIt.newQuestionLoad=true;
	FlipIt.uniqueArray=[];
	FlipIt.loadmetaDataFlag=false;
	FlipIt.pointerEventFlag=true;
}
//setting sources to all images
FlipIt.setAllImages=function()
{
	document.getElementById("homeImage").src=Utils.Path+"images/home.png";
	document.getElementById("logoImage").src=Utils.Path+"images/logo.png";
	document.getElementById("play").src=Utils.Path+"images/Play.png";
	document.getElementById("next").src=Utils.Path+"images/Next.png";
	document.getElementById("sound").src=Utils.Path+"images/Sound.png";
	document.getElementById("levelImg1").src=Utils.Path+"images/Level_01.png";
	document.getElementById("levelImg2").src=Utils.Path+"images/Level_02.png";
	document.getElementById("replayImg").src=Utils.Path+"images/PlayAgain.png";
	document.getElementById("creditImg").src=Utils.Path+"images/credit.png";
	document.getElementById("lastPara").innerHTML=FlipIt.hardCodedData.gameOver;
	//document.getElementById("message").innerHTML=FlipIt.hardCodedData.message;
}
//creates divs for options
FlipIt.createOptionDivs=function()
{
	var i=0,parentDiv,option,para;
	parentDiv=document.getElementById("optionDiv");
	for(i=1;i<=4;i++)
	{
		option=document.createElement("DIV");
		option.setAttribute("id","optionDiv"+i);
		if(i==1)
			option.setAttribute("class","optionDivs nopadding col-xs-8 col-md-8 col-lg-8 col-sm-8");
		else
			option.setAttribute("class","optionDivs marginCls nopadding col-xs-8 col-md-8 col-lg-8 col-sm-8");
		option.setAttribute("onclick","FlipIt.checkAnswer(this.id);");
		if(i%2==1)
			option.style.backgroundImage="url("+Utils.Path+"images/arrow_1.png";
		else
		{	
			option.style.backgroundImage="url("+Utils.Path+"images/arrow_2.png";
			option.style.marginLeft="20vw";
		}
		parentDiv.appendChild(option);
	
		para=document.createElement("P");
		para.setAttribute("id","option"+i);
		para.setAttribute("class","options");
		option.appendChild(para);
		
	}
}
//displays levelPage
FlipIt.showLevel=function()
{
	$("#coverPage").hide();
	$("#gamePage").hide();
	$("#levelPage").show();
	$("#lastPage").hide();
	$(".header").css("visibility","visible");
	$("#gameOver").css("visibility","hidden");
	document.body.style.backgroundImage = "url("+Utils.Path+"images/levelBg.png";
	document.getElementById("level1").setAttribute("level",1);
	document.getElementById("level2").setAttribute("level",2);
	FlipIt.initializeVariables();
}

//runs @ onclick of level button,selects level
FlipIt.selectLevel=function(levelId)
{
	level=parseInt(document.getElementById(levelId).getAttribute("level"));
	FlipIt.levelIndex=level-1;
	FlipIt.playGame();			
}

//shows gamePage
FlipIt.playGame=function()
{
	rNo=0;
	FlipIt.newQuestionLoad=true;
	document.body.style.backgroundImage = "url("+Utils.Path+"images/bg.png";
	$(".options").css("font-size","3.5vw");
	$("#levelPage").hide();
	$("#gamePage").show();
	$("#lastPage").hide();
	$(".header").css("visibility","visible");
	FlipIt.setQuestion();
}

//runs @onclick replay button @endPage,reloads the game again
FlipIt.playAgain=function()
{
	FlipIt.uniqueArray=[];
	console.log(FlipIt.uniqueArray);
	$("#gameOver").css("visibility","hidden");
	FlipIt.attemptCounter=0;
	FlipIt.wordLevel=0;
	FlipIt.noOfQuestions=0;
	
	FlipIt.playGame();
}

//selects the one option as question,plays the sound of translation of question
FlipIt.setQuestion=function()
{

	scoredMarks=0;
	var d,i=0,rNo=0,question,option,flag=0,optionArr=[],randOption=0,allOption=[];
	d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	FlipIt.firstAttemptFlag=true;
	FlipIt.wrongFlag=false;
	FlipIt.noOfQuestions++;
	if(FlipIt.wordLevel>1)
		$(".options").css("font-size","3vw");
	if(FlipIt.wordLevel>2)
		$(".options").css("font-size","2.3vw");
	if(FlipIt.noOfQuestions>=8)
		FlipIt.endGame();
	else
	{	
		rNo=Math.floor(Math.random()*FlipIt.data[FlipIt.wordLevel].sentence.length);
		if(FlipIt.levelIndex==0)
		{
			FlipIt.question=FlipIt.data[FlipIt.wordLevel].sentence[rNo];
			while(FlipIt.uniqueArray.includes(FlipIt.question))
			{
				rNo=Math.floor(Math.random()*FlipIt.data[FlipIt.wordLevel].sentence.length);
				FlipIt.question=FlipIt.data[FlipIt.wordLevel].sentence[rNo];
			}
			
			allOption.push(FlipIt.data[FlipIt.wordLevel].sentence[rNo].english)
			for(i=0;i<3;i++)
			{
				allOption.push(FlipIt.data[FlipIt.wordLevel].sentence[rNo].option[i]);
			}
			shuffleArray(allOption);
			for(i=0;i<allOption.length;i++)
			{
				document.getElementById("option"+(i+1)).innerHTML=allOption[i];
			}	
		}
		else
		{
			for(i=0;i<4;i++)
			{
				while(optionArr.includes(rNo))
					rNo=Math.floor(Math.random()*FlipIt.data[FlipIt.wordLevel].sentence.length);
				optionArr.push(rNo)
				if(FlipIt.levelIndex==0)
					option=FlipIt.data[FlipIt.wordLevel].sentence[rNo].english;
				else
					option=FlipIt.data[FlipIt.wordLevel].sentence[rNo].hindi;
				document.getElementById("option"+(i+1)).innerHTML=option;
			}
			randOption=Math.floor(Math.random()*optionArr.length);
			FlipIt.question=FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]];
			while(FlipIt.uniqueArray.includes(FlipIt.question))
			{
				randOption=Math.floor(Math.random()*optionArr.length);
				FlipIt.question=FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]];
			}	
			FlipIt.uniqueArray.push(FlipIt.question);
		}
		if(FlipIt.levelIndex==0)
		{
			label=(FlipIt.data[FlipIt.wordLevel].sentence[rNo].hindi);
			questionId=parseInt(FlipIt.data[FlipIt.wordLevel].sentence[rNo].questionId);
		}
		else
		{
			label=(FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]].english);
			questionId=parseInt(FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]].questionId);
		}
		FlipIt.playSound();
	}
}

//calls when 5 question completesshows endPage
FlipIt.endGame=function()
{
	document.getElementById("acknowledgementDiv").style.display="none";
	$("#gamePage").hide();
	$("#lastPage").show();
	$("#gameOver").css("visibility","visible");
	document.body.style.backgroundImage = "url("+Utils.Path+"images/BBg.png";
	document.getElementById("playSound").pause();
}

//runs @onclick of options checks whether the translation and option clicked are matched
FlipIt.checkAnswer=function(divId)
{
	FlipIt.attemptFlag=true;
	FlipIt.attemptCounter++;
	document.getElementById("playSound").pause();
	document.getElementById(divId).style.pointerEvents="none";
	if(FlipIt.levelIndex==0)
		if(document.getElementById(divId).children[0].innerHTML==FlipIt.question.english)
		{
			FlipIt.sendScore(divId);
		}
		else
		{
			FlipIt.wrongFlag=true;
			document.getElementById("playSound").src=Utils.Path+"sounds/Try_again.mp3";
			document.getElementById(divId).children[0].style.opacity=0.5;
			$("#"+divId).children().addClass("animated shake");
			
		}
	else
		if(document.getElementById(divId).children[0].innerHTML==FlipIt.question.hindi)
			FlipIt.sendScore(divId);
		else
		{	
			FlipIt.wrongFlag=true;
			document.getElementById("playSound").src=Utils.Path+"sounds/Try_again.mp3";
			document.getElementById(divId).children[0].style.opacity=0.5;
			$("#"+divId).children().addClass("animated shake");
		}
	document.getElementById("playSound").play();
}

//runs when answer is correct.
FlipIt.sendScore=function(divId)
{
	$("#"+divId).children().addClass("animated flash");
	scoredMarks=(5-FlipIt.attemptCounter)*25;
	FlipIt.wordLevel++;
	document.getElementById("playSound").src=Utils.Path+"sounds/CorrectAksharkhadi.mp3";
	document.getElementById(divId).children[0].style.color="#2de430";
	$(".optionDivs").css("pointer-events","none");
	$("#soundDiv").css("pointer-events","none");
	console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);	
	FlipIt.nextQuestionTimeout=setTimeout(function()
	{
		FlipIt.showNextQuestion();
	},2000);
	
}
//plays the translation of question
FlipIt.playSound=function()
{
	var source;
	if(FlipIt.levelIndex==0)
		document.getElementById("playSound").src=Utils.Path+"sounds/"+FlipIt.question.hindiSound;
	else
		document.getElementById("playSound").src=Utils.Path+"sounds/"+FlipIt.question.englishSound;
	source=document.getElementById("playSound").src;
	//document.getElementById("playSound").play();
	if(FlipIt.pointerEventFlag==true)
		$(".optionDivs").css("pointer-events","none");
	$("#soundDiv").css("pointer-events","auto");
	FlipIt.loadmetaDataFlag=true;
	FlipIt.getDuration(source);
	
}
function saySomething(whatToSay)
{
	var synth,speech;
	synth = window.speechSynthesis;
	if('speechSynthesis' in window)
	{
		speech = new SpeechSynthesisUtterance(whatToSay);
		speech.lang = 'hi-IN'; //en-US
		window.speechSynthesis.speak(speech);
	}
} 
//runs @onclick of next button and when answer given is correct
FlipIt.showNextQuestion=function()
{
	FlipIt.pointerEventFlag=true;
	if(FlipIt.attemptFlag==false)
	{
		scoredMarks=-1;
		console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
		if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
	}
	else
	{
		FlipIt.attemptFlag=false;
		if(scoredMarks==0)
		{
			console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
			if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);	
		}
	}	
	clearTimeout(FlipIt.nextQuestionTimeout);
	FlipIt.attemptCounter=0;
	$(".options").css("color","white");
	$(".optionDivs").css("pointer-events","auto");
	$("#soundDiv").css("pointer-events","auto");
	document.getElementById("playSound").pause();
	$(".options").removeClass("anmated shake");
	$(".options").removeClass("animated flash");
	$(".options").css("opacity",1);
	FlipIt.setQuestion();
}
//runs @ onclick of home button shows the levelPage from game and homePage from levelPage
FlipIt.callhome=function()
{

	FlipIt.pointerEventFlag=true;	
	if(document.getElementById("levelPage").style.display=="block")
		location.reload();
	else
	{

		document.getElementById("playSound").pause();
		clearTimeout(FlipIt.nextQuestionTimeout);
		FlipIt.showLevel();
		if(FlipIt.wrongFlag==true)
		{
			console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
			if(Utils.mobileDeviceFlag)
				Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);	
		}
		$(".options").removeClass("anmated shake");	
		$(".options").removeClass("animated flash");
		$(".options").css("color","white");
		$(".options").css("opacity",1);
	}	
	
}

function saySomething(whatToSay)
{
if('speechSynthesis' in window)
{
speech = new SpeechSynthesisUtterance(whatToSay);
speech.lang = 'hi-IN'; //en-USdocument.getElementById("playSound").pause();
//speech.rate=0.7;
window.speechSynthesis.speak(speech);
}document.getElementById("playSound").pause();
//speech.onend = function() { $("#soundDiv").css("pointer-events","auto"); };
}


//shows acknowledgement.
FlipIt.showAcknowlwdgement=function()
{
	var i=0,div;
	$("#acknowledgementDiv").empty();
	console.log(Object.keys(FlipIt.AcknowledgementPageData).length)
	for(i=0;i<Object.keys(FlipIt.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(FlipIt.AcknowledgementPageData)[i]+" : "+Object.values(FlipIt.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=FlipIt.hardCodedData['createdOn'];
	div.style.marginBottom="2vh";
	acknowledgementDiv.appendChild(div);
	document.getElementById("acknowledgementDiv").style.display="block";
}

function shuffleArray(array)
{
var i,j,temp;
for (i = array.length - 1; i > 0; i--) 
{
   j = Math.floor(Math.random() * (i + 1));
   temp = array[i];
   array[i] = array[j];
   array[j] = temp;
}
return array;
}

FlipIt.getDuration=function(sound)
{
	var duration=0;
	$('#playSound').prop('src',sound);
	document.getElementById("playSound").play();
	if(FlipIt.loadmetaDataFlag)
	{
		$('#playSound').on("loadedmetadata", function(){
			FlipIt.loadmetaDataFlag=false;
			$('#playSound').unbind("loadedmetadata");
			duration=$('#playSound').prop('duration');
			
			if(duration==0)
			{
				duration=1;
				console.log(duration);
			}
			if(FlipIt.pointerEventFlag==true)
			{	
				FlipIt.pointerEventFlag=false;
				FlipIt.enableClick(duration);
			}
			}	
		);
    }
    else
		$('#playSound').unbind("loadedmetadata");
}
FlipIt.enableClick=function(duration)
{
	setTimeout(function()
	{
		$(".optionDivs").css("pointer-events","auto");
	},duration*900);
}