//4th July 2020
var BirdGame = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 10, wrongCnt = 0, totalLength = 0, type = "word", correctCnt = 0;
BirdGame.skipedQ = 0;
BirdGame.alreadyShownObject = [];
BirdGame.tempArr = [];								//json data
BirdGame.queArr=[];
BirdGame.skipFlag = true;
BirdGame.attemptFlag = false;
BirdGame.objPointerFlag = true;						//image clicked flag
BirdGame.finalInstrFlag == false;
BirdGame.optionCnt = 0;								//counter for playing optionin sequence
BirdGame.levelNumber = 0;							//false for learn & true for practice
BirdGame.correctCounter=0;
BirdGame.total_No_of_Questions = 5;
//BirdGame.levelName = false;
//function for loader
$(document).ready(function () {
	$(".se-pre-con").fadeOut("slow");
	if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
		Utils.mobileDeviceFlag = true; 
	/* if(Utils.mobileDeviceFlag)
		Utils.Path=Android.getMediaPath("Aksharkhadi");  */
	setTimeout(function () {
		$("#gamepage,#endpage,#homeImg").hide();
		$("#coverpage").show();
		BirdGame.init();
		BirdGame.setImages();
	}, 300);
});
BirdGame.init = function () {

	var categoryName;
	if (Utils.mobileDeviceFlag) {
		categoryName = Android.getCategory();
		for (var i = 0; i < BirdGame.data.list.length; i++) {
			if (BirdGame.data.list[i].Bird_name_marathi.includes(categoryName)) {
				BirdGame.levelNumber = i;
				break;
			}
		}
		BirdGame.levelName=Android.isPractice();
	}
	else
		BirdGame.levelNumber = Math.floor(Math.random() * BirdGame.data.list.length);
	totalLength = BirdGame.data.list[BirdGame.levelNumber].data.length;
	console.log(totalLength + " " + type);
}
BirdGame.setImages = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path +"images/skin/coverPage.png)";
	document.getElementById("BirdGamePageDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/board.png)";
	$("#homeImg").prop("src", Utils.Path + "images/skin/Home.png");
	$("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
	$("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
	$("#nextImage").prop("src", Utils.Path + "images/skin/Next.png");
	$("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
	$("#credit").prop("src", Utils.Path + "images/skin/credits.png");
	$("#sound").prop('src', Utils.Path + "images/skin/Sound.png");
}
BirdGame.playGame = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
	$("#homeImg,#gamepage").show();
	$("#coverpage").hide();
	document.getElementById("BirdGamePageDiv").innerHTML="";
	BirdGame.createDivs(BirdGamePageDiv, "picture", "pictureClass noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1", 3);
	$(".borderClass").css("backgroundImage", "url(images/skin/imageBox.png)");
	BirdGame.selectLevel();
	BirdGame.populate();	
	BirdGame.showObjects();
}
//creates No. of Divs
BirdGame.createDivs = function (parentDiv, id, className, no) { //create Divs for level page & Main game page
	var pictureDiv, img, imgDiv, textDiv, levelNo = 1;
	for (var j = 0; j < no; j++ , levelNo++) {
		pictureDiv = document.createElement("div");
		pictureDiv.setAttribute("id", id + j);
		pictureDiv.setAttribute("class", className);
		parentDiv.appendChild(pictureDiv);

		/* textDiv = document.createElement("div");
		textDiv.setAttribute("id", id + "text" + j);
		textDiv.setAttribute("class", 'textDivCss noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12');
		pictureDiv.appendChild(textDiv); */
		
		img = document.createElement('img');
		img.setAttribute("id", id + "img" + j);
		img.setAttribute("class", "noPadding borderClass img-responsive col-lg-10 col-md-10 col-xs-10 col-sm-10 col-lg-offset-1 col-md-offset-1 col-xs-offset-1 col-sm-offset-1");
		pictureDiv.appendChild(img);
		img.setAttribute("onclick", "BirdGame.checkAnswer(this)");
		/* if (!BirdGame.levelName) {										//For learn section
			imgDiv = document.createElement("div");
			imgDiv.setAttribute("class", "optionClass noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
			pictureDiv.appendChild(imgDiv);

			subImgDiv = document.createElement("div");
			subImgDiv.setAttribute("class", "noPadding col-lg-4 col-md-4 col-xs-4 col-sm-4 col-sm-offset-4 col-lg-offset-4 col-md-offset-4 col-xs-offset-4");
			imgDiv.appendChild(subImgDiv);

			img = document.createElement('img');
			img.setAttribute("class", "img-responsive noPadding col-lg-10 col-md-10 col-xs-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
			img.setAttribute("src", Utils.Path + "images/skin/option_Sound.png");
			$(img).data("ans", j);
			img.setAttribute("onclick", "BirdGame.playOptions(this)");
			subImgDiv.appendChild(img);
		} */
	}
}
BirdGame.selectLevel = function (element) { 		//selects level
	BirdGame.skipedQ = 0;
	BirdGame.alreadyShownObject = [];
	$("#message").css("visibility", "hidden");
	$("#instruction").css("visibility", "hidden");
	BirdGame.tempArr = JSON.parse(JSON.stringify(BirdGame.data.list[BirdGame.levelNumber].data));
	/* console.log('category');
	console.log(BirdGame.data.list[BirdGame.levelNumber].category); */
	shuffleArray(BirdGame.tempArr);
	/* console.log('BirdGame.tempArr');
	console.log(BirdGame.tempArr); */
}
BirdGame.populate = function () {
	BirdGame.queArr=[];
	BirdGame.queArr = populate(BirdGame.tempArr, BirdGame.queArr, 5);
}
BirdGame.options = function () {
	BirdGame.uniqueImgArr = [];
	BirdGame.uniqueImgArr.push(BirdGame.queArr[BirdGame.skipedQ]);
	BirdGame.uniqueImgArr = populate(BirdGame.tempArr, BirdGame.uniqueImgArr, 3);
	console.log('BirdGame.uniqueImgArr');
	console.log(BirdGame.uniqueImgArr);
	shuffleArray(BirdGame.uniqueImgArr);
	BirdGame.uniqueQue = BirdGame.queArr[BirdGame.skipedQ];	//get unique Question
	questionId = BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].qid;
}
//Show Objects on the screen
BirdGame.showObjects = function() {				//display  images levelwise 
	var d;
	BirdGame.optionCnt = 0;
	BirdGame.skipFlag = true;
	BirdGame.objPointerFlag = true;
	BirdGame.options();
	$("#acknowledgementDiv").text('');
	clearTimeout(BirdGame.optionTimer);
	clearTimeout(BirdGame.instructionTimer);
	$("#message").css("visibility", "hidden");
	$("#instruction").css("visibility", "hidden");
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	
	for (var j=0; j<3; j++) {			//display images & set data to images
		BirdGame.showLoader();
		$("#pictureimg" + j).prop("src", Utils.Path + "images/" + BirdGame.tempArr[BirdGame.uniqueImgArr[j]].Image);
		$("#pictureimg" + j).data("ans", BirdGame.tempArr[BirdGame.uniqueImgArr[j]].Bird_name_marathi);
		//document.getElementById("picturetext" + j).innerHTML = BirdGame.tempArr[BirdGame.uniqueImgArr[j]].Bird_name_marathi;
	}
	//BirdGame.playInstruction();
}
BirdGame.showLoader = function()
{
	$(".loader").show();
	$('.loader').css('display', 'flex');
	var imgs = document.images, len = imgs.length, counter = 0;
	[].forEach.call( imgs, function( img )
	{
		if(img.complete)
			incrementCounter();
	   else
			img.addEventListener( 'load', incrementCounter, false );
	} );
	function incrementCounter()
	{
		counter++;
		if ( counter === len ){
			$(".loader").hide();
			BirdGame.playInstruction();
		}	
	}
}
/* BirdGame.playOptions = function (element) {		//plays particular sound for image
	clearTimeout(BirdGame.instructionTimer);
	clearTimeout(BirdGame.optionTimer);
	$("#soundDiv").css({ "pointer-events": "auto" });
	$(".borderClass").removeClass("animated zoomIn");
	var data = $(element).data("ans");
	document.getElementById('playSound').pause();
	document.getElementById('playSound').src = Utils.Path + 'sounds/BirdNameSound/' + BirdGame.tempArr[BirdGame.uniqueImgArr[data]].birdNameAudio;
	document.getElementById('playSound').play();
} */
BirdGame.playInstruction = function () {		// plays sound of instruction/options
	BirdGame.soundFlag = true;
	$(".optionClass").css("pointer-events", "none");
	if (BirdGame.objPointerFlag)
		$(".borderClass").css({ "pointer-events": "none" });
	if (BirdGame.levelName) 
		getDuration(Utils.Path + 'sounds/instruction/' + BirdGame.hardcoded.instruction, "playInstruction");
	else
	{
		if (BirdGame.optionCnt < 3)
			getDuration(Utils.Path + 'sounds/BirdNameSound/' + BirdGame.tempArr[BirdGame.uniqueImgArr[BirdGame.optionCnt]].birdNameAudio, "play");
		else
			getDuration(Utils.Path + 'sounds/instruction/' + BirdGame.hardcoded.instruction, "playInstruction");
	}
}
function getDuration(src, functionName) {
	var duration = 0;
	if (BirdGame.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			BirdGame.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			if (functionName == "playInstruction")
				BirdGame.playNextSound(duration);
			else
				BirdGame.playOptionsInLoop(duration);
		});
		$('#playSound').prop('src', src);
	}
} 

BirdGame.playOptionsInLoop = function (duration)						//play option sounds in a loop
{
	$("#pictureimg" + BirdGame.optionCnt).addClass("animated zoomIn");
	$("#soundDiv").css({ "pointer-events": "none" });
	clearTimeout(BirdGame.instructionTimer);
	document.getElementById('playSound').play();
	if (BirdGame.optionTimer) {
		clearTimeout(BirdGame.optionTimer);
		BirdGame.optionTimer = null;
	}
	BirdGame.optionTimer = setTimeout(function () {
		$("#pictureimg" + BirdGame.optionCnt).removeClass("animated zoomIn");
		BirdGame.optionCnt++;
		if (BirdGame.optionCnt > 2) {
			clearTimeout(BirdGame.optionTimer);
			setTimeout(function () { BirdGame.playInstruction(); }, 1000);
		}
		else
			BirdGame.playInstruction();
	}, duration * 2000);
}

BirdGame.playNextSound = function (duration)			//function for instruction
{
	document.getElementById('playSound').play();
	if (BirdGame.instructionTimer) {
		clearTimeout(BirdGame.instructionTimer);
		BirdGame.instructionTimer = null;
	}
	BirdGame.instructionTimer = setTimeout(function () {
		document.getElementById('playSound').pause();
		if(BirdGame.finalInstrFlag == true)
				BirdGame.playLastInstruction();
		document.getElementById('playSound').src = Utils.Path + 'sounds/BirdNameSound/' + BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].birdNameAudio;
		document.getElementById('playSound').play();
		setTimeout(function () {
			if (BirdGame.objPointerFlag) {
				BirdGame.objPointerFlag = false;
				$(".borderClass").css({ "pointer-events": "auto" });
			}
			$(".optionClass,#soundDiv").css({ "pointer-events": "auto" });
		}, duration * 800);
	}, duration * 1000);
}

BirdGame.checkAnswer = function (element) {							//Check Answer
	var randomSound;
	$(".optionClass").css("pointer-events", "auto");
	BirdGame.skipFlag = false;
	clearTimeout(BirdGame.instructionTimer);
	if (wrongCnt == 0){
		scoredMarks = 10;
		//BirdGame.correctCounter++;
	}
	else if (wrongCnt == 1)
		scoredMarks = 5;
	if (($(element).data('ans') == BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].Bird_name_marathi)) {
		BirdGame.correctCounter++;
		correctCnt++;
		$(element).addClass("animated zoomIn");
		randomSound = Math.floor(Math.random() * (BirdGame.correctAns.length));
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + BirdGame.correctAns[randomSound];
		document.getElementById('playSound').play();

		console.log(BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].Bird_name_marathi, totalLength, type);
		if (Utils.mobileDeviceFlag)
			Android.addLearntData(BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].Bird_name_marathi, totalLength, type);
		BirdGame.calculateScore();
	}
	else {
		wrongCnt++;
		$(element).css({ "pointer-events": "none", "opacity": "0.5" });
		$(element).addClass("animated shake");
		BirdGame.attemptFlag = true;
		randomSound = Math.floor(Math.random() * (BirdGame.wrongAns.length));
		if (wrongCnt == 2)
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
		else
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + BirdGame.wrongAns[randomSound];
		document.getElementById('playSound').play();
		setTimeout(function () {
			$(element).removeClass("animated shake");
		}, 1500);
	}
	if (wrongCnt == 2 || correctCnt == 1) {
		$(".borderClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
		if (BirdGame.nextQ) {
			clearTimeout(BirdGame.nextQ);
			BirdGame.nextQ = null;
		}
		BirdGame.nextQ = setTimeout(function () {
			BirdGame.nextQuestion();
			$(element).removeClass("animated zoomIn");
		}, 3000);
	}
}
BirdGame.nextQuestion = function () {			//Loads Next Question
	
	clearTimeout(BirdGame.instructionTimer);
	clearTimeout(BirdGame.optionTimer);
	$(".borderClass").removeClass("animated zoomIn animated shake");
	if (BirdGame.attemptFlag) {
		scoredMarks = 0;
		BirdGame.attemptFlag = false;
		BirdGame.calculateScore();
	}
	if (BirdGame.skipFlag) {
		scoredMarks = -1;
		BirdGame.calculateScore();
	}
	wrongCnt = 0;
	correctCnt = 0;
	BirdGame.skipedQ++;
	clearTimeout(BirdGame.nextQ);
	document.getElementById('playSound').pause();
	$(".borderClass").css({ "pointer-events": "auto", "opacity": "1" });
	//BirdGame.tempArr.splice(BirdGame.uniqueImgArr[BirdGame.uniqueQue], 1);
	if (BirdGame.skipedQ == 5) {
		clearTimeout(BirdGame.instructionTimer);
		clearTimeout(BirdGame.optionTimer);
		document.getElementById('playSound').pause();
		$('#endpage').show();
		$('#gamepage,#acknowledgementDiv').hide();
		$("#message").text(BirdGame.hardcoded.gameOver);
		$("#instruction").text(BirdGame.hardcoded.instructionText);
		$("#message").css("visibility", "visible");
		$("#instruction").css("visibility", "visible");
		BirdGame.createHardcodeddivs();
		BirdGame.createStars();
    	BirdGame.giveStars();
		//document.getElementById("endpage").style.backgroundImage = "url(" + Utils.Path + "images/skin/board.png)";
	}
	else
		BirdGame.showObjects(BirdGame.levelNumber);
}
BirdGame.createHardcodeddivs = function () {
	var ackDiv;
	for (var i = 0; i < Object.keys(BirdGame.acknowledgementData).length; i++) {
		ackDiv = document.createElement("div");
		ackDiv.setAttribute("id", "ack" + i);
		ackDiv.setAttribute("class", "firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
		ackDiv.innerHTML = Object.keys(BirdGame.acknowledgementData)[i] + " : " + Object.values(BirdGame.acknowledgementData)[i];
		document.getElementById("acknowledgementDiv").appendChild(ackDiv);
	}
	div = document.createElement('div');
	div.className = "fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML = BirdGame.hardcoded['createdOn'];
	document.getElementById("acknowledgementDiv").appendChild(div);
}
BirdGame.callHome = function () {
	BirdGame.resetAll();
	if (BirdGame.attemptFlag) {
		scoredMarks = 0;
		BirdGame.attemptFlag = false;
		BirdGame.calculateScore();
	}
	location.reload(true);
}
BirdGame.playAgain = function () {
	BirdGame.resetAll();
	document.getElementById('playSound').pause();
	document.getElementById("acknowledgementDiv").scrollTop = '0px';			//Always scroll the slider to the Top at the beginning. 
	$(".borderClass").removeClass("animated zoomIn animated shake");
	$("#message").css("visibility", "visible");
	$("#instruction").css("visibility", "visible");
	$("#endpage").hide();
	$("#gamepage").show();
	BirdGame.skipedQ = 0;
	wrongCnt = 0;
	correctCnt = 0;
	BirdGame.alreadyShownObject = [];
	BirdGame.tempArr = [];
	BirdGame.tempArr = JSON.parse(JSON.stringify(BirdGame.data.list[BirdGame.levelNumber].data));
	BirdGame.showObjects(BirdGame.levelNumber);
}
BirdGame.resetAll = function () {
	wrongCnt = 0;
	correctCnt = 0;
	BirdGame.optionCnt = 0;
	BirdGame.correctCounter = 0;
	document.getElementById('playSound').pause();
	document.getElementById('starsDiv').innerHTML = '';
	BirdGame.skipFlag = true;
	clearTimeout(BirdGame.nextQ);
	clearTimeout(BirdGame.instructionTimer);
	clearTimeout(BirdGame.optionTimer);
}
BirdGame.calculateScore = function () {
	BirdGame.attemptFlag = false;
	console.log(resId, questionId, scoredMarks, totalMarks,2, startTime, BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].Bird_name_marathi);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks,2, startTime, BirdGame.tempArr[BirdGame.queArr[BirdGame.skipedQ]].Bird_name_marathi);
}
BirdGame.showCredit = function () {
	$("#acknowledgementDiv").show();
	document.getElementById('playSound').pause();
}

BirdGame.createStars=function()	//function which creates star divs.
{
	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/skin/star1.png");
		$(newDiv).append(newImage);
		$("#starsDiv").append(newDiv);
	}
}

BirdGame.giveStars = function () 	//calculate stars
{
	clearInterval(BirdGame.noResponseTimer);
	var i,temp;
	numberOfStars = 0,
	ans = BirdGame.total_No_of_Questions / 5;
	temp = BirdGame.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/skin/star2.png");
	$("#starsDiv").css("visibility", "visible");
	if(numberOfStars!=0)
		BirdGame.starInstruction();
	else{
		document.getElementById("playSound").src=Utils.Path+"sounds/instruction/finalInstruction.mp3";
		document.getElementById("playSound").play();
	}
	if (Utils.mobileDeviceFlag)
	Android.StudentCertification(BirdGame.correctCounter, BirdGame.total_No_of_Questions, "8");
}

BirdGame.starInstruction = function () {
	BirdGame.soundFlag=true;
	BirdGame.finalInstrFlag = true;
	src = Utils.Path+"sounds/instruction/"+"Star"+numberOfStars+".mp3";
	getDuration(src, "playInstruction");
}

BirdGame.playLastInstruction = function(){
	document.getElementById("playSound").src=Utils.Path+"sounds/instruction/finalInstruction.mp3";
	document.getElementById("playSound").play();
	BirdGame.finalInstrFlag = false;
}