// 04/05/2019

var GuessWord = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var elePosition = null, leftPos = 0, askQueFlag = false, queSoundSrc, scoreFlag = true, label = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0;
GuessWord.init = function () {
	document.title = GuessWord.hardCodedData.gameTitle;
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/" + GuessWord.hardCodedData.cover_page + ")";
	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('Guess a Word');
	}
	setTimeout(function () {
		$("#playImgDiv").show();
		$("#playImgDiv").addClass('magictime slideDownReturn');
		$("#guessWordText").addClass('animated pulse');
		setTimeout(function () {
			$("#guessWordText").removeClass('animated pulse');
		}, 2000);
	}, 3000);
	GuessWord.setStartPage();
	GuessWord.setUnchangedVariables();
	GuessWord.setVariables();
	GuessWord.setImages();
	GuessWord.countJsonNodes();
	GuessWord.createStars();
}

GuessWord.setStartPage = function () {
	var i = 0, animationInterval;
	document.getElementById("aWordImg").src = Utils.Path + "images/a_word.png";
	animationInterval = setInterval(function () {
		i++;
		document.getElementById("w" + i).src = Utils.Path + "images/w" + i + ".png";
		$("#w" + i).addClass('magictime vanishIn');
		$("#w" + i).show();
		if (i >= 5) {
			setTimeout(function () {
				$("#aWordText").show();
			}, 700);
			$("#aWordImg").addClass('magictime foolishIn');
			clearInterval(animationInterval);
		}
	}, 200);
}


GuessWord.setUnchangedVariables = function () {
	GuessWord.jsonObjectLength = 0;
	GuessWord.previousQuestions = [];// array which stores previous questions
	GuessWord.totalQuestionCount = 5;//total question 
	GuessWord.attemptedQuestionCount = 0;
	GuessWord.correctAns = 0;
	GuessWord.correctSound = ["Very_Good!_The_word_is__Aditi.mp3", "Correct!_The_word_is__Aditi.mp3"];
	GuessWord.wrongSound = ["Sorry__the_word_is__Aditi.mp3", "Oh_no!_the_word_is_Aditi.mp3"];
	GuessWord.questionsArrayIndex = [];//  array which stores GuessWord.previousQuestions array index
	GuessWord.alphabetIndexArray = [];
	GuessWord.questionIndexArray = [];
	GuessWord.queIndexCount = 0;
}
//set variable
GuessWord.setVariables = function () {
	GuessWord.questionIndex;// preserve current question index
	GuessWord.strWithoutVowels;// question string without vowels
	GuessWord.strWithVowels;//question string with vowels
	GuessWord.optionsIndex = [];// array which contains current option
	GuessWord.answerDivIndex;// preserve last digit of answer div
	GuessWord.loadmetaDataFlag = false;
	GuessWord.stopInterval;
	GuessWord.playSoundTimeOut;
	GuessWord.answerSoundFlag = false;
	GuessWord.noResponseTimer = null;
	GuessWord.seconds = 0;
}

//set images
GuessWord.setImages = function () {
	document.getElementById("playImage").src = Utils.Path + "images/play.png";
	document.getElementById("logo").src = Utils.Path + "images/logo.png";
	document.getElementById("roboImg").src = Utils.Path + "images/roboStand.png";
	document.getElementById("skipBtnImg").src = Utils.Path + "images/Skip.png";
	document.getElementById("nextImage").src = Utils.Path + "images/next.png";

}
// count total values in json
GuessWord.countJsonNodes = function () {
	var i = 0;
	for (i = 0; i < GuessWord.wordData.length; i++) {
		GuessWord.jsonObjectLength += GuessWord.wordData[i].data.length;
	}
}


//play game
GuessWord.playgame = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/" + GuessWord.hardCodedData.backGround + ")";
	document.getElementById("optionsMainDiv").style.backgroundImage = "url(" + Utils.Path + "images/Frame.png" + "" + ")";
	document.getElementById("questionTextMainDiv").style.backgroundImage = "url(" + Utils.Path + "images/Main_box_bg.png" + "" + ")";
	document.getElementById("questionDiv").style.backgroundImage = "url(" + Utils.Path + "images/queBg.png" + "" + ")";
	document.getElementById("acknowledgementMainDiv").style.backgroundImage = "url(" + Utils.Path + "images/Frame2.png" + "" + ")";
	$("#playImgDiv").removeClass('magictime slideDownReturn');
	$("#skipBtnDiv").addClass('magictime slideRightReturn');
	$("#gamePage").show();
	$("#startPage").hide();
	GuessWord.createOptionsDiv();
}

// create divs for set option strings
GuessWord.createOptionsDiv = function () {
	var i = 0, innrDiv, span;
	for (i = 1; i <= 4; i++) {
		innrDiv = document.createElement('div');
		innrDiv.setAttribute("id", "option" + i);
		innrDiv.setAttribute("class", "bgProp  col-xs-12 col-sm-12 col-md-12 col-lg-12 optionClass noPadding");
		innrDiv.setAttribute("onclick", "GuessWord.checkAnswer(this.id)");
		span = document.createElement('span');
		span.setAttribute("id", "optionText" + i);
		span.setAttribute("class", "optionSpanClass");
		optionsMainDiv.appendChild(innrDiv);
		innrDiv.appendChild(span);
		$("#option" + i).css("background-image", "url(" + Utils.Path + "images/Main.png" + ")");
	}
	GuessWord.getAllQuestions();
	GuessWord.setQuestion();
}


GuessWord.getAllQuestions = function () {
	var alphaIndex = 0, queIndex = 0;
	while (GuessWord.alphabetIndexArray) {
		alphaIndex = Math.floor(Math.random() * GuessWord.wordData.length);
		queIndex = Math.floor(Math.random() * GuessWord.wordData[alphaIndex].data.length);
		if (GuessWord.alphabetIndexArray.includes(alphaIndex) && GuessWord.questionIndexArray.includes(queIndex)) {
			continue;
		}
		else {
			GuessWord.alphabetIndexArray.push(alphaIndex);
			GuessWord.questionIndexArray.push(queIndex);
		}
		if (GuessWord.alphabetIndexArray.length >= GuessWord.totalQuestionCount)
			break;
	}

}

// set question function 
GuessWord.setQuestion = function () {
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	GuessWord.alphabetIndex = GuessWord.alphabetIndexArray[GuessWord.queIndexCount];
	GuessWord.questionIndex = GuessWord.questionIndexArray[GuessWord.queIndexCount];
	GuessWord.optionsIndex.push(GuessWord.questionIndex);
	GuessWord.strWithVowels = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].word;
	questionId = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].questionId;
	GuessWord.attemptedQuestionCount++;
	GuessWord.previousQuestions.push(GuessWord.strWithVowels);
	document.getElementById("questionTextDiv").innerHTML = GuessWord.strWithoutVowels = GuessWord.strWithVowels.replace(/[aeiou_]/gi, '').replace("-", '');
	$("#questionDiv").addClass('magictime spaceInLeft');
	$("#questionDiv").show();
	GuessWord.createOption();
}

// create option for current quetion
GuessWord.createOption = function () {
	var i = 0, alphaIndex, tempStrWithoutVowels;
	while (GuessWord.optionsIndex.length < 4) {
		alphaIndex = Math.floor(Math.random() * GuessWord.wordData[GuessWord.alphabetIndex].data.length);
		if (GuessWord.optionsIndex.includes(alphaIndex)) {
			continue;
		}
		else {
			tempStrWithoutVowels = GuessWord.wordData[GuessWord.alphabetIndex].data[alphaIndex].word.replace(/[aeiou_]/gi, '').replace("-", '');
			if (GuessWord.questionIndex != alphaIndex && GuessWord.strWithoutVowels != tempStrWithoutVowels) {
				// check, is option word contain any one letter from GuessWord.strWithVowels(quetion string with Vowels)
				GuessWord.checkWordForSetOption(GuessWord.wordData[GuessWord.alphabetIndex].data[alphaIndex].word, alphaIndex);
			}
		}

	}
	GuessWord.setOption();
}

// check, is option word contain any one letter from GuessWord.strWithVowels(quetion string with Vowels)
GuessWord.checkWordForSetOption = function (optionWord, alphaIndex) {
	var i, j, letterCount = 0;
	for (i = 1; i < GuessWord.strWithVowels.length; i++) {
		if (optionWord.indexOf(GuessWord.strWithVowels[i]) != -1) {
			letterCount++;
			if (letterCount >= 2) {
				GuessWord.optionsIndex.push(alphaIndex);
				break;
			}
		}
	}
}

//set all option randomly 
GuessWord.setOption = function () {
	var i = 0, tempArray = [], tempIdCount, animationCount = 1, animationInterval;
	for (i = 0; i < GuessWord.optionsIndex.length; i++) {
		tempIdCount = Math.floor(Math.random() * 4) + 1;
		if (tempArray.includes(tempIdCount)) {
			i--;
			continue;
		}
		else {
			tempArray.push(tempIdCount);
			GuessWord.answerDivIndex = tempArray[0];
			document.getElementById("optionText" + tempIdCount).innerHTML = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.optionsIndex[i]].langWord;
			document.getElementById("option" + tempIdCount).setAttribute("engText", GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.optionsIndex[i]].word)
		}
	}

	animationInterval = setInterval(function () {
		if (animationCount == 2) {
			GuessWord.playSound("instruction/Buzzercorrect.mp3");
		}
		$("#option" + animationCount).addClass('magictime spaceInUp');
		$("#option" + animationCount).show();
		animationCount++;
		if (animationCount > 4) {
			$(".optionClass").css({ "pointer-events": "auto" });
			$("#skipBtnDiv").show();
			clearInterval(animationInterval);
			clearTimeout(GuessWord.timeOut);
			clearInterval(GuessWord.noResponseTimer);
			GuessWord.seconds = 0;
			GuessWord.startTimer();
		}
	}, 200);
}
//if user interaction stoped play sound "please answer the question" after some time 
GuessWord.startTimer = function () {
	if (GuessWord.noResponseTimer) {
		clearInterval(GuessWord.noResponseTimer);
		GuessWord.noResponseTimer = null;
		GuessWord.seconds = 0;
	}
	GuessWord.noResponseTimer = setInterval(function () {
		GuessWord.seconds++;
		if (GuessWord.seconds >= 6) {
			GuessWord.seconds = 0;
			GuessWord.playSound("instruction/please_ans_the_ques.mp3");
			clearInterval(GuessWord.noResponseTimer)
			GuessWord.timeOut = setTimeout(function () {
				GuessWord.seconds = 0;
				GuessWord.startTimer();
			}, 2000);
		}
	}, 1000);
}
//check answer function
GuessWord.checkAnswer = function (clickedID) {
	var dataText;
	GuessWord.seconds = 0;// for not to play please answer the question sound
	clearTimeout(GuessWord.timeOut);
	clearInterval(GuessWord.noResponseTimer);
	GuessWord.attemptCount++;
	dataText = document.getElementById(clickedID).getAttribute("engText");
	$(".optionClass").removeClass('magictime spaceInUp');
	GuessWord.alphabetIndexArray.splice(GuessWord.queIndexCount, 1);
	GuessWord.questionIndexArray.splice(GuessWord.queIndexCount, 1);
	questionId = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].questionId;

	if (dataText == GuessWord.strWithVowels)// correct answer
	{
		$("#skipBtnDiv").hide();
		$("#" + clickedID).addClass('animated flash');
		document.getElementById("roboImg").src = Utils.Path + "images/robo-happy.gif";
		GuessWord.loadmetaDataFlag = true;
		// play correct msg sound 
		GuessWord.soundDuration("sounds/instruction/" + GuessWord.correctSound[Math.floor(Math.random() * GuessWord.correctSound.length)]);
		$("#questionDiv").removeClass('magictime spaceInLeft');
		$(".optionClass").css({ "pointer-events": "none" });
		$(".optionClass").not("#" + clickedID).css({ "visibility": "hidden" });
		$("#" + clickedID).css({ "pointer-events": "none" });
		scoredMarks = 10;
		GuessWord.correctAns++;
		if (Utils.mobileDeviceFlag)
			Android.addLearntData(GuessWord.strWithVowels, GuessWord.jsonObjectLength, "word");
		console.log(GuessWord.strWithVowels, GuessWord.jsonObjectLength, "word");
		GuessWord.scoreFun();

	}
	else // if wrong answer click in both chance
	{
		$("#questionDiv").removeClass('magictime spaceInLeft');
		$("#skipBtnDiv").hide();
		$("#option" + GuessWord.answerDivIndex).addClass('animated flash');
		$("#" + clickedID).addClass('animated shake');
		$("#" + clickedID).addClass("opacityClass");
		$(".optionClass").css({ "pointer-events": "none" });
		document.getElementById("roboImg").src = Utils.Path + "images/robo-sad.gif";
		GuessWord.loadmetaDataFlag = true;
		//play wrong msg sound  
		GuessWord.soundDuration("sounds/instruction/" + GuessWord.wrongSound[Math.floor(Math.random() * GuessWord.wrongSound.length)]);
		scoredMarks = 0;
		GuessWord.scoreFun();
	}
}

// this function takes the sound's path and return sound duration
GuessWord.soundDuration = function (sound) {
	var duration = 0;
	$('#playSound').prop('src', sound);
	if (GuessWord.loadmetaDataFlag) {
		$('#playSound').on("loadedmetadata", function () {
			duration = $('#playSound').prop('duration');
			GuessWord.loadmetaDataFlag = false;
			$('#playSound').unbind("loadedmetadata");
			GuessWord.WordSound(duration);
		});
	}
	else
		$('#playSound').unbind("loadedmetadata");
}

//play correct-wrong sound and call "GuessWord.soundDuration" function for word sound
GuessWord.WordSound = function (duration) {
	document.getElementById("playSound").play();
	GuessWord.showAnswerAndHighligth(GuessWord.strWithVowels);
	$("#option" + GuessWord.answerDivIndex).addClass('animated flash');
	$("#option" + GuessWord.answerDivIndex).addClass('vowelsClass');
	if (GuessWord.answerSoundFlag == false) {
		if (GuessWord.playSoundTimeOut) {
			clearTimeout(GuessWord.playSoundTimeOut);
			GuessWord.playSoundTimeOut = null;
		}
		GuessWord.playSoundTimeOut = setTimeout(function () {
			GuessWord.answerSoundFlag = true;
			GuessWord.loadmetaDataFlag = true;
			// duration function for word sound
			GuessWord.soundDuration("sounds/" + GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].sound);
		}, duration * 1000);
	}
	else //call function for next question 
	{
		if (GuessWord.playSoundTimeOut) {
			clearTimeout(GuessWord.playSoundTimeOut);
			GuessWord.playSoundTimeOut = null;
		}
		GuessWord.playSoundTimeOut = setTimeout(function () {
			GuessWord.nextQuestion();// load next question
		}, duration * 1500);
	}
}

//Add_score function 
GuessWord.scoreFun = function () {
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
	else
		console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
}

// show next question
GuessWord.nextQuestion = function () {
	$("#skipBtnDiv").hide();
	document.getElementById("roboImg").src = Utils.Path + "images/roboStand.png";
	if (GuessWord.attemptedQuestionCount >= GuessWord.totalQuestionCount) {
		setTimeout(function ()// game over and show play skip or last page
		{
			// $("#gamePage").hide();
			$(".optionClass").removeClass("opacityClass");
			$(".optionClass").hide();
			$("#questionDiv").hide();
			if (GuessWord.queIndexCount != 0) {
				document.getElementById("textInstuction").innerHTML = GuessWord.modalData.responseMsg;
				document.getElementById("btn1").innerHTML = GuessWord.modalData.yes;
				document.getElementById("btn2").innerHTML = GuessWord.modalData.no;
				$("#askForSkipedQuestionDiv").show();
			}
			else {
				$("#gamePage").hide();
				GuessWord.giveStars();
				if (Utils.mobileDeviceFlag) {
					Android.StudentCertification(GuessWord.correctAns, GuessWord.totalQuestionCount, "5")
				}
			}
		}, 500);
	}
	else {
		setTimeout(function ()// for next question
		{
			$(".optionClass").removeClass('animated shake');
			$(".optionClass").removeClass('animated flash');
			$(".optionClass").removeClass('vowelsClass');
			$(".optionClass").removeClass("opacityClass");
			$(".optionClass").css({ "visibility": "visible" });
			$(".optionClass").hide();
			$("#questionDiv").hide();
			GuessWord.setVariables();
			GuessWord.setQuestion();
		}, 10);
	}
}

// show question string with vowels and highlight the vowels and answer string
GuessWord.showAnswerAndHighligth = function (answerWord) {
	var span, vowelsString = "aeiouAEIOU";
	$("#questionTextDiv").html("");
	for (i = 0; i < answerWord.length; i++) {
		span = document.createElement('span');
		span.setAttribute("id", "span" + i);
		span.innerHTML = answerWord[i];
		if (vowelsString.includes(answerWord[i])) {
			span.setAttribute("class", "vowelsClass2");
		}
		questionTextDiv.appendChild(span);
	}
}

// if next button click
GuessWord.skipQuestion = function () {
	clearTimeout(GuessWord.timeOut);
	clearInterval(GuessWord.noResponseTimer);
	GuessWord.seconds = 0;
	GuessWord.queIndexCount++;
	document.getElementById("playSound").pause();
	$(".optionClass").css({ "pointer-events": "none" });
	$("#skipBtnDiv").hide();
	$("#questionDiv").removeClass('magictime spaceInLeft');
	GuessWord.attemptCount = 0;
	GuessWord.nextQuestion();
}

//play sound , pass source as a parameter
GuessWord.playSound = function (src) {
	document.getElementById("playSound").src = "sounds/" + src;
	document.getElementById("playSound").play();
}


GuessWord.playSkipYes = function () {
	console.log("YES SKIP");
	GuessWord.attemptedQuestionCount -= GuessWord.alphabetIndexArray.length;
	GuessWord.queIndexCount = 0;
	$("#askForSkipedQuestionDiv").hide();
	$("#gamePage").show();
	$(".optionClass").removeClass('animated shake');
	$(".optionClass").removeClass('animated flash');
	$(".optionClass").removeClass('vowelsClass');
	$(".optionClass").removeClass("opacityClass");
	$(".optionClass").css({ "visibility": "visible" });
	$(".optionClass").hide();
	$("#questionDiv").hide();
	GuessWord.setVariables();
	GuessWord.setQuestion();
}


GuessWord.createStars = function () {
	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/star2.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
	$("#starDiv").css("visibility", "hidden");
};

GuessWord.giveStars = function () {
	var fractionVar, i, numberOfStars = GuessWord.correctAns;
	clearTimeout(GuessWord.timeOut);
	clearInterval(GuessWord.noResponseTimer);
	$("#askForSkipedQuestionDiv").hide();
	$("#nextBtn").show();
	$("#nextBtn").addClass('magictime slideRightReturn');
	setTimeout(function () {
		$("#nextBtn").removeClass('magictime slideRightReturn');
		$("#nextBtn").addClass('blink_me');
	}, 1000);
	$("#acknowledgementMainDiv").show();
	$("#gamePage").hide();
	document.getElementById("gameOverMsg").innerHTML = GuessWord.hardCodedData.gameOverMSg;
	if (GuessWord.correctAns != 0) {
		document.getElementById("playSound").src = Utils.Path + "sounds/instruction/Star" + GuessWord.correctAns + ".mp3";
		document.getElementById("playSound").play();
	}
	fractionVar = numberOfStars - Math.floor(numberOfStars);
	if (fractionVar != 0)
		numberOfStars++;
	for (i = 1; i <= Math.floor(numberOfStars); i++)
		document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/star1.png");
	if (fractionVar != 0)
		document.getElementById("starImg" + (i - 1)).setAttribute("src", Utils.Path + "images/Star-Half.png");
	$("#starDiv").css("visibility", "visible");
};

GuessWord.nextClick = function () {
	clearTimeout(GuessWord.timeOut);
	clearInterval(GuessWord.noResponseTimer);
	document.getElementById("playSound").pause();
	if (Utils.mobileDeviceFlag) {
		Android.GotoNextGame();
	}

}