//4th May 2019
var ShowMe = {};
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;
ShowMe.skipedQ = 0;
ShowMe.alreadyShownObject = [];
ShowMe.tempArr = [];								//json data
ShowMe.queArr=[];
ShowMe.skipFlag = true;
ShowMe.attemptFlag = false;
ShowMe.objPointerFlag = true;						//image clicked flag
ShowMe.optionCnt = 0;			//counter for playing optionin sequence
ShowMe.levelNumber = 0;			//false for learn & true for practice
ShowMe.total_No_of_Questions=5;
ShowMe.correctCounter=0;
//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();
		ShowMe.init();
		ShowMe.setImages();
	}, 300);
});
ShowMe.init = function () {

	/* var categoryName;
	if (Utils.mobileDeviceFlag) {
	//	categoryName = Android.getCategory();
		for (var i = 0; i < ShowMe.data.list.length; i++) {
			if (ShowMe.data.list[i].name.includes(categoryName)) {
				ShowMe.levelNumber = i;
				break;
			}
		}
	//	ShowMe.levelName=Android.isPractice();
	}
	else */
		ShowMe.levelNumber = Math.floor(Math.random() * ShowMe.data.list.length);
	totalLength = ShowMe.data.list[ShowMe.levelNumber].data.length;
	console.log(totalLength + " " + type);
}
ShowMe.setImages = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + ShowMe.coverImage + ")";
	document.getElementById("showMePageDiv").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");
}
ShowMe.playGame = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
	$("#homeImg,#gamepage").show();
	$("#coverpage").hide();
	document.getElementById("showMePageDiv").innerHTML="";
	ShowMe.createDivs(showMePageDiv, "picture", "pictureClass  noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3 col-lg-offset-1 col-md-offset-1 col-xs-offset-1 col-sm-offset-1", 3);
	$(".borderClass").css("backgroundImage", "url(images/skin/blue_pach.png)");
	ShowMe.selectLevel();
	ShowMe.populate();
	ShowMe.showObjects();
}
//creates No. of Divs
ShowMe.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("span");
		textDiv.setAttribute("id", id + "text" + j);
		textDiv.setAttribute("class", 'textDivCss');
		pictureDiv.appendChild(textDiv);

		textDiv = document.createElement("span");
		textDiv.setAttribute("id", id + "Etext" + j);
		textDiv.setAttribute("class", 'textDivCss');
		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", "ShowMe.checkAnswer(this)");
		if (!ShowMe.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);
		}
	}
}
ShowMe.selectLevel = function (element) { 							//selects level
	ShowMe.skipedQ = 0;
	ShowMe.alreadyShownObject = [];
	$("#message").css("visibility", "hidden");
	ShowMe.tempArr = JSON.parse(JSON.stringify(ShowMe.data.list[ShowMe.levelNumber].data));
	shuffleArray(ShowMe.tempArr);
}
ShowMe.populate = function () {
	ShowMe.queArr=[];
	ShowMe.queArr = populate(ShowMe.tempArr, ShowMe.queArr, 5);
}
ShowMe.options = function () {
	ShowMe.uniqueImgArr = [];
	ShowMe.uniqueImgArr.push(ShowMe.queArr[ShowMe.skipedQ]);
	ShowMe.uniqueImgArr = populate(ShowMe.tempArr, ShowMe.uniqueImgArr, 3);
	shuffleArray(ShowMe.uniqueImgArr);
	ShowMe.uniqueQue = ShowMe.queArr[ShowMe.skipedQ];	//get unique Question
	questionId = ShowMe.tempArr[ShowMe.queArr[ShowMe.skipedQ]].qid;
}
//Show Objects on the screen
ShowMe.showObjects = function () {							//display  images levelwise 
	var d;
	ShowMe.optionCnt = 0;
	ShowMe.skipFlag = true;
	ShowMe.objPointerFlag = true;
	ShowMe.options();
	$("#acknowledgementDiv").text('');
	clearTimeout(ShowMe.optionTimer);
	clearTimeout(ShowMe.instructionTimer);
	$("#message").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
		$("#pictureimg" + j).prop("src", Utils.Path + "images/" + ShowMe.tempArr[ShowMe.uniqueImgArr[j]].Image);
		$("#pictureimg" + j).data("ans", ShowMe.tempArr[ShowMe.uniqueImgArr[j]].Bird_name_marathi);
		document.getElementById("picturetext" + j).innerHTML = ShowMe.tempArr[ShowMe.uniqueImgArr[j]].Bird_name_marathi;
		document.getElementById("pictureEtext" + j).innerHTML = ShowMe.tempArr[ShowMe.uniqueImgArr[j]].Bird_name_devnagari;
	}
	$(".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);
	} );
	function incrementCounter()
	{
		counter++;
		if ( counter === len )
		{
			console.log( 'All images loaded!');
			$(".loader").hide();
			if(ShowMe.skipedQ == 0)
				ShowMe.playInstruction();
			else
				document.getElementById('playSound').src = Utils.Path + 'sounds/' + ShowMe.tempArr[ShowMe.queArr[ShowMe.skipedQ]].birdVoiceAudio;
			console.log( 'playSound');
			document.getElementById('playSound').play();
		}
	}
}
ShowMe.playInstruction = function () {		// plays sound of instruction/options
	ShowMe.soundFlag = true;
	$(".optionClass").css("pointer-events", "none");
	if (ShowMe.objPointerFlag)
		$(".borderClass").css({ "pointer-events": "none" });
	getDuration(Utils.Path + 'sounds/instruction/' + ShowMe.hardcoded.instruction);
}
function getDuration(src) {
	var duration = 0;
	if (ShowMe.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			ShowMe.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			if (ShowMe.skipedQ == 5)
				ShowMe.playInstructionSound(duration);
			else
				ShowMe.playNextSound(duration);
		});
		$('#playSound').prop('src', src);
	}
}

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

		console.log(ShowMe.tempArr[ShowMe.queArr[ShowMe.skipedQ]].Bird_name_marathi, totalLength, type);
		if (Utils.mobileDeviceFlag)
			Android.addLearntData(ShowMe.tempArr[ShowMe.queArr[ShowMe.skipedQ]].Bird_name_marathi, totalLength, type);
		ShowMe.calculateScore();
	}
	else {
		wrongCnt++;
		$(element).css({ "pointer-events": "none", "opacity": "0.5" });
		$(element).addClass("animated shake");
		ShowMe.attemptFlag = true;
		randomSound = Math.floor(Math.random() * (ShowMe.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/' + ShowMe.wrongAns[randomSound];
		document.getElementById('playSound').play();
		setTimeout(function () {
			$(element).removeClass("animated shake");
			$("#soundDiv").css({ "pointer-events": "auto" });
		}, 1500);
	}
	if (wrongCnt == 2 || correctCnt == 1) {
		$(".borderClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
		if (ShowMe.nextQ) {
			clearTimeout(ShowMe.nextQ);
			ShowMe.nextQ = null;
		}
		ShowMe.nextQ = setTimeout(function () {
			ShowMe.nextQuestion();
			$(element).removeClass("animated zoomIn");
		}, 3000);
	}
}
ShowMe.nextQuestion = function () {				//Loads Next Question
	clearTimeout(ShowMe.instructionTimer);
	clearTimeout(ShowMe.optionTimer);
	$(".borderClass").removeClass("animated zoomIn animated shake");
	if (ShowMe.attemptFlag) {
		scoredMarks = 0;
		ShowMe.attemptFlag = false;
		ShowMe.calculateScore();
	}
	if (ShowMe.skipFlag) {
		scoredMarks = -1;
		ShowMe.calculateScore();
	}
	wrongCnt = 0;
	correctCnt = 0;
	ShowMe.skipedQ++;
	clearTimeout(ShowMe.nextQ);
	document.getElementById('playSound').pause();
	$(".borderClass").css({ "pointer-events": "auto", "opacity": "1" });
	//ShowMe.tempArr.splice(ShowMe.uniqueImgArr[ShowMe.uniqueQue], 1);
	if (ShowMe.skipedQ == 5) {
		clearTimeout(ShowMe.instructionTimer);
		clearTimeout(ShowMe.optionTimer);
		document.getElementById('playSound').pause();
		$('#endpage').show();
		$('#gamepage,#acknowledgementDiv').hide();
		//$("#message").text(ShowMe.hardcoded.gameOver);
		$("#instructionText").text(ShowMe.hardcoded.instructionText);
		$("#message").css("visibility", "visible");
		ShowMe.createHardcodeddivs();
	//	document.getElementById("endpage").style.backgroundImage = "url(" + Utils.Path + "images/skin/board.png)";
		ShowMe.createStars();
		ShowMe.giveStars();
	}
	else
		ShowMe.showObjects(ShowMe.levelNumber);
}
ShowMe.createHardcodeddivs = function () {
	var ackDiv;
	for (var i = 0; i < Object.keys(ShowMe.acknowledgementData).length; i++) {
		ackDiv = document.createElement("div");
		ackDiv.setAttribute("id", "ack" + i);
		ackDiv.setAttribute("class", "noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
		ackDiv.innerHTML = Object.keys(ShowMe.acknowledgementData)[i] + " : " + Object.values(ShowMe.acknowledgementData)[i];
		document.getElementById("acknowledgementDiv").appendChild(ackDiv);
	}
	div = document.createElement('div');
	div.className = "noPadding fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML = ShowMe.hardcoded['createdOn'];
	document.getElementById("acknowledgementDiv").appendChild(div);
	for (var i = 0; i < 2; i++)
	{
		var extradiv=document.createElement("div");
		$(extradiv).prop('class', 'noPadding fontClass col-md-12 col-xs-12 col-lg-12 col-sm-12');
		$(extradiv).text(ShowMe.extraInfo[i]);
        $(extradiv).css("font-size","1.9vw");
		$(extraInfo).append(extradiv)
	}
}
ShowMe.callHome = function () {
	ShowMe.resetAll();
	if (ShowMe.attemptFlag) {
		scoredMarks = 0;
		ShowMe.attemptFlag = false;
		ShowMe.calculateScore();
	}
	location.reload(true);
}
ShowMe.playAgain = function () {
	clearTimeout(ShowMe.endInstructionTimer);
	ShowMe.resetAll();
	$(".borderClass").removeClass("animated zoomIn animated shake");
	$("#message").css("visibility", "visible");
	$("#endpage").hide();
	$("#gamepage").show();
	ShowMe.skipedQ = 0;
	wrongCnt = 0;
	correctCnt = 0;
	ShowMe.playGame();
	ShowMe.alreadyShownObject = [];
	ShowMe.tempArr = [];
	ShowMe.tempArr = JSON.parse(JSON.stringify(ShowMe.data.list[ShowMe.levelNumber].data));
	ShowMe.showObjects(ShowMe.levelNumber);
}
ShowMe.resetAll = function () {
	wrongCnt = 0;
	correctCnt = 0;
	ShowMe.optionCnt = 0;
	ShowMe.correctCounter=0;
	document.getElementById('playSound').pause();
	ShowMe.skipFlag = true;
	clearTimeout(ShowMe.nextQ);
	clearTimeout(ShowMe.instructionTimer);
	clearTimeout(ShowMe.optionTimer);
}
ShowMe.calculateScore = function () {
	ShowMe.attemptFlag = false;
	console.log(resId, questionId, scoredMarks, totalMarks,2, startTime, ShowMe.tempArr[ShowMe.queArr[ShowMe.skipedQ]].Bird_name);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks,2, startTime, ShowMe.tempArr[ShowMe.queArr[ShowMe.skipedQ]].Bird_name);
}
ShowMe.showCredit = function () {
	document.getElementById('playSound').pause();
	$("#acknowledgementDiv").show();
}
//function which creates star divs
ShowMe.createStars=function()
{
	document.getElementById("starDiv").innerHTML="";
	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);
		$("#starDiv").append(newDiv);
	}
};

ShowMe.giveStars=function()
{
	var fractionVar,i,temp; 
	var numberOfStars=0;
	ans=ShowMe.total_No_of_Questions/5;
	temp=ShowMe.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");
	/* if(temp>numberOfStars)
	document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/halfStar.png"); */
	$("#starsDiv").css("visibility","visible");
	if(numberOfStars!=0)
	{
		ShowMe.soundFlag = true;
	getDuration(Utils.Path+"sounds/instruction/"+"Star"+numberOfStars+".mp3");
	}
	else
	{
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/finalInstruction.mp3';
		document.getElementById('playSound').play();
	}
	console.log(ShowMe.correctCounter,ShowMe.total_No_of_Questions,"1");
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(ShowMe.correctCounter,ShowMe.total_No_of_Questions,"1");
};
ShowMe.playInstructionSound = function (duration)  //fun for last instruction
{
	document.getElementById('playSound').play();
	if (ShowMe.endInstructionTimer) {
		clearTimeout(ShowMe.endInstructionTimer);
		ShowMe.endInstructionTimer = null;
	}
	ShowMe.endInstructionTimer = setTimeout(function () {
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/finalInstruction.mp3';
		document.getElementById('playSound').play();
	}, duration * 1000);
}