//7th May 2019
var Preposition = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
Preposition.loadmetaDataFlag = false;
Preposition.recordClickFlag = false;
Preposition.skipFlag = true;
Preposition.attemptFlag = false;
Preposition.clickSoundFlag = false;
Preposition.showCreditFlag = false;
Preposition.questionAudio;
Preposition.answer = "";
Preposition.punctArr = ['.', ',', '?', '!'];
Preposition.wordsToBeChecked = "";
Preposition.tempArr = [];
Preposition.queCounter = 0;
Preposition.wrongCnt = 0;
Preposition.practice = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 10;
$(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("Preposition");   */
	setTimeout(function () {
		Preposition.init();
		Preposition.setImages();
		Preposition.harcodedData();
	}, 100);
}, 200);
Preposition.init = function () {
	$('#gamePage').hide();
	$('#coverPage').show();
};
Preposition.harcodedData = function () {
	$("#gameOverText").text(Preposition.hardcodedData.gameover);
	$('#conceptBy').text(Preposition.hardcodedData.concept_by);
	$('#mediacontent').text(Preposition.hardcodedData.mediacontent);
	$('#artWork').text(Preposition.hardcodedData.art_work);
	$('#animations').text(Preposition.hardcodedData.animation);
	$('#audioEditing').text(Preposition.hardcodedData.audio_editing);
	$('#music').text(Preposition.hardcodedData.music);
	$('#developerName').text(Preposition.hardcodedData.developed_by);
	$('#date').text(Preposition.hardcodedData.date);
}
// set Images//
Preposition.setImages = function () {
	document.getElementById('play').src = Utils.Path + "images/skin/Play.png";
	document.getElementById('homeImage').src = Utils.Path + "images/skin/Home.png";
	document.getElementById('logoImage').src = Utils.Path + "images/skin/logo.png";
	document.getElementById('soundImg').src = Utils.Path + "images/skin/Sound.png";
	document.getElementById('recordImg').src = Utils.Path + "images/skin/Record.png";
	document.getElementById('replayImg').src = Utils.Path + "images/skin/Replay.png";
	document.getElementById('creditImg').src = Utils.Path + "images/skin/Credit.png";
	document.getElementById('nextImg').src = Utils.Path + "images/skin/Next.png";
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Cover.png)";
};
//function which executes on play button click
Preposition.playGame = function () {
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	$('#coverPage,#animalsCard,#Card').hide();
	$('#homeImage,#imageDiv,#questionText').css('visibility', 'visible');
	$('#logoImage,#gamePage').show();
	Preposition.tempArr = populate(Preposition.data, Preposition.tempArr, 5);
	console.log(Preposition.tempArr);
	Preposition.showQuestion();
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Background.png)";
};
//function which executes on play button click
Preposition.showQuestion = function () {
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	console.log(Preposition.queCounter);
	Preposition.skipFlag = true;
	questionId = Preposition.tempArr[Preposition.queCounter].questionId;
	console.log(questionId);
	$("#questionText").text(Preposition.tempArr[Preposition.queCounter].question);

	if (Preposition.tempArr[Preposition.queCounter].image == null)
		$("#imageOuterDiv").css('visibility', 'hidden');
	else
		$("#imageOuterDiv").css('visibility', 'visible');

	$("#imageOuterDiv").prop('src', Utils.Path + "images/" + Preposition.tempArr[Preposition.queCounter].image);
	Preposition.questionAudio = Preposition.tempArr[Preposition.queCounter].questionSound;

	if (Utils.mobileDeviceFlag)
		Preposition.practice = Android.isPractice();
	if (Preposition.practice) {
		Preposition.playQuestionOnSoundClick();
		$("#answerDiv").css('visibility', 'hidden');
	}
	else {
		$("#answerDiv").data('answerAudio', Preposition.tempArr[Preposition.queCounter].answerSound);
		Preposition.playQuestion();
	}
	Preposition.wordsToBeChecked = Preposition.tempArr[Preposition.queCounter].wordstobechecked;
	Preposition.highlightPreposition(Preposition.tempArr[Preposition.queCounter].answer);
};
Preposition.playQuestion = function () {
	var sound;
	document.getElementById('playSound').pause();
	sound = Utils.Path + "sounds/" + Preposition.questionAudio;
	Preposition.loadmetaDataFlag = true;
	callback = Preposition.playAnswerAudio;
	Preposition.getAudioDuration(sound, callback);
};
Preposition.playQuestionOnSoundClick = function () {
	document.getElementById('playSound').pause();
	clearTimeout(Preposition.instructionTimer);
	clearTimeout(Preposition.playAnswerTimer);
	document.getElementById('playSound').src = Utils.Path + "sounds/" + Preposition.questionAudio;
	document.getElementById('playSound').play();
};
Preposition.playAnswerAudio = function (duration) {
	var sound;
	document.getElementById('playSound').play();
	if (Preposition.playAnswerTimer) {
		clearTimeout(Preposition.playAnswerTimer);
		Preposition.playAnswerTimer = null;
	}
	Preposition.playAnswerTimer = setTimeout(function () {
		document.getElementById('playSound').pause();
		sound = "sounds/" + $("#answerDiv").data('answerAudio');
		Preposition.loadmetaDataFlag = true;
		callback = Preposition.playInstruction;
		Preposition.getAudioDuration(sound, callback);
	}, duration * 1000)
};
Preposition.playInstruction = function (duration) {
	document.getElementById('playSound').play();
	if (Preposition.instructionTimer) {
		clearTimeout(Preposition.instructionTimer);
		Preposition.instructionTimer = null;
	}
	Preposition.instructionTimer = setTimeout(function () {
		document.getElementById('playSound').src = Utils.Path + "sounds/instructions/Now_your_turn.mp3";
		document.getElementById('playSound').play();
	}, duration * 1000);
};
//function which highlights preposition in answer string
Preposition.highlightPreposition = function (str) {
	var index = 0, span1, span2, highlightStr1 = "", highlightStr2 = "", word, preposition = [];
	str = str.trim();
	arr = str.split(' ');
	preposition = Preposition.tempArr[Preposition.queCounter].preposition.split(' ');
	index = arr.indexOf(preposition[0].toLowerCase());
	for (var i = 0; i < index; i++)
		highlightStr1 = highlightStr1 + " " + arr[i];
	span1 = document.createElement("span");
	span1.innerHTML = highlightStr1;
	document.getElementById('answerText').appendChild(span1);

	word = document.createElement("span");
	word.innerHTML = "  " + arr[index];
	$(word).css('color', 'green');
	document.getElementById('answerText').appendChild(word);

	for (var i = index + 1; i < arr.length; i++)
		highlightStr2 = highlightStr2 + " " + arr[i];

	span2 = document.createElement("span");
	span2.innerHTML = highlightStr2;
	document.getElementById('answerText').appendChild(span2);
};
//function which records the answer 
Preposition.record = function () {
	Preposition.skipFlag = false;
	$('#soundImg').css('pointer-events', 'none');
	document.getElementById('playSound').pause();
	clearTimeout(Preposition.playAnswerTimer);
	clearTimeout(Preposition.instructionTimer);

	Preposition.ansString = "";
	if (Preposition.recordClickFlag == false) {
		Preposition.recordClickFlag = true;
		if (Utils.mobileDeviceFlag)
			Android.startSttArray("eng");
		$("#recordImg").prop('src', Utils.Path + "images/skin/Stop.png");
		$("#recordImg").addClass("blink_me");
		if (Preposition.checkStatus) {
			clearInterval(Preposition.checkStatus);
			Preposition.checkStatus = null;
		}
		Preposition.checkStatus = setInterval(function () {
			if (Utils.mobileDeviceFlag)
				Preposition.sttString = Android.getSttResult();
			console.log(Preposition.sttString);
			if ('$$$' !== Preposition.sttString) {
				clearInterval(Preposition.checkStatus);
				if (Preposition.sttString !== "###" && Preposition.sttString !== "")
					Preposition.checkAnswer();
				else {
					console.log('Stops');
					$('#soundImg').css('pointer-events', 'auto');
				}
				Preposition.recordClickFlag = false;
				$("#recordImg").prop('src', Utils.Path + "images/skin/Record.png");
				$('#recordImg').removeClass('blink_me');
			}
		}, 500);
	}
	else {
		Preposition.recordClickFlag = false;
		$('#soundImg').css('pointer-events', 'auto');
		if (Utils.mobileDeviceFlag)
			Android.stopStt();
		Preposition.sttString = "";
		clearInterval(Preposition.checkStatus);
		$("#recordImg").prop('src', Utils.Path + "images/skin/Record.png");
		$("#recordImg").removeClass("blink_me");
	}
};
//function which checks answer
Preposition.checkAnswer = function () {
	var arr = [], wordTocheck = [], answerArr = [], indexArr = []
	var flag = 0, index = 0;
	$("#recordImg").prop('src', Utils.Path + "images/skin/Record.png");
	arr = Preposition.sttString.split(' ');
	for (var i = 0; i < arr.length; i++)
		arr[i] = arr[i].toLowerCase(); // converting sttStringArr words to lowercase
	Preposition.wordsToBeChecked = Preposition.wordsToBeChecked.replace(/\s\s+/g, ' ');//replace multiple spaces in wordsToBeChecked with single space 
	Preposition.wordsToBeChecked = Preposition.wordsToBeChecked.toLowerCase();// converting wordsToBeChecked words to lowercase
	console.log(arr);
	arr = Preposition.removePunctuation(arr); //remove punctuations from sttStringArr as well as from wordsToBeChecked 
	/*alert(wordTocheck); */
	if (Preposition.wordsToBeChecked[Preposition.wordsToBeChecked.length - 1] == "." || Preposition.wordsToBeChecked[Preposition.wordsToBeChecked.length - 1] == "," || Preposition.wordsToBeChecked[Preposition.wordsToBeChecked.length - 1] == "!")
		Preposition.wordsToBeChecked = Preposition.wordsToBeChecked.slice(0, Preposition.wordsToBeChecked.length - 1);
	//alert(Preposition.wordsToBeChecked);
	wordTocheck = Preposition.wordsToBeChecked.split(' ');
	//alert(wordTocheck[wordTocheck.length-1]);
	//Preposition.wordsToBeChecked=Preposition.removePunctuation(Preposition.wordsToBeChecked);
	for (var i = 0; i < wordTocheck.length; i++) {
		index = arr.indexOf(wordTocheck[i]); //here indexes are pushed of the words which includes in sttStringArr
		if (index >= 0)
			indexArr.push(index);
	}
	for (var i = 0; i < indexArr.length; i++) {	//here sequence of words are checked weather there are in correct sequence according to wordsToBeChecked
		if (indexArr[i] > indexArr[i + 1]) {
			flag = 1;
			break;
		}
	}
	if (flag == 1 || indexArr.length < wordTocheck.length) {
		//alert("wrong"+arr+'\n'+wordTocheck+'\n'+indexArr+"\n"+indexArr.length+"\n"+wordTocheck.length);	
		//alert("wrong"+arr+'\n'+wordTocheck);
		$('#soundImg').css('pointer-events', 'auto');
		Preposition.wrongCnt++;
		Preposition.attemptFlag = true;
		document.getElementById("playSound").pause();
		Preposition.audioTimer = setTimeout(function () {
			document.getElementById("playSound").src = Utils.Path + "sounds/instructions/No__that's_wrong__Aditi.mp3";
			document.getElementById("playSound").play();
		}, 100);

	}
	else {
		//alert("correct"+arr+'\n'+wordTocheck+'\n'+indexArr+"\n"+indexArr.length+"\n"+wordTocheck.length);
		console.log(Preposition.tempArr[Preposition.queCounter].answer + "" + Preposition.data.length + " " + "sentence");
		if (Utils.mobileDeviceFlag)
			Android.addLearntData(Preposition.tempArr[Preposition.queCounter].answer, Preposition.data.length, "sentence");
		//alert("correct"+arr+'\n'+wordTocheck);
		if (Preposition.wrongCnt == 0)
			scoredMarks = 10;
		else
			scoredMarks = 0;
		Preposition.calculateScore();
		$('#recordImg').css('pointer-events', 'none');
		document.getElementById("playSound").pause();
		Preposition.audioTimer = setTimeout(function () {
			document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Weldone.mp3";
			document.getElementById("playSound").play();
		}, 200);
		if (Preposition.nextQueTimer) {
			clearTimeout(Preposition.nextQueTimer);
			Preposition.nextQueTimer = null;
		}
		Preposition.nextQueTimer = setTimeout(function () {
			Preposition.nextQuestion();
		}, 1500);
	}
};
//function which removes punctuation
Preposition.removePunctuation = function (arr) {
	var str = "";
	str = arr[arr.length - 1];
	for (var j = 0; j < Preposition.punctArr.length; j++) {
		if (str.indexOf(Preposition.punctArr[j]) != -1) {
			str = str.replace(Preposition.punctArr[j], "");
			arr.splice(arr.length - 1, 1);
			arr.push(str);
		}
	}
	return arr;
};
//function which calculates score 
Preposition.calculateScore = function () {
	Preposition.attemptFlag = false;
	console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
};
//function which executes on next button click
Preposition.nextQuestion = function () {
	Preposition.queCounter++;
	if (Preposition.checkStatus) {
		clearInterval(Preposition.checkStatus);
		Preposition.checkStatus = null;
	}
	clearTimeout(Preposition.audioTimer);
	Preposition.audioTimer = null;
	clearTimeout(Preposition.playAnswerTimer);
	clearTimeout(Preposition.instructionTimer);

	if (Preposition.attemptFlag) {
		scoredMarks = 0;
		Preposition.attemptFlag = false;
		Preposition.calculateScore();
	}
	if (Preposition.skipFlag) {
		scoredMarks = -1;
		Preposition.calculateScore();
	}
	$("#recordImg").removeClass("blink_me");
	$("#recordImg").prop('src', Utils.Path + "images/skin/Record.png");
	if (Preposition.nextQueTimer) {
		clearTimeout(Preposition.nextQueTimer);
		Preposition.nextQueTimer = null;
	}
	if (Preposition.queCounter < 5) {
		if (Utils.mobileDeviceFlag)
			Android.stopStt();
		Preposition.recordClickFlag = false;
		$('#soundImg').css('pointer-events', 'auto');
		$('#recordImg').css('pointer-events', 'auto');
		$("#answerText").empty();
		Preposition.ansString = "";
		Preposition.answer = "";
		questionId = 0, scoredMarks = 0;
		Preposition.wrongCnt = 0;
		clearInterval(Preposition.checkStatus);
		Preposition.showQuestion();
	}
	else {
		document.getElementById('playSound').src = "";
		document.getElementById('playSound').pause();
		clearTimeout(Preposition.instructionTimer);
		clearTimeout(Preposition.playAnswerTimer);
		clearTimeout(Preposition.audioTimer);
		Preposition.audioTimer = null;
		Preposition.showEndPage();
	}
};
//function which restart game again
Preposition.replay = function () {
	$("#gamePage").show();
	$("#endPage").hide();
	Preposition.queCounter = 0;
	Preposition.skipFlag = true;
	Preposition.attemptFlag = false;
	Preposition.showCreditFlag = false;
	Preposition.recordClickFlag = false;
	$('#soundImg').css('pointer-events', 'auto');
	$('#recordImg').css('pointer-events', 'auto');
	$("#answerText").empty();
	Preposition.ansString = "";
	Preposition.answer = "";
	questionId = 0, scoredMarks = 0;
	Preposition.wrongCnt = 0;
	Preposition.tempArr = [];
	Preposition.tempArr = populate(Preposition.data, Preposition.tempArr, 5);
	Preposition.showQuestion();
};
//function which shows last page of game
Preposition.showEndPage = function () {
	$("#gamePage").hide();
	$("#endPage").show();
};
Preposition.showCredits = function () {
	if (Preposition.showCreditFlag) {
		$("#gameOverText").show();
		$("#acknowledgementDiv").css('visibility', 'hidden');
		Preposition.showCreditFlag = false;
	}
	else if (Preposition.showCreditFlag == false) {
		Preposition.showCreditFlag = true;
		$("#gameOverText").hide();
		$("#acknowledgementDiv").css('visibility', 'visible');
	}
};
//function which executes on home button click
Preposition.goToHome = function () {
	clearTimeout(Preposition.instructionTimer);
	clearTimeout(Preposition.playAnswerTimer);
	document.getElementById('playSound').pause();
	if (Preposition.attemptFlag) {
		scoredMarks = 0;
		Preposition.attemptFlag = false;
		Preposition.calculateScore();
	}
	location.reload(true);
};
//function getting audio duration
Preposition.getAudioDuration = function (sound, callback) {
	var duration = 0;
	$('#playSound').prop('src', sound);
	if (Preposition.loadmetaDataFlag) {
		$('#playSound').on("loadedmetadata", function () {
			duration = $('#playSound').prop('duration');
			Preposition.loadmetaDataFlag = false;
			$('#playSound').unbind("loadedmetadata");
			callback(duration);
		});
	}
	else
		$('#playSound').unbind("loadedmetadata");
};	
