//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;
var correctCnt = 0, attemptCnt = 0;

$(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"); 
	setTimeout(function () {
		FlipIt.init();
	}, 100);
});
// initial function,shows the coverPage.
FlipIt.init = function () {
	document.title = FlipIt.hardCodedData.gameTitle;
	$("#coverPage").show();
	$("#levelPage").hide();
	$("#gamePage").hide();
	$("#lastPage").hide();
	$(".header").not("#logo").css("visibility", "hidden");
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/coverImage.png";
	FlipIt.initializeVariables();
	FlipIt.setAllImages();
	FlipIt.createOptionDivs();
	FlipIt.createStars();
}

//sets 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("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("nextButton").src = Utils.Path + "images/skin/Next.png";
	document.getElementById("next").src = Utils.Path + "images/skin/Skip.png";
	document.getElementById("gameOver").innerHTML = FlipIt.hardCodedData.gameOver;
}
//creates optionDivs
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");
			option.setAttribute("onclick", "FlipIt.playSoundOnsoundClick();");
		}
		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.playSoundOnsoundClick();");
		para.setAttribute("id", "option" + i);
		para.setAttribute("class", "options");
		option.appendChild(para);

	}
}
FlipIt.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/skin/star1.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
	$("#starDiv").css("visibility", "hidden");
};
//shows the levelPage
// FlipIt.showLevel=function()
// {
// 	$("#coverPage").hide();
// 	$("#gamePage").hide();
// 	$("#levelPage").show();
// 	$("#lastPage").hide();
// 	$("#message").css("visibility","hidden");
// 	document.body.style.backgroundImage = "url("+Utils.Path+"images/skin/levelBg.png";
// 	document.getElementById("level1").setAttribute("level",1);
// 	document.getElementById("level2").setAttribute("level",2);
// 	FlipIt.initializeVariables();
// }
//variable initialization
FlipIt.initializeVariables = function () {
	FlipIt.seconds = 0;
	FlipIt.levelIndex = 0;
	FlipIt.correctCounter = 0;
	FlipIt.question;
	FlipIt.attemptCounter = 0;
	FlipIt.wordLevel = 0;
	FlipIt.noOfQuestions = 0;
	FlipIt.attemptFlag = false;
	FlipIt.noResposnseFlag = false;
	FlipIt.soundQue;
	FlipIt.loadmetaDataFlag = true;
	FlipIt.timeOut;
	FlipIt.uniqueArray = [];
	FlipIt.totalQuestions = 5;
	FlipIt.objArr = [];
}
//Runs selection of level
FlipIt.selectLevel = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png";
	level = Math.floor(Math.random() * 2) + 1;//parseInt(document.getElementById(levelId).getAttribute("level"));
	FlipIt.levelIndex = level;
	FlipIt.playGame();
}

//shows the gamePage
FlipIt.playGame = function () {
	rNo = 0;
	$("#coverPage").hide();
	$("#levelPage").hide();
	$("#gamePage").show();
	$("#lastPage").hide();
	$(".header").css("visibility", "visible");
	FlipIt.findQuestions();
	FlipIt.setQuestion();

}

FlipIt.findQuestions = function () {
	var i, j, rno, randObject, randOption, option, obj = {}, rnoArr = [], refArr = [];
	for (i = 0; i < 5; i++) {
		obj = {};
		rno = Math.floor(Math.random() * FlipIt.data.length);
		while (rnoArr.includes(rno))
			rno = Math.floor(Math.random() * FlipIt.data.length);
		rnoArr.push(rno);
		randObject = Math.floor(Math.random() * FlipIt.data[rno].sentence.length);
		obj.wordLevel = rno;
		obj.question = FlipIt.data[rno].sentence[randObject];
		obj.optionArr = [];
		refArr = [];
		for (j = 0; j < 3; j++) {
			randOption = Math.floor(Math.random() * FlipIt.data[rno].sentence.length);
			while (refArr.includes(randOption) || randOption == randObject)
				randOption = Math.floor(Math.random() * FlipIt.data[rno].sentence.length);
			refArr.push(randOption);
			option = FlipIt.data[rno].sentence[randOption].hindi;
			obj.optionArr.push(option);
		}
		FlipIt.objArr.push(obj);
	}
	console.log(FlipIt.objArr);
}

//sets the four options for question
FlipIt.setQuestion = function () {
	FlipIt.attemptFlag = false;
	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();
	if (FlipIt.levelIndex == 2) {
		FlipIt.question = FlipIt.objArr[FlipIt.noOfQuestions].question.hindi;
		FlipIt.answer = FlipIt.objArr[FlipIt.noOfQuestions].question.english;
		FlipIt.soundQue = Utils.Path + "sounds/" + FlipIt.objArr[FlipIt.noOfQuestions].question.hindiSound;


		allOption.push(FlipIt.answer);
		for (i = 0; i < 3; i++) {
			allOption.push(FlipIt.objArr[FlipIt.noOfQuestions].question.option[i]);
		}
		shuffleArray(allOption);
		for (i = 0; i < allOption.length; i++) {
			document.getElementById("option" + (i + 1)).innerHTML = allOption[i];
		}
	}
	else {
		FlipIt.question = FlipIt.objArr[FlipIt.noOfQuestions].question.english;
		FlipIt.answer = FlipIt.objArr[FlipIt.noOfQuestions].question.hindi;
		FlipIt.soundQue = Utils.Path + "sounds/" + FlipIt.objArr[FlipIt.noOfQuestions].question.englishSound;
		allOption.push(FlipIt.answer);
		for (i = 0; i < 3; i++) {
			allOption.push(FlipIt.objArr[FlipIt.noOfQuestions].optionArr[i]);
		}
		shuffleArray(allOption);
		for (i = 0; i < allOption.length; i++) {
			document.getElementById("option" + (i + 1)).innerHTML = allOption[i];
		}
	}
	label = FlipIt.question;
	questionId = parseInt(FlipIt.objArr[FlipIt.noOfQuestions].question.questionId);
	if (FlipIt.objArr[FlipIt.noOfQuestions].wordLevel >= 0)
		$(".options").css("font-size", "3vw");
	$(".options").css("margin-top", "2vh");
	if (FlipIt.objArr[FlipIt.noOfQuestions].wordLevel > 1) {
		$(".options").css("font-size", "2.3vw");
		$(".options").css("margin-top", "2.5vh");
	}
	if (FlipIt.objArr[FlipIt.noOfQuestions].wordLevel > 3) {
		$(".options").css("font-size", "2vw");
		$(".options").css("margin-top", "3vh");
	}
	document.getElementById("option0").innerHTML = FlipIt.question;
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	FlipIt.startTimer();
	FlipIt.getQueSoundSrc();
}
//plays the question sound when loads the new question.
FlipIt.getQueSoundSrc = function () {
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	$(".optionDivs").css("pointer-events", "none");
	FlipIt.loadmetaDataFlag = true;
	FlipIt.getDuration(FlipIt.soundQue);
}

//gets the duration of question sound played.
FlipIt.getDuration = function (sound) {
	var duration = 0;
	$('#playSound').prop('src', sound);
	if (FlipIt.loadmetaDataFlag) {
		$('#playSound').on("loadedmetadata", function () {
			FlipIt.loadmetaDataFlag = false;
			$('#playSound').unbind("loadedmetadata");
			duration = $('#playSound').prop('duration');
			FlipIt.playQueSound(duration);
		}
		);
	}
	else
		$('#playSound').unbind("loadedmetadata");
}
//plays the question;
FlipIt.playQueSound = function (duration) {
	document.getElementById("playSound").play();
	if (FlipIt.playQuestionTime) {
		clearTimeout(FlipIt.playQuestionTime);
		FlipIt.playQuestionTime = null;
	}
	FlipIt.playQuestionTime = setTimeout(function () {
		$(".optionDivs").css("pointer-events", "auto");
		FlipIt.startTimer();
	}, duration * 1000);
}

//timer
FlipIt.startTimer = function () {
	if (FlipIt.noResponseTimer) {
		clearInterval(FlipIt.noResponseTimer);
		FlipIt.noResponseTimer = null;
		FlipIt.seconds = 0;
	}
	FlipIt.noResponseTimer = setInterval(function () {
		FlipIt.seconds++;
		if (FlipIt.seconds >= 7) {
			document.getElementById("playSound").src = Utils.Path + "sounds/instructions/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(FlipIt.noResponseTimer)
			if (FlipIt.timeOut) {
				clearTimeout(FlipIt.timeOut);
				FlipIt.timeOut = null;
			}
			FlipIt.timeOut = setTimeout(function () {
				FlipIt.seconds = 0;
				FlipIt.startTimer();
			}, 2000);
		}
	}, 1000);
}
//shows the gameover
FlipIt.endGame = function () {
	$('#responseBoxDiv').hide();
	correctCnt = FlipIt.correctCounter;
	attemptCnt = FlipIt.attemptCounter;
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	document.getElementById("playSound").pause();
	FlipIt.giveStars();
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/BBg.png";
	$("#message").css("visibility", "hidden");
	$("#gamePage").hide();
	$("#lastPage").show();
	$("#nextGame").addClass("blink_me");
	if (Utils.mobileDeviceFlag)
		Android.StudentCertification(correctCnt, FlipIt.totalQuestions, "7");
}
//runs @selecting the answer from the options
FlipIt.checkAnswer = function (divId) {
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	FlipIt.attemptFlag = true;
	FlipIt.attemptCounter++;
	document.getElementById("playSound").pause();
	$(".optionDivs").css("pointer-events", "none");
	$("#soundDiv").css("pointer-events", "none");
	document.getElementById(divId).style.pointerEvents = "none";
	if (document.getElementById(divId).children[0].innerHTML == FlipIt.answer) {
		scoredMarks = 100;
		FlipIt.correctCounter++;
		$("#" + divId).children().addClass("animated flash");
		document.getElementById("playSound").src = Utils.Path + "sounds/instructions/CorrectAksharkhadi.mp3";
		document.getElementById(divId).children[0].style.color = "#2de430";

	}
	else {
		scoredMarks = 0;
		document.getElementById("playSound").src = Utils.Path + "sounds/instructions/wrongSoundAksharkhadi.mp3";
		document.getElementById(divId).children[0].style.opacity = 0.5;
		$("#" + divId).children().addClass("animated shake");
	}
	document.getElementById("playSound").play();
	FlipIt.objArr.splice(FlipIt.noOfQuestions, 1);
	console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	if (FlipIt.nextQuestionTimeout) {
		clearTimeout(FlipIt.nextQuestionTimeout)
		FlipIt.nextQuestionTimeout = null;
	}
	FlipIt.nextQuestionTimeout = setTimeout(function () {
		FlipIt.showNextQuestion();
	}, 2000);
}

FlipIt.skipQuestion = function () {
	clearTimeout(nextQuestionTimeout);
	FlipIt.showNextQuestion();
}
//shows the next question.
FlipIt.showNextQuestion = function () {
	clearTimeout(FlipIt.nextQuestionTimeout);
	if (FlipIt.attemptFlag == false)
		FlipIt.noOfQuestions++;
	$(".options").css("color", "white");
	$(".optionDivs").css("pointer-events", "auto");
	$("#soundDiv").css("pointer-events", "auto");
	document.getElementById("playSound").pause();
	$(".options").removeClass("animated shake");
	$(".options").removeClass("animated flash");
	$(".options").css("opacity", 1);

	if (FlipIt.objArr.length == 0) {
		FlipIt.endGame();
	}
	else if (FlipIt.objArr.length != 0 && FlipIt.noOfQuestions >= FlipIt.objArr.length) {
		FlipIt.showPopUP();
	}
	else
		FlipIt.setQuestion();
}

FlipIt.showPopUP = function () {
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	clearTimeout(FlipIt.playQuestionTime);
	document.getElementById("playSound").pause();
	document.getElementById("playSound").src = "";
	$('#responseBoxDiv').show();
	$('#questionMsg').text(FlipIt.modalData.responseMsg);
	$('#Yes').text(FlipIt.modalData.yes);
	$('#No').text(FlipIt.modalData.no);
}

FlipIt.showSkippedQuestions = function () {
	FlipIt.noOfQuestions = 0;
	$('#responseBoxDiv').hide();
	FlipIt.setQuestion();
}

//reloads the page 
FlipIt.callhome = function () {
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	if (document.getElementById("levelPage").style.display == "block")
		location.reload();
	else {
		document.getElementById("playSound").pause();
		clearTimeout(FlipIt.nextQuestionTimeout);
		FlipIt.initializeVariables();
		FlipIt.showLevel();
	}

}

//on click of sound button
FlipIt.playSoundOnsoundClick = function () {
	$('#playSound').prop('src', FlipIt.soundQue);
	clearInterval(FlipIt.noResponseTimer);
	clearTimeout(FlipIt.timeOut);
	document.getElementById("playSound").play();
	setTimeout(function () {
		FlipIt.startTimer();
	}, 1000);
}
//creates stars according to the score of game
FlipIt.giveStars = function () {
	var fractionVar, i, numberOfStars = FlipIt.correctCounter;
	for (i = 1; i <= Math.floor(numberOfStars); i++)
		document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
	$("#starDiv").css("visibility", "visible");
	if (numberOfStars != 0) {
		document.getElementById("playSound").src = Utils.Path + "sounds/instructions/" + FlipIt.sounds[(numberOfStars - 1)].sound;
		document.getElementById("playSound").play();
	}
};

FlipIt.showNextGame = function () {
	if (Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}

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);
// 			}
// 			FlipIt.enableClick(duration);
// 			}	
// 		);
//     }
//     else
// 		$('#playSound').unbind("loadedmetadata");
// }
// FlipIt.enableClick=function(duration)
// {
// 	setTimeout(function()
// 	{
// 		$(".optionDivs").css("pointer-events","auto");
// 	},duration*900);
// }
