//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.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.homeFlag=null;
ShowMe.levelName = false;
//function for loader
$(document).ready(function () {
	$('title').text(ShowMe.GameName)
	$(".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 () {
		$("#levelpage,#gamepage,#endpage,#homeImg").hide();
		$("#coverpage").show();
		ShowMe.setImages();
	}, 300);
});
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,#levelpage").show();
	$("#coverpage").hide();
	ShowMe.levelDivs()
	ShowMe.createDivs(showMePageDiv, "picture", "pictureClass  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(); 
}
ShowMe.levelDivs = function ()
{
	var level , levelImg , levelname
	for (var i = 0; i < ShowMe.data.list.length;i++) {
		level = document.createElement("div");
		level.setAttribute("id", 'level'+i);
		level.setAttribute("class", "noPadding col-lg-2 col-md-2 col-xs-2 col-sm-2 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		$(level).css('height','65%;')
		$(".levels").append(level);

		levelImg = document.createElement('img');
		levelImg.setAttribute("id","levelImg" + i);
		levelImg.setAttribute("class", " borderClass img-responsive col-lg-12 col-md-12 col-xs-12 col-sm-12");
		levelImg.setAttribute("src", Utils.Path + "images/" + ShowMe.data.list[i].data[0].imgName);
		$(levelImg).data("levelnum",i);
		levelImg.setAttribute("onclick", "ShowMe.selectLevel(this)");
		level.append(levelImg);

		levelname = document.createElement('p');
		levelname.setAttribute("id","levelname" + i);
		levelname.setAttribute("class", " menuNames noPadding text-center col-lg-12 col-md-12 col-xs-12 col-sm-12");
		$(levelname).text(ShowMe.data.list[i].name)
		level.append(levelname)
	}
}
//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) {										//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", "ShowMe.playOptions(this)");
			subImgDiv.appendChild(img);
		}
	}
}
ShowMe.selectLevel = function (element) { 							//selects level
	ShowMe.skipedQ = 0;
	ShowMe.alreadyShownObject = [];
	$("#levelpage").hide();
	$("#gamepage").show();

	ShowMe.levelNumber = $(element).data("levelnum");
	totalLength = ShowMe.data.list[ShowMe.levelNumber].data.length;
	$("#message").css("visibility", "hidden");
	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.homeFlag="showlevel";
	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)
		$(".borderClass").css({ "pointer-events": "none" });
	if (ShowMe.levelName) 
		getDuration(Utils.Path + 'sounds/instruction/' + ShowMe.hardcoded.instruction, "playInstruction");
	else
	{
		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");
	}
}
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");
	$("#soundDiv").css({ "pointer-events": "none" });
	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
{
	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;
				$(".borderClass").css({ "pointer-events": "auto" });
			}
			$(".optionClass,#soundDiv").css({ "pointer-events": "auto" });
		}, duration * 800);
	}, duration * 1000);
}
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.uniqueImgArr[ShowMe.uniqueQue]].name)) {
		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.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).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");
		}, 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
	ShowMe.skipedQ++;
	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;
	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();
		ShowMe.homeFlag=null;
		$('#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();
	}
	if(ShowMe.homeFlag == "showlevel"){
		$("#levelpage").show();
		$("#gamepage,#endpage").hide();
		ShowMe.homeFlag=null;
	}
	else
		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;
	correctCnt = 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;
	correctCnt = 0;
	ShowMe.optionCnt = 0;
	document.getElementById('playSound').pause();
	$(".borderClass").removeClass("animated zoomIn animated shake");
	ShowMe.skipFlag = true;
    $(".borderClass").css({ "pointer-events": "auto", "opacity": "1" });
	clearTimeout(ShowMe.nextQ);
	clearTimeout(ShowMe.instructionTimer);
	clearTimeout(ShowMe.optionTimer);
}
ShowMe.calculateScore = function () {
	ShowMe.attemptFlag = false;
	console.log(resId, questionId, scoredMarks, totalMarks,1, startTime, ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks,1, startTime, ShowMe.tempArr[ShowMe.uniqueImgArr[ShowMe.uniqueQue]].name);
}
ShowMe.showCredit = function () {
	$("#acknowledgementDiv").show();
}