//starting date:19th october 2018.
var FlipIt = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 100, resId = 0, level = 0, label, totalLength, wordType = "sentence";

$(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("FlipIt"); 
	// FlipIt.JsonLength();
	setTimeout(function () {
		FlipIt.init();
	}, 100);
});
FlipIt.JsonLength = function () {
	var i, j, counter = 0;
	for (i = 0; i < FlipIt.data.length; i++) {
		for (j = 0; j < FlipIt.data[i].sentence.length; j++)
			counter++;
	}
	totalLength = counter;
	console.log(totalLength);
}
//shows coverPage
FlipIt.init = function () {
	$("#coverPage").show();
	$("#levelPage").hide();
	$("#gamePage").hide();
	$("#lastPage").hide();
	$(".header").not("#logo").css("visibility", "hidden");
	$("#gameOver").css("visibility", "hidden");
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/coverImage.png";
	FlipIt.setAllImages();
	FlipIt.createOptionDivs();
	FlipIt.initializeVariables();

}
//initialization
FlipIt.initializeVariables = function () {
	FlipIt.levelIndex = 0;
	FlipIt.question;
	FlipIt.attemptCounter = 0;
	FlipIt.wordLevel = 0;
	FlipIt.noOfQuestions = 0;
	FlipIt.attemptFlag = false;
	FlipIt.newQuestionLoad = true;
	FlipIt.uniqueArray = [];
	FlipIt.loadmetaDataFlag = false;
	FlipIt.pointerEventFlag = true;
	FlipIt.wrongFlag = false;
}
//setting sources to all images
FlipIt.setAllImages = function () {
	document.getElementById("homeImage").src = Utils.Path + "images/skin/home.png";
	document.getElementById("logoImage").src = Utils.Path + "images/skin/logo.png";
	document.getElementById("play").src = Utils.Path + "images/skin/Play.png";
	document.getElementById("go").src = Utils.Path + "images/skin/Play.png";
	document.getElementById("next").src = Utils.Path + "images/skin/Next.png";
	document.getElementById("sound").src = Utils.Path + "images/skin/Sound.png";
	document.getElementById("levelImg1").src = Utils.Path + "images/skin/Level_01.png";
	document.getElementById("levelImg2").src = Utils.Path + "images/skin/Level_02.png";
	document.getElementById("replayImg").src = Utils.Path + "images/skin/PlayAgain.png";
	document.getElementById("creditImg").src = Utils.Path + "images/skin/credit.png";
	document.getElementById("lastPara").innerHTML = FlipIt.hardCodedData.gameOver;
	document.getElementById("InstrTitle").innerHTML=FlipIt.hardCodedData.howToPlay;
	document.getElementById("instr").innerHTML=FlipIt.hardCodedData.instruction;
}
//creates divs for options
FlipIt.createOptionDivs = function () {
	var i = 0, parentDiv, option, para;
	parentDiv = document.getElementById("optionDiv");
	for (i = 0; i <= 4; i++) {
		option = document.createElement("DIV");
		option.setAttribute("id", "optionDiv" + i);
		if (i == 0)
			option.setAttribute("class", "optionDivs nopadding col-xs-8 col-md-8 col-lg-8 col-sm-8");
		else {
			option.setAttribute("class", "optionDivs marginCls nopadding col-xs-8 col-md-8 col-lg-8 col-sm-8");
			option.setAttribute("onclick", "FlipIt.checkAnswer(this.id);");
		}
		if (i == 0) {
			option.style.backgroundImage = "url(" + Utils.Path + "images/skin/name_plate.png";
			option.style.margin = "-12vh 0 0 11vw";
		}
		else if (i % 2 == 1) {
			option.style.backgroundImage = "url(" + Utils.Path + "images/skin/arrow_1.png";
			if (i == 1)
				option.style.marginTop = "10vh";
		}
		else {
			option.style.backgroundImage = "url(" + Utils.Path + "images/skin/arrow_2.png";
			option.style.marginLeft = "20vw";
		}
		parentDiv.appendChild(option);

		para = document.createElement("P");
		if (i == 0)
			para.setAttribute("onclick", "FlipIt.playSound();");
		para.setAttribute("id", "option" + i);
		para.setAttribute("class", "options");
		option.appendChild(para);

	}
}

FlipIt.showInstr=function(){
	$("#coverPage").hide();
	$("#instrPage").show();
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/BBg.png";
}
//displays levelPage
FlipIt.showLevel = function () {
	$("#coverPage").hide();
	$("#gamePage").hide();
	$("#levelPage").show();
	$("#lastPage").hide();
	$(".header").css("visibility", "visible");
	$("#gameOver").css("visibility", "hidden");
	//$("#logo").addClass("header nopadding col-xs-1 col-md-1 col-lg-1 col-sm-1 col-xs-offset-10 col-md-offset-10 col-lg-offset-10 col-sm-offset-10");
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/levelBg.png";
	document.getElementById("level1").setAttribute("level", 1);
	document.getElementById("level2").setAttribute("level", 2);
}

//runs @ onclick of level button,selects level
FlipIt.selectLevel = function (levelId) {
	level = parseInt(document.getElementById(levelId).getAttribute("level"));
	FlipIt.levelIndex = level;
	FlipIt.playGame();
}

//shows gamePage
FlipIt.playGame = function () {
	$("#instrPage").hide();
	$("#coverPage").hide();
	$("#gamePage").hide();
	$("#levelPage").show();
	$("#lastPage").hide();
	$(".header").css("visibility", "visible");
	$("#gameOver").css("visibility", "hidden");
	
	rNo = 0;
	FlipIt.newQuestionLoad = true;
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png";
	$(".options").css("font-size", "3.5vw");
	$("#levelPage").hide();
	$("#gamePage").show();
	$("#lastPage").hide();
	$(".header").css("visibility", "visible");
	FlipIt.selectQuestion();
	FlipIt.setQuestion();
}

//runs @onclick replay button @endPage,reloads the game again
FlipIt.playAgain = function () {
	FlipIt.uniqueArray = [];
	console.log(FlipIt.uniqueArray);
	$("#gameOver").css("visibility", "hidden");
	//$("#logo").addClass("header nopadding col-xs-1 col-md-1 col-lg-1 col-sm-1 col-xs-offset-10 col-md-offset-10 col-lg-offset-10 col-sm-offset-10");
	FlipIt.attemptCounter = 0;
	FlipIt.wordLevel = 0;
	FlipIt.noOfQuestions = 0;

	FlipIt.playGame();
}
FlipIt.selectQuestion=function(){
	rNo = Math.floor(Math.random() * FlipIt.data.length);
	FlipIt.sentenceArr=FlipIt.data[rNo].questions;
	questionId = parseInt(FlipIt.data[rNo].level);
}

//selects the one option as question,plays the sound of translation of question
FlipIt.setQuestion = function () {

	scoredMarks = 0;
	var d, i = 0, rNo = 0, question, option, flag = 0, optionArr = [], randOption = 0, allOption = [];
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	FlipIt.firstAttemptFlag = true;
	FlipIt.wrongFlag = false;
	FlipIt.noOfQuestions++;
	if (FlipIt.wordLevel >= 1)
		$(".options").css("font-size", "2vw");
	$(".options").css("margin-top", "3vh");
	// if (FlipIt.wordLevel > 2) {
	// 	$(".options").css("font-size", "2.3vw");
	// 	$(".options").css("margin-top", "2.5vh");
	// }
	// if (FlipIt.wordLevel > 4) {
	// 	$(".options").css("font-size", "2vw");
	// 	$(".options").css("margin-top", "3vh");
	// }
	if (FlipIt.noOfQuestions > FlipIt.sentenceArr.length)
		FlipIt.endGame();
	else {
	// if (FlipIt.levelIndex == 2) {
		FlipIt.question = FlipIt.sentenceArr[FlipIt.wordLevel].sentence;
		// while (FlipIt.uniqueArray.includes(FlipIt.question)) {
		// 	rNo = Math.floor(Math.random() * FlipIt.data[FlipIt.wordLevel].sentence.length);
		// 	FlipIt.question = FlipIt.data[FlipIt.wordLevel].sentence[rNo];
		// }
		// FlipIt.uniqueArray.push(FlipIt.question);
		 document.getElementById("option0").innerHTML = FlipIt.sentenceArr[FlipIt.wordLevel].sentence;

		// allOption.push(FlipIt.data[FlipIt.wordLevel].sentence[rNo].english)
		// for (i = 0; i < 3; i++) {
		// 	allOption.push(FlipIt.data[FlipIt.wordLevel].sentence[rNo].option[i]);
		// }
		allOption=FlipIt.sentenceArr[FlipIt.wordLevel].options;
		shuffleArray(allOption);
		for (i = 0; i < 4; i++) {
			document.getElementById("option" + (i + 1)).innerHTML = allOption[i];
		}
	// }
		// else {
		// 	for (i = 0; i < 4; i++) {
		// 		while (optionArr.includes(rNo))
		// 			rNo = Math.floor(Math.random() * FlipIt.data[FlipIt.wordLevel].sentence.length);
		// 		optionArr.push(rNo)
		// 		// if(FlipIt.levelIndex==2)
		// 		// 	option=FlipIt.data[FlipIt.wordLevel].sentence[rNo].english;
		// 		// else
		// 		option = FlipIt.data[FlipIt.wordLevel].sentence[rNo].hindi;
		// 		document.getElementById("option" + (i + 1)).innerHTML = option;
		// 	}
		// 	document.getElementById("option0").innerHTML = FlipIt.data[FlipIt.wordLevel].sentence[rNo].english;
		// 	randOption = Math.floor(Math.random() * optionArr.length);
		// 	FlipIt.question = FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]];
		// 	while (FlipIt.uniqueArray.includes(FlipIt.question)) {
		// 		randOption = Math.floor(Math.random() * optionArr.length);
		// 		FlipIt.question = FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]];
		// 	}
		// 	FlipIt.uniqueArray.push(FlipIt.question);
		// 	document.getElementById("option0").innerHTML = FlipIt.question.english;
		// }
		// if (FlipIt.levelIndex == 2) {
			label = (FlipIt.sentenceArr[FlipIt.wordLevel].sentence);
		// }
		// else {
		// 	label = (FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]].english);
		// 	questionId = parseInt(FlipIt.data[FlipIt.wordLevel].sentence[optionArr[randOption]].questionId);
		// }
		 FlipIt.playSound();
	}
}

//calls when 5 question completesshows endPage
FlipIt.endGame = function () {
	document.getElementById("acknowledgementDiv").style.display = "none";
	$("#gamePage").hide();
	$("#lastPage").show();
	$("#gameOver").css("visibility", "visible");
	//$("#logo").addClass("header nopadding col-xs-1 col-md-1 col-lg-1 col-sm-1 col-xs-offset-2 col-md-offset-2 col-lg-offset-2 col-sm-offset-2");
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/BBg.png";
	document.getElementById("playSound").pause();
}

//runs @onclick of options checks whether the translation and option clicked are matched
FlipIt.checkAnswer = function (divId) {
	FlipIt.attemptFlag = true;
	FlipIt.attemptCounter++;
	document.getElementById("playSound").pause();
	document.getElementById(divId).style.pointerEvents = "none";
	// if (FlipIt.levelIndex == 2) {
		if (document.getElementById(divId).children[0].innerHTML == FlipIt.sentenceArr[FlipIt.wordLevel].answer) {
			FlipIt.wrongFlag = false;
			if (Utils.mobileDeviceFlag)
				Android.addLearntData(FlipIt.question.english, totalLength, wordType);
			FlipIt.sendScore(divId);
		}
		else {
			FlipIt.wrongFlag = true;
			document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Try_again.mp3";
			document.getElementById(divId).children[0].style.opacity = 0.5;
			$("#" + divId).children().addClass("animated shake");

		}
	// }
	// else
	// 	if (document.getElementById(divId).children[0].innerHTML == FlipIt.question.hindi)
	// 		FlipIt.sendScore(divId);
	// 	else {
	// 		FlipIt.wrongFlag = true;
	// 		document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Try_again.mp3";
	// 		document.getElementById(divId).children[0].style.opacity = 0.5;
	// 		$("#" + divId).children().addClass("animated shake");
	// 	}
	 document.getElementById("playSound").play();
}

//runs when answer is correct.
FlipIt.sendScore = function (divId) {
	$("#" + divId).children().addClass("animated flash");
	scoredMarks = (5 - FlipIt.attemptCounter) * 25;
	// FlipIt.wordLevel++;
	document.getElementById("playSound").src = Utils.Path + "sounds/instructions/CorrectAksharkhadi.mp3";
	document.getElementById(divId).children[0].style.color = "#2de430";
	$(".optionDivs").css("pointer-events", "none");
	$("#soundDiv").css("pointer-events", "none");
	$("#option0").css("pointer-events", "none");
	console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	FlipIt.nextQuestionTimeout = setTimeout(function () {
		FlipIt.showNextQuestion();
	}, 2000);

}
//plays the translation of question
FlipIt.playSound = function () {
	var source;
	// if (FlipIt.levelIndex == 2)
	document.getElementById("playSound").src = Utils.Path + "sounds/" + FlipIt.sentenceArr[FlipIt.wordLevel].sound;
	// else
	// 	document.getElementById("playSound").src = Utils.Path + "sounds/" + FlipIt.question.englishSound;
	source = document.getElementById("playSound").src;
	document.getElementById("playSound").play();
	if (FlipIt.pointerEventFlag == true)
		$(".optionDivs").css("pointer-events", "none");
	$("#soundDiv").css("pointer-events", "auto");
	$("#option0").css("pointer-events", "auto");

	FlipIt.loadmetaDataFlag = true;
	FlipIt.getDuration(source);
}
function saySomething(whatToSay) {
	var synth, speech;
	synth = window.speechSynthesis;
	if ('speechSynthesis' in window) {
		speech = new SpeechSynthesisUtterance(whatToSay);
		speech.lang = 'hi-IN'; //en-US
		window.speechSynthesis.speak(speech);
	}
}
//runs @onclick of next button and when answer given is correct
FlipIt.showNextQuestion = function () {
	FlipIt.pointerEventFlag = true;
	if (FlipIt.attemptFlag == false) {
		FlipIt.wordLevel++;
		scoredMarks = -1;
		console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
		if (Utils.mobileDeviceFlag)
			Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	}
	else {
		FlipIt.attemptFlag = false;
		FlipIt.wordLevel++;
		if (scoredMarks == 0) {
			console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
			if (Utils.mobileDeviceFlag)
				Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
		}
	}
	clearTimeout(FlipIt.nextQuestionTimeout);
	FlipIt.attemptCounter = 0;
	$(".options").css("color", "white");
	$(".optionDivs").css("pointer-events", "auto");
	$("#soundDiv").css("pointer-events", "auto");
	$("#option0").css("pointer-events", "auto");
	document.getElementById("playSound").pause();
	$(".options").removeClass("anmated shake");
	$(".options").removeClass("animated flash");
	$(".options").css("opacity", 1);
	FlipIt.setQuestion();
}
//runs @ onclick of home button shows the levelPage from game and homePage from levelPage
FlipIt.callhome = function () {

	// FlipIt.pointerEventFlag = true;
	// if (document.getElementById("levelPage").style.display == "block")
		location.reload();
	// else {

	// 	document.getElementById("playSound").pause();
	// 	clearTimeout(FlipIt.nextQuestionTimeout);

	// 	if (FlipIt.wrongFlag == true) {
	// 		console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	// 		if (Utils.mobileDeviceFlag)
	// 			Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	// 	}
	// 	FlipIt.showLevel();
	// 	$(".options").removeClass("anmated shake");
	// 	$(".options").removeClass("animated flash");
	// 	$(".options").css("color", "white");
	// 	$(".options").css("opacity", 1);
	// }

}

function saySomething(whatToSay) {
	if ('speechSynthesis' in window) {
		speech = new SpeechSynthesisUtterance(whatToSay);
		speech.lang = 'hi-IN'; //en-USdocument.getElementById("playSound").pause();
		//speech.rate=0.7;
		window.speechSynthesis.speak(speech);
	} document.getElementById("playSound").pause();
	//speech.onend = function() { $("#soundDiv").css("pointer-events","auto"); };
}


//shows acknowledgement.
FlipIt.showAcknowlwdgement = function () {
	var i = 0, div;
	$("#acknowledgementDiv").empty();
	console.log(Object.keys(FlipIt.AcknowledgementPageData).length)
	for (i = 0; i < Object.keys(FlipIt.AcknowledgementPageData).length; i++) {
		div = document.createElement('div');
		div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML = Object.keys(FlipIt.AcknowledgementPageData)[i] + " : " + Object.values(FlipIt.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div = document.createElement('div');
	div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML = FlipIt.hardCodedData['createdOn'];
	div.style.marginBottom = "2vh";
	acknowledgementDiv.appendChild(div);
	document.getElementById("acknowledgementDiv").style.display = "block";
}

function shuffleArray(array) {
	var i, j, temp;
	for (i = array.length - 1; i > 0; i--) {
		j = Math.floor(Math.random() * (i + 1));
		temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	return array;
}

FlipIt.getDuration = function (sound) {
	var duration = 0;
	$('#playSound').prop('src', sound);
	document.getElementById("playSound").play();
	if (FlipIt.loadmetaDataFlag) {
		$('#playSound').on("loadedmetadata", function () {
			FlipIt.loadmetaDataFlag = false;
			$('#playSound').unbind("loadedmetadata");
			duration = $('#playSound').prop('duration');

			if (duration == 0) {
				duration = 1;
				console.log(duration);
			}
			if (FlipIt.pointerEventFlag == true) {
				FlipIt.pointerEventFlag = false;
				FlipIt.enableClick(duration);
			}
		}
		);
	}
	else
		$('#playSound').unbind("loadedmetadata");
}
FlipIt.enableClick = function (duration) {
	setTimeout(function () {
		$(".optionDivs").css("pointer-events", "auto");
	}, duration * 900);
}