//29th August 2019
var Composition = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 10, wrongCnt = 0, totalLength = 0, correctCnt = 0, quesCnt = 0, type = "sentence";
Composition.questionArr = [];								//5 question Array
Composition.quesSplitArr = [];							//correct english text splitted array
Composition.skipFlag = true;							//Q skip Flag
Composition.seconds = 0;								//5 sec timer
Composition.skipedQ = 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,#endpag,#robotDiv,#widgetDiv").hide();
		$("#playGame").addClass("animated rotateInUpLeft");
		$("#coverpage").show();
		Composition.setImages();
	}, 300);
});
Composition.setImages = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + Composition.coverImage + ")";
	$("#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/Skip.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");
	$("#checkImg").prop('src', Utils.Path + "images/skin/check.png");
	$("#nextGameImage").prop('src', Utils.Path + "images/skin/Next.png");
	$("#questionDiv").css("backgroundImage", "url(" + Utils.Path + "images/skin/text_box.png");
}
Composition.playGame = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
	$("#gamepage,#robotDiv,#widgetDiv").show();
	$("#coverpage").hide();
	Composition.questionArr = populate(Composition.data, Composition.questionArr, 5);
	Composition.createStars();
	Composition.createOptionDivs(modalDiv);
	Composition.showSentence();
	Composition.playInstruction();
}
Composition.createStars = function () {					//5 stars 
	var newImage, newDiv, i, numberOfStars = 5;
	for (i = 1; i <= 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);
	}
	$("#starDiv").css("visibility", "hidden");
};
Composition.createOptionDivs = function (parentDiv) {			//modal options
	var optionDiv;
	for (var i = 0; i < 3; i++) {
		optionDiv = document.createElement("div");
		optionDiv.setAttribute("id", 'optionDiv' + i);
		optionDiv.setAttribute("class", 'noPadding borderClass col-lg-12 col-md-12 col-xs-12 col-sm-12');
		optionDiv.setAttribute("onclick", 'Composition.setWord(this)');
		$(optionDiv).css("backgroundImage", "url(" + Utils.Path + "images/skin/option_box.png)");
		parentDiv.appendChild(optionDiv)
	}

}
Composition.showSentence = function () {			//shows hindi & english text on screen
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	Composition.skipFlag = true;
	$("#hindiTextDiv,#englishWrongTextDiv").text('');
	$(".roboImg").hide();
	$("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
	$("#robotImg1").show();
	$("#helpDiv,#soundDiv,#checkDiv,#nextDiv").addClass("animated rotateInUpLeft");
	$("#message").css("visibility", "hidden");
	var engSentence = Composition.data[Composition.questionArr[quesCnt]].sentence.replace(' .', '.');
	Composition.quesSplitArr = engSentence.split(' ');
	Composition.hindiSplitArr = Composition.data[Composition.questionArr[quesCnt]].lang_sentence.split(' ');
	$("#englishWrongTextDiv").children().css("color", "white");
	Composition.createHindiSentence(hindiTextDiv, Composition.hindiSplitArr.length);
	Composition.createEnglishSentence(englishWrongTextDiv, Composition.quesSplitArr.length);

	if (Composition.showRobot) {
		Composition.showRobot = null;
		clearInterval(Composition.showRobot);
	}
	Composition.showRobot = setInterval(function () {
		var randomRobot = Math.floor(Math.random() * 2) + 1;
		$(".roboImg").hide();
		$("#robotImg" + randomRobot).show();
	}, 3000);

}
Composition.createHindiSentence = function (parentDiv, length) { 	//create hindi word span
	var span;
	for (var j = 0; j < length;) {
		var wordFoundFlag = false;
		span = document.createElement("span");
		for (var k = 0; k < Composition.data[Composition.questionArr[quesCnt]].list.length; k++) {
			var tempArr = [];
			tempArr = Composition.data[Composition.questionArr[quesCnt]].list[k].correctWord.trim().split(' ');
			if (tempArr.includes(Composition.hindiSplitArr[j])) {
				$(span).text(Composition.data[Composition.questionArr[quesCnt]].list[k].correctWord.trim() + " ");
				wordFoundFlag = true;
				j = j + tempArr.length;
				break;
			}
		}
		if (wordFoundFlag == false) {
			$(span).text(Composition.hindiSplitArr[j] + " ");
			$(span).data("value", Composition.hindiSplitArr[j]);
			j++;
		}
		parentDiv.appendChild(span);
	}
}
Composition.createEnglishSentence = function (parentDiv, length) {  //create english word span
	var span, wCnt = 0, sentenceCnt = 0;
	loop1:
	for (var j = 0; j < length;) {
		var wordFoundFlag = false;
		wCnt = 0;
		span = document.createElement("span");
		span.setAttribute("id", 'span' + j);
		loop2:
		for (var k = sentenceCnt; k < Composition.data[Composition.questionArr[quesCnt]].list.length; k++) {
			var tempArr = [];
			var correctLang = Composition.data[Composition.questionArr[quesCnt]].list[k].correctLang.replace(' .', '.');
			tempArr = correctLang.trim().split(' ');
			loop3:
			for (var i = 0; i < tempArr.length; i++) {
				if (tempArr.includes(Composition.quesSplitArr[j])) {
					wordFoundFlag = true;
					wCnt++;
					j++;
				}
				else
					wordFoundFlag = false;
				if (wCnt == tempArr.length) {
					var randomOption = Math.floor(Math.random() * Composition.data[Composition.questionArr[quesCnt]].list[k].option.length);
					var option = Composition.data[Composition.questionArr[quesCnt]].list[k].option[randomOption].replace(' .', '.');
					$(span).text(option.trim() + " ");
					var correctOption = Composition.data[Composition.questionArr[quesCnt]].list[k].correctLang.replace(' .', '.');
					$(span).data("value", correctOption.trim());
					wordFoundFlag = true;
					span.setAttribute("onclick", "Composition.showOptions(this)");
					$(span).css('color', 'cyan');
					sentenceCnt++;
					break loop2;
				}
			}
		}
		if (wordFoundFlag == false) {
			if (wCnt != 0)
				j = j - wCnt;
			$(span).text(Composition.quesSplitArr[j] + " ");
			$(span).data("value", Composition.quesSplitArr[j]);
			j++;
		}
		parentDiv.appendChild(span);
	}
	questionId = Composition.data[Composition.questionArr[quesCnt]].questionId;
}
Composition.showOptions = function (element) {		//show options in modal 
	var optionArr = [], wordCnt = 0;

	Composition.closeModal();
	clearInterval(Composition.noResponseTimer);
	clearTimeout(Composition.timeOut);
	document.getElementById('playSound').pause();
	document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
	document.getElementById('playSound').play();
	optionArr.push($(element).data("value"));
	for (var i = 0; i < Composition.data[Composition.questionArr[quesCnt]].list.length; i++) {
		var correctOption = Composition.data[Composition.questionArr[quesCnt]].list[i].correctLang.replace(' .', '.');
		if ($(element).data("value") == correctOption.trim()) {
			for (var k = 0; k < $("#hindiTextDiv").children().length; k++) {
				if ($($("#hindiTextDiv").children()[k]).text().trim().includes(Composition.data[Composition.questionArr[quesCnt]].list[i].correctWord.trim())) {
					$($("#hindiTextDiv").children()[k]).css('color', '#eff00f');
					break;
				}

			}
			for (var j = 0; j < Composition.data[Composition.questionArr[quesCnt]].list[i].option.length; j++)
				optionArr.push(Composition.data[Composition.questionArr[quesCnt]].list[i].option[j])
			break;
		}
	}
	shuffleArray(optionArr);
	for (var i = 0; i < 3; i++) {
		var opt = optionArr[wordCnt].replace(' .', '.');
		$('#optionDiv' + i).text(opt);
		wordCnt++;
	}
	if (Composition.showModal) {
		clearTimeout(Composition.showModal);
		Composition.showModal = null;
	}
	Composition.showModal = setTimeout(function () {
		$("#modalRoot").addClass("slideInDownCls");
		$("#modalRoot").show();
	}, 50);

	Composition.clickedWord = $(element);
	$(element).css('color', '#eff00f');
	Composition.startTimer();
}
Composition.setWord = function (element) {			//set selected option to sentence
	document.getElementById('playSound').pause();
	/* document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
	document.getElementById('playSound').play(); */
	clearInterval(Composition.noResponseTimer);
	$(".borderClass").css("color", "white");
	$(element).css("color", "yellow");
	Composition.clickedWord.text($(element).text() + " ");
	Composition.startTimer();
}
Composition.closeModal = function () {					//close modal
	$("#modalRoot").removeClass("slideInDownCls");
	clearInterval(Composition.noResponseTimer);
	$(".borderClass").css("color", "white");
	document.getElementById('playSound').pause();
	$("#modalRoot").hide();
	$(Composition.clickedWord).css('color', 'cyan');
	$("#hindiTextDiv").children().css("color", "white");
	Composition.startTimer();
}
Composition.playInstruction = function () {		// plays instruction
	Composition.seconds = 0;
	clearTimeout(Composition.timeOut);
	clearInterval(Composition.noResponseTimer);
	getDuration(Utils.Path + 'sounds/instruction/' + Composition.hardcoded.instruction);
}
function getDuration(src) {
	var duration = 0;
	//if (ShowMe.soundFlag) {
	$('#playSound').on("loadedmetadata", function () {
		duration = $('#playSound').prop('duration');
		$('#playSound').unbind("loadedmetadata");
		Composition.playNextSound(duration);
	});
	$('#playSound').prop('src', src);
}
Composition.playNextSound = function (duration)								//function for instruction
{
	document.getElementById('playSound').play();
	if (Composition.instructionTimer) {
		clearTimeout(Composition.instructionTimer);
		Composition.instructionTimer = null;
	}
	Composition.instructionTimer = setTimeout(function () {
		Composition.startTimer();
	}, duration * 1000);
}
Composition.startTimer = function () {						//5 second timer (No responce Sound)
	$("#nextImage").css({ "pointer-events": "auto" });
	if (Composition.noResponseTimer) {
		clearInterval(Composition.noResponseTimer);
		Composition.noResponseTimer = null;
		Composition.seconds = 0;
	}
	Composition.noResponseTimer = setInterval(function () {
		Composition.seconds++;
		if (Composition.seconds >= 10) {
			document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + Composition.hardcoded.noResponce;
			document.getElementById("playSound").play();
			$(".pointerClass").css("pointer-events", "auto");
			clearInterval(Composition.noResponseTimer)
			if (Composition.timeOut) {
				clearTimeout(Composition.timeOut);
				Composition.timeOut = null;
			}
			Composition.timeOut = setTimeout(function () {
				Composition.seconds = 0;
				Composition.startTimer();
			}, 2000);
		}
	}, 1000);
}
Composition.checkAnswer = function () {					//check answer
	document.getElementById('playSound').pause();
	clearInterval(Composition.showRobot);
	clearInterval(Composition.noResponseTimer);
	Composition.closeModal();
	$("#soundDiv,#checkDiv,#nextDiv").removeClass("animated rotateInUpLeft");
	$(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
	$(".roboImg").hide();
	Composition.skipFlag = false;
	correctWordCntr = 0;
	$('span,#checkImg').css("pointer-events", "none");
	for (var i = 0; i < Composition.quesSplitArr.length; i++) {			//count total correct keywords
		if ($($("#englishWrongTextDiv").children()[i]).data("value") != null)
			if ($($("#englishWrongTextDiv").children()[i]).data("value") == $($("#englishWrongTextDiv").children()[i]).text().trim())
				correctWordCntr++;
			else {
				$($("#englishWrongTextDiv").children()[i]).css("color", "#790606");
			}
	}
	if (correctWordCntr == $("#englishWrongTextDiv").children().length) {
		correctCnt++;
		scoredMarks = 10;
		$("#englishWrongTextDiv").children().css({ "color": "#0bf50b", "pointer-events": "none" });
		//var random = Math.floor(Math.random() * Composition.correctAns.length)
		$("#englishWrongTextDiv").addClass('animated zoomIn');
		document.getElementById('playSound').src = Utils.Path + 'sounds/' + Composition.data[Composition.questionArr[quesCnt]].sound;
		document.getElementById('playSound').play();
		$("#robotImg2").prop('src', Utils.Path + "images/skin/robo-happy.gif");
		$("#robotImg2").show();
		console.log(Composition.data[Composition.questionArr[quesCnt]].sentence, Composition.data.length, type);
		if (Utils.mobileDeviceFlag)
			Android.addLearntData(Composition.data[Composition.questionArr[quesCnt]].sentence, Composition.data.length, type);
	}
	else {
		scoredMarks = 0;
		var random = Math.floor(Math.random() * Composition.wrongAns.length)
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
		document.getElementById('playSound').play();
		$("#robotImg1").prop('src', Utils.Path + "images/skin/robo-sad.gif");
		$("#robotImg1").show();
	}
	Composition.calculateScore();
	Composition.questionArr.splice(quesCnt, 1);
	if (Composition.showCharacter) {
		clearTimeout(Composition.showCharacter);
		Composition.showCharacter = null;
	}
	Composition.showCharacter = setTimeout(function () {
		Composition.nextQuestion();
	}, 3000);
}
Composition.nextQuestion = function () {						//Loads Next Question
	$("#soundDiv,#checkDiv,#nextDiv").removeClass("animated rotateInUpLeft");
	$("#modalRoot").hide();
	$("#nextDiv").removeClass("blink_me");
	$(".opacityCls").css({ 'opacity': '1', 'pointer-events': 'auto' });
	Composition.skipedQ++;
	clearTimeout(Composition.showModal);
	if (Composition.skipFlag)
		quesCnt++;
	clearTimeout(Composition.timeOut);
	clearInterval(Composition.showRobot);
	clearInterval(Composition.noResponseTimer);
	clearTimeout(Composition.instructionTimer);
	document.getElementById('playSound').pause();
	$('span,#checkImg').css("pointer-events", "auto");
	document.getElementById('playSound').pause();
	$("#checkDiv").show();
	$("#englishWrongTextDiv").removeClass('magictime vanishIn');
	$("#englishWrongTextDiv").css('box-shadow', 'none');
	clearTimeout(Composition.showCharacter);
	if (Composition.questionArr.length == 0)
		Composition.lastPage();
	else if (quesCnt == Composition.questionArr.length) {
		$('#responseBoxDiv').show();
		$('#confiramtionText').text(Composition.hardcoded.message);
	}
	else {
		Composition.showSentence();
		Composition.startTimer();
	}

}
Composition.showNext = function (element) {				//onclick of Yes/No modal option
	if ($(element).text() == "No")
		Composition.lastPage();
	else
		Composition.showRemaining();
}
Composition.lastPage = function () {					//show last page
	clearInterval(Composition.noResponseTimer);
	document.getElementById('playSound').pause();
	$('#endpage').show();
	$('#responseBoxDiv,#gamepage,#widgetDiv').hide();
	$("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
	$("#message").text(Composition.hardcoded.gameOver);
	$("#message").css("visibility", "visible");
	Composition.giveStars();
	console.log(correctCnt, Composition.skipedQ);
	if (Utils.mobileDeviceFlag)
		Android.StudentCertification(correctCnt, Composition.skipedQ, "8");
}
Composition.giveStars = function () {					//calculates stars
	var i, numberOfStars = correctCnt;
	for (i = 1; i <= numberOfStars; i++)
		document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
	$("#starDiv").css("visibility", "visible");
	if (correctCnt != 0) {
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + 'Star' + correctCnt + '.mp3';
		document.getElementById('playSound').play();
	}
};
Composition.showRemaining = function () {				//show remaining questions
	quesCnt = 0;
	$('#responseBoxDiv').hide();
	$('#gamepage').show();
	$("#soundDiv").css("visibility", "visible");
	Composition.showSentence();
}
Composition.calculateScore = function () {
	console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Composition.data[Composition.questionArr[quesCnt]].sentence);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Composition.data[Composition.questionArr[quesCnt]].sentence);
}
Composition.nextGame = function () {
	if (Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}