//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";
ShowMe.skipedQ = 0;
ShowMe.alreadyShownObject = [];
ShowMe.tempArr = [];								//json data
ShowMe.skipFlag = true;
ShowMe.attemptFlag = false;
ShowMe.objPointerFlag = true;						//image clicked flag
ShowMe.optionCnt = 0;								//counter for playing optionin sequence
ShowMe.levelNumber=0;
ShowMe.levelName = "Learn";
//function for loader
$(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("Aksharkhadi");  */
	setTimeout(function () {
		$("#gamepage,#endpage,#homeImg").hide();
		$("#coverpage").show();
		ShowMe.init();
		ShowMe.setImages();
	}, 300);
});
ShowMe.init = function () {

	/* if(Utils.mobileDeviceFlag)
	{
		ShowMe.levelName=Android.getLevel();
		for(var i=0;i<ShowMe.data.list.length;i++)
		{
			if(ShowMe.data.list[i].name.includes(ShowMe.levelName))
			{
				ShowMe.levelNumber=i;
				break;
			}
		}
	}
	else */
		ShowMe.levelNumber=Math.floor(Math.random()*ShowMe.data.list.length);
		/* ShowMe.levelName="Body";
		for(var i=0;i<ShowMe.data.list.length;i++)
		{
			if(ShowMe.data.list[i].name.includes(ShowMe.levelName))
			{
				ShowMe.levelNumber=i;
				break;
			}
		}
 */
	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,#optionDiv1,#optionDiv2,#optionDiv3").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();
	ShowMe.createDivs(showMePageDiv, "picture", "pictureClass pointerClass pointers noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3", 3);
	$(".borderClass").css("backgroundImage", "url(images/skin/blue_pach.png)");
	ShowMe.selectLevel();
}
//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);

		img = document.createElement('img');
		img.setAttribute("id", id + "img" + j);
		img.setAttribute("class", " borderClass img-responsive col-lg-12 col-md-12 col-xs-12 col-sm-12");
		pictureDiv.appendChild(img);
		img.setAttribute("onclick", "ShowMe.checkAnswer(this)");
		if (ShowMe.levelName == "Learn") {
			imgDiv = document.createElement("div");
			imgDiv.setAttribute("class", "optionClass noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
			pictureDiv.appendChild(imgDiv);

			img = document.createElement('img');
			img.setAttribute("class", "img-responsive noPadding col-lg-6 col-md-6 col-xs-6 col-sm-6 col-sm-offset-4 col-lg-offset-4 col-md-offset-4 col-xs-offset-4");
			img.setAttribute("src", Utils.Path + "images/skin/Sound.png");
			$(img).data("ans", j);
			img.setAttribute("onclick", "ShowMe.playOptions(this)");
			imgDiv.appendChild(img);
		}
	}
}
ShowMe.selectLevel = function (element) { 							//selects level
	ShowMe.skipedQ = 0;
	ShowMe.alreadyShownObject = [];
	$("#message").css("visibility", "hidden");
	ShowMe.internalLevelNumber = $(element).data("internalLevel");			//sub level number
	ShowMe.tempArr = JSON.parse(JSON.stringify(ShowMe.data.list[ShowMe.levelNumber].data));
	ShowMe.showObjects();
}
//Show Objects on the screen
ShowMe.showObjects = function () {							//display  images levelwise 
	var d;
	ShowMe.optionCnt = 0;
	ShowMe.skipFlag = true;
	ShowMe.objPointerFlag = true;
	$("#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();
	ShowMe.uniqueImgArr = [];
	ShowMe.uniqueImgArr = populate(ShowMe.tempArr, ShowMe.uniqueImgArr, ShowMe.hardcoded.number);

	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]].imgName);
		$("#pictureimg" + j).data("ans", ShowMe.tempArr[ShowMe.uniqueImgArr[j]].name);
	}
	ShowMe.uniqueQue = Math.floor(Math.random() * (ShowMe.uniqueImgArr.length));	//get unique Question
	while ($.inArray(ShowMe.uniqueImgArr[ShowMe.uniqueQue].name, ShowMe.alreadyShownObject) !== -1)
		ShowMe.uniqueQue = Math.floor(Math.random() * (ShowMe.uniqueImgArr.length));
	ShowMe.alreadyShownObject.push(ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name);
	questionId = parseInt(ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].questionId);
	ShowMe.playInstruction();
}
ShowMe.playOptions = function (element) {		//plays perticular sound for image
	clearTimeout(ShowMe.instructionTimer);
	clearTimeout(ShowMe.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/' + ShowMe.tempArr[ShowMe.uniqueImgArr[data]].sound;
	document.getElementById('playSound').play();
}
ShowMe.playInstruction = function () {		// plays sound of instruction/options
	ShowMe.soundFlag = true;
	$(".optionClass").css("pointer-events", "none");
	if (ShowMe.objPointerFlag)
		$(".pointerClass").css({ "pointer-events": "none" });
	if (ShowMe.levelName == "Learn") {
		if (ShowMe.optionCnt < 3)
			getDuration(Utils.Path + 'sounds/' + ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.optionCnt]].sound, "play");
		else
			getDuration(Utils.Path + 'sounds/instruction/' + ShowMe.hardcoded.instruction, "playInstruction");
	}
	else
		getDuration(Utils.Path + 'sounds/instruction/' + ShowMe.hardcoded.instruction, "playInstruction");
}
function getDuration(src, functionName) {
	var duration = 0;
	if (ShowMe.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			ShowMe.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			if (functionName == "playInstruction")
				ShowMe.playNextSound(duration);
			else
				ShowMe.playOptionsInLoop(duration);
		});
		$('#playSound').prop('src', src);
	}
}
ShowMe.playOptionsInLoop = function (duration)						//play option sounds in a loop
{
	$("#pictureimg" + ShowMe.optionCnt).addClass("animated zoomIn");
	clearTimeout(ShowMe.instructionTimer);
	document.getElementById('playSound').play();
	if (ShowMe.optionTimer) {
		clearTimeout(ShowMe.optionTimer);
		ShowMe.optionTimer = null;
	}
	ShowMe.optionTimer = setTimeout(function () {
		$("#pictureimg" + ShowMe.optionCnt).removeClass("animated zoomIn");
		ShowMe.optionCnt++;
		if (ShowMe.optionCnt > 2) {
			clearTimeout(ShowMe.optionTimer);
			setTimeout(function () { ShowMe.playInstruction(); }, 1000);
		}
		else
			ShowMe.playInstruction();
	}, duration * 2000);
}

ShowMe.playNextSound = function (duration)								//function for instruction
{
	$(".optionClass").css("pointer-events", "auto");
	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.uniqueImgArr[ShowMe.uniqueQue]].sound;
		document.getElementById('playSound').play();
		setTimeout(function () {
			if (ShowMe.objPointerFlag) {
				ShowMe.objPointerFlag = false;
				$(".pointerClass").css({ "pointer-events": "auto" });
			}
		}, duration * 800);
	}, duration * 1000);
}
ShowMe.checkAnswer = function (element) {							//Check Answer
	var randomSound;
	ShowMe.skipFlag = false;
	clearTimeout(ShowMe.instructionTimer);
	if (wrongCnt == 0)
		scoredMarks = 10;
	else if (wrongCnt == 1)
		scoredMarks = 5;
	else
		scoredMarks = 1;
	if (($(element).data('ans') == ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name)) {
		$(".pointerClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
		$(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();
		if (ShowMe.nextQ) {
			clearTimeout(ShowMe.nextQ);
			ShowMe.nextQ = null;
		}
		ShowMe.nextQ = setTimeout(function () {
			ShowMe.nextQuestion();
			$(element).removeClass("animated zoomIn");
		}, 2000);
		console.log(ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name, totalLength, type);
		if (Utils.mobileDeviceFlag)
			Android.addLearntData(ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name, totalLength, type);
		ShowMe.calculateScore();
	}
	else {
		wrongCnt++;
		$(element).parent().css({ "pointer-events": "none", "opacity": "0.5" });
		$(element).addClass("animated shake");
		ShowMe.attemptFlag = true;
		randomSound = Math.floor(Math.random() * (ShowMe.wrongAns.length));
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + ShowMe.wrongAns[randomSound];
		document.getElementById('playSound').play();
		setTimeout(function () {
			$(element).removeClass("animated shake");
		}, 1500);
	}
}
ShowMe.nextQuestion = function () {						//Loads Next Question
	ShowMe.skipedQ++;
	$(".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;
	clearTimeout(ShowMe.nextQ);
	document.getElementById('playSound').pause();
	$(".pointerClass").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);
		$("#message").css("visibility", "visible");
		ShowMe.createHardcodeddivs();
	}
	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);
}
ShowMe.callHome = function () {
	ShowMe.resetAll();
	if (ShowMe.attemptFlag) {
		scoredMarks = 0;
		ShowMe.attemptFlag = false;
		ShowMe.calculateScore();
	}
	location.reload(true);
}
ShowMe.playAgain = function () {
	ShowMe.resetAll();
	$(".borderClass").removeClass("animated zoomIn animated shake");
	$("#message").css("visibility", "visible");
	$("#endpage").hide();
	$("#gamepage").show();
	ShowMe.skipedQ = 0;
	wrongCnt = 0;
	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;
	ShowMe.optionCnt = 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, (ShowMe.levelNumber+1), startTime, ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, (ShowMe.levelNumber+1), startTime, ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name);
}
ShowMe.showCredit = function () {
	$("#acknowledgementDiv").show();
}