//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;
var correctCnt=0,attemptCnt=0;

$(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);
});
// initial function,shows the coverPage.
FlipIt.init=function()
{
	$("#coverPage").show();
	$("#levelPage").hide();
	$("#gamePage").hide();
	$("#lastPage").hide();
	$(".header").not("#logo").css("visibility","hidden");
	document.body.style.backgroundImage = "url("+Utils.Path+"images/coverImage.png";
	FlipIt.setAllImages();
	FlipIt.createOptionDivs();
	FlipIt.createStars();
}

//sets 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("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("nextButton").src=Utils.Path+"images/Next.png";
	document.getElementById("gameOver").innerHTML=FlipIt.hardCodedData.gameOver;
}
//creates optionDivs
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);
		option.setAttribute("class","optionDivs 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);
		
	}
}
FlipIt.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);
		$("#starDiv").append(newDiv);
	}
$("#starDiv").css("visibility","hidden");
};
//shows the levelPage
FlipIt.showLevel=function()
{
	$("#coverPage").hide();
	$("#gamePage").hide();
	$("#levelPage").show();
	$("#lastPage").hide();
	$("#message").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();
}
//variable initialization
FlipIt.initializeVariables=function()
{
	FlipIt.seconds=0;
	FlipIt.levelIndex=0;
	FlipIt.correctCounter=0;
	FlipIt.question;
	FlipIt.attemptCounter=0;
	FlipIt.wordLevel=0;
	FlipIt.noOfQuestions=0;
	FlipIt.attemptFlag=false;
	FlipIt.noResposnseFlag=false;
	FlipIt.soundQue;
	FlipIt.loadmetaDataFlag=true;
	FlipIt.timeOut;
	FlipIt.uniqueArray=[];
	FlipIt.totalQuestions=5;
}
//Runs selection of level
FlipIt.selectLevel=function(levelId)
{
	document.body.style.backgroundImage = "url("+Utils.Path+"images/bg.png";
	level=parseInt(document.getElementById(levelId).getAttribute("level"));
	FlipIt.levelIndex=level-1;
	FlipIt.playGame();			
}

//shows the gamePage
FlipIt.playGame=function()
{
	rNo=0;
	
	$("#levelPage").hide();
	$("#gamePage").show();
	$("#lastPage").hide();
	$(".header").css("visibility","visible");
	FlipIt.setQuestion();
	
}
//sets the four options for 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.noOfQuestions++;
	if(FlipIt.wordLevel>2)
		$(".options").css("font-size","3vw");
	if(FlipIt.wordLevel>=4)
		$(".options").css("font-size","2.5vw");
	if(FlipIt.noOfQuestions>FlipIt.totalQuestions)
		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);
		}
		clearInterval(FlipIt.noResponseTimer);
		clearTimeout(FlipIt.timeOut);
		FlipIt.getQueSoundSrc();
	}
}
//plays the question sound when loads the new question.
FlipIt.getQueSoundSrc=function()
{
	clearInterval(FlipIt.noResponseTimer);
	if(FlipIt.levelIndex==0)
		FlipIt.soundQue=Utils.Path+"sounds/"+FlipIt.question.hindiSound;
	else
		FlipIt.soundQue=Utils.Path+"sounds/"+FlipIt.question.englishSound;
	FlipIt.loadmetaDataFlag=true;
	$(".optionDivs").css("pointer-events","none");
	FlipIt.getDuration(FlipIt.soundQue);
}

//gets the duration of question sound played.
FlipIt.getDuration=function(sound)
{
	var duration=0;
	$('#playSound').prop('src',sound);
	if(FlipIt.loadmetaDataFlag)
	{
		$('#playSound').on("loadedmetadata", function(){
			FlipIt.loadmetaDataFlag=false;
			$('#playSound').unbind("loadedmetadata");
			duration=$('#playSound').prop('duration');
			FlipIt.playQueSound(duration);
			}	
		);
    }
    else
		$('#playSound').unbind("loadedmetadata");
}
//plays the question;
FlipIt.playQueSound=function(duration)
{
	document.getElementById("playSound").play();
	setTimeout(function()
	{
		$(".optionDivs").css("pointer-events","auto");
		FlipIt.startTimer();
	},duration*900);
}

//timer
FlipIt.startTimer=function()
{
	if(FlipIt.noResponseTimer)
	{
		clearInterval(FlipIt.noResponseTimer);
		FlipIt.noResponseTimer=null;
		FlipIt.seconds=0;
	}	
	FlipIt.noResponseTimer=setInterval(function() 
	{
		FlipIt.seconds++;
		if(FlipIt.seconds>=7)
		{
			document.getElementById("playSound").src=Utils.Path+"sounds/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(FlipIt.noResponseTimer)
			FlipIt.timeOut=setTimeout(function()
			{
				FlipIt.seconds=0;
				FlipIt.startTimer();
			},2000);
		}
	},1000);
}	
//shows the gameover
FlipIt.endGame=function()
{
	correctCnt=FlipIt.correctCounter;
	attemptCnt=FlipIt.attemptCounter;
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	document.getElementById("playSound").pause();
	FlipIt.giveStars();
	document.body.style.backgroundImage = "url("+Utils.Path+"images/BBg.png";
	$("#message").css("visibility","hidden");
	$("#gamePage").hide();
	$("#lastPage").show();
	$("#nextGame").addClass("blink_me");
	if(Utils.mobileDeviceFlag) 
		Android.StudentCertification(correctCnt,FlipIt.totalQuestions,"7");
}
//runs @selecting the answer from the options
FlipIt.checkAnswer=function(divId)
{
	clearInterval(FlipIt.noResponseTimer);
	FlipIt.attemptFlag=true;
	FlipIt.attemptCounter++;
	document.getElementById("playSound").pause();
	$(".optionDivs").css("pointer-events","none");
	$("#soundDiv").css("pointer-events","none");
	document.getElementById(divId).style.pointerEvents="none";
	if(FlipIt.levelIndex==0)
		if(document.getElementById(divId).children[0].innerHTML==FlipIt.question.english)
		{
			FlipIt.sendScore(divId);
		}
		else
		{	
			scoredMarks=0;
			document.getElementById("playSound").src=Utils.Path+"sounds/wrongSoundAksharkhadi.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
		{	
			scoredMarks=0;
			document.getElementById("playSound").src=Utils.Path+"sounds/wrongSoundAksharkhadi.mp3";
			document.getElementById(divId).children[0].style.opacity=0.5;
			$("#"+divId).children().addClass("animated shake");
		}
	document.getElementById("playSound").play();
	FlipIt.nextQuestionTimeout=setTimeout(function()
	{
		FlipIt.showNextQuestion();
	},2000);
}
//runs when answer is correct
FlipIt.sendScore=function(divId)
{
	scoredMarks=100;
	FlipIt.correctCounter++;
	$("#"+divId).children().addClass("animated flash");
	if(FlipIt.wordLevel<6)
		FlipIt.wordLevel++;
	document.getElementById("playSound").src=Utils.Path+"sounds/CorrectAksharkhadi.mp3";
	document.getElementById(divId).children[0].style.color="#2de430";
	//console.log(resId,questionId,scoredMarks,totalMarks,level,startTime);
	//if(Utils.mobileDeviceFlag)
		//Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime);	
}
//shows the next question.
FlipIt.showNextQuestion=function()
{
	console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);	
		
	$(".options").css("color","white");
	$(".optionDivs").css("pointer-events","auto");
	$("#soundDiv").css("pointer-events","auto");
	document.getElementById("playSound").pause();
	$(".options").removeClass("animated shake");   
	$(".options").removeClass("animated flash");
	$(".options").css("opacity",1);
	FlipIt.setQuestion();
}
//reloads the page 
FlipIt.callhome=function()
{
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);		
	if(document.getElementById("levelPage").style.display=="block")
		location.reload();
	else
	{
		document.getElementById("playSound").pause();
		clearTimeout(FlipIt.nextQuestionTimeout);
		FlipIt.initializeVariables();
		FlipIt.showLevel();
	}	
	
}

//on click of sound button
FlipIt.playSoundOnsoundClick=function()
{
	$('#playSound').prop('src',FlipIt.soundQue);
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	document.getElementById("playSound").play();
	setTimeout(function()
	{
		FlipIt.startTimer();
	},1000);
}
//creates stars according to the score of game
FlipIt.giveStars=function()
{
	var fractionVar,i,numberOfStars=FlipIt.correctCounter; 
	for(i=1;i<=Math.floor(numberOfStars);i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/star2.png");
	$("#starDiv").css("visibility","visible");
	if(numberOfStars!=0)
	{
		document.getElementById("playSound").src=Utils.Path+"sounds/"+FlipIt.sounds[(numberOfStars-1)].sound;
		document.getElementById("playSound").play();
	}
};

FlipIt.showNextGame=function()
{
	if(Utils.mobileDeviceFlag) 
		Android.GotoNextGame();
}

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);
			}
			FlipIt.enableClick(duration);
			}	
		);
    }
    else
		$('#playSound').unbind("loadedmetadata");
}
FlipIt.enableClick=function(duration)
{
	setTimeout(function()
	{
		$(".optionDivs").css("pointer-events","auto");
	},duration*900);
}
