//starting Date:09-01-2019
var Fraction = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
Fraction.questionCtr = 0;
Fraction.soundFlag = false;
var quesId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, level = 1, label;
var ctx, canvas, optionWidth, optionHeight;
canvas = document.getElementById("canvasId");
ctx = canvas.getContext("2d");
Fraction.fractionFlag = false;
Fraction.questionArr = [];
Fraction.seconds = 0;
Fraction.correctCnt = 0;
Fraction.storedArr = [];
$(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;
	setTimeout(function () {
		Fraction.init();
	}, 100);
});
//shows coverPage
Fraction.init = function () {
	document.title = Object.values(Fraction.AcknowledgementPageData)[0];
	$("#coverPage").show();
	$("#gamePage").hide();
	$("#endPage").hide();
	//$(".header").not("#logo").css("visibility", "hidden");
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/GameCover.png";
	Fraction.setAllImages();
	Fraction.createOptionDivs();
	Fraction.initializeVariables();
	//Fraction.createAcknowledgementDivs();
}

Fraction.initializeVariables = function () {
	Fraction.ansArr = [];
	Fraction.nextTimeout = 0;
}

//set sources to images
Fraction.setAllImages = function () {
	document.getElementById("homeImage").src = Utils.Path + "images/skin/Home.png";
	document.getElementById("logoImage").src = Utils.Path + "images/skin/logo.png";
	document.getElementById("playImg").src = Utils.Path + "images/skin/Play.png";
	document.getElementById("nextImg").src = Utils.Path + "images/skin/Skip.png";
	document.getElementById("nextGame").src = Utils.Path + "images/skin/Next.png";
	//document.getElementById("creditImg").src = Utils.Path + "images/skin/Credit.png";
	//document.getElementById("replayImg").src = Utils.Path + "images/skin/playAgain.png";
	document.getElementById("soundImg").src = Utils.Path + "images/skin/Sound.png";
}
Fraction.createOptionDivs = function () {
	var i = 0, parentDiv, optionDiv;
	parentDiv = document.getElementById("optionDiv");
	for (i = 1; i <= 4; i++) {
		optionDiv = document.createElement("DIV");
		optionDiv.setAttribute("id", "optionDiv" + i);
		optionDiv.setAttribute("class", "options 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");
		optionDiv.setAttribute("onclick", "Fraction.checkAnswer(this.id);");
		//optionDiv.style.backgroundColor = "#779fd3";
		optionDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/Score.png";
		parentDiv.appendChild(optionDiv);

		numer = document.createElement("DIV");
		numer.setAttribute("id", "numer" + i);
		numer.setAttribute("class", "border_bottom nopadding col-xs-12 col-md-12 col-lg-12 col-sm-12");
		optionDiv.appendChild(numer);

		denomr = document.createElement("DIV");
		denomr.setAttribute("id", "denomr" + i);
		denomr.setAttribute("class", " nopadding col-xs-12 col-md-12 col-lg-12 col-sm-12");
		optionDiv.appendChild(denomr);
	}
}

//starts game
Fraction.playGame = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Game_bg.png";
	$("#coverPage").hide();
	$("#gamePage").show();
	element = document.getElementById("questionDiv");
	canvas.style.width = "100%";
	canvas.width = element.offsetWidth;
	canvas.height = element.offsetHeight;
	optionHeight = element.offsetHeight;
	optionWidth = element.offsetWidth;

	Fraction.getQuestion();
	Fraction.createStars();
}
Fraction.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/star5.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
	//$("#starDiv").css("display","none");
};

Fraction.getQuestion = function () {
	var questionObj = {}, rNo = 0;
	for (var i = 0; i < 5; i++) {
		questionObj = {};
		arr = [], Fraction.ansArr = [];
		rNo = 0;
		Fraction.totalParts, Fraction.coloredParts = 0;
		rNo = Math.floor(Math.random() * 2);
		Fraction.totalParts = Math.floor(Math.random() * 8 + 2);
		Fraction.coloredParts = Math.floor(Math.random() * 8 + 1);


		while (Fraction.totalParts <= Fraction.coloredParts)
			Fraction.coloredParts = Math.floor(Math.random() * 8 + 1);
		arr.push(Fraction.coloredParts, Fraction.totalParts);
		if (JSON.stringify(Fraction.storedArr).includes(JSON.stringify(arr))) {
			i--;
			continue;
		}
		else
			Fraction.storedArr.push(arr);
		Fraction.ansArr.push(arr);
		Fraction.setOptions();
		questionObj['shape'] = rNo;
		questionObj['question'] = arr;
		questionObj['options'] = Fraction.ansArr;
		Fraction.questionArr.push(questionObj);
	}
	console.log(Fraction.questionArr);
	Fraction.totalQue = Fraction.questionArr.length;
	Fraction.setQuestionAndOption();
}
Fraction.setQuestionAndOption = function () {
	var rndColor;
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	Fraction.gamePlayedFlag = false;
	Fraction.startTimer();
	if (!(Fraction.soundFlag)) {
		Fraction.playInstruction();
		Fraction.soundFlag = true;
	}
	rndColor = Math.floor(Math.random() * Fraction.colorArr.length);
	Fraction.fillColor = Fraction.colorArr[rndColor];
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	if (Fraction.questionArr[Fraction.questionCtr]['shape'] == 0)
		Fraction.drawWheel();
	else
		Fraction.drawRectangle();

	for (i = 1; i <= Fraction.questionArr[Fraction.questionCtr]['options'].length; i++) {
		document.getElementById("numer" + i).innerHTML = Fraction.questionArr[Fraction.questionCtr]['options'][i - 1][0];
		document.getElementById("denomr" + i).innerHTML = Fraction.questionArr[Fraction.questionCtr]['options'][i - 1][1];
	}
}

Fraction.drawWheel = function () {
	ctx.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<
	ctx.moveTo(0, 0);
	ctx.lineWidth = 3;
	ctx.lineTo(0, 0);
	ctx.stroke();
	//$("#canvasId").remove();file:///home/pi/Desktop/aj/working/fraction/images/Next.png
	ctx.save();
	var startAngle = 0, leftValue = optionWidth / 2, topValue = optionHeight / 2, left = 50, top = 10;
	if (canvas.getContext) {
		var outsideRadius = optionWidth / 3.5;
		var insideRadius = 1;
		var arc = Math.PI * 2 / Fraction.questionArr[Fraction.questionCtr]['question'][1];

		ctx.beginPath();
		ctx.fillStyle = "#3A3A3F";
		ctx.strokeStyle = "black";
		ctx.lineWidth = 3;

		for (var i = 0; i < Fraction.questionArr[Fraction.questionCtr]['question'][1]; i++) {
			var angle = -(startAngle + i * arc);
			if (i < Fraction.questionArr[Fraction.questionCtr]['question'][0]) {
				ctx.fillStyle = Fraction.fillColor;
				var img = document.getElementById("image");
				$(img).css("z-index", "1");
			}
			else
				ctx.fillStyle = "#FFFFFF";

			ctx.beginPath();
			ctx.lineWidth = 3;
			ctx.lineTo(leftValue, topValue);
			ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
			ctx.arc(leftValue, topValue, insideRadius, angle + arc, angle, true);
			ctx.stroke();
			ctx.fill();
			randomNum = Math.floor(Math.random() * outsideRadius);
			if (i < Fraction.questionArr[Fraction.questionCtr]['question'][0]) {

				var coordinatesX = (outsideRadius * 3.5 / 5) * Math.cos(angle + arc / 2);
				var coordinateY = (outsideRadius * 3.5 / 5) * Math.sin(angle + arc / 2);
			}
			ctx.restore();
		}
	}
}

Fraction.drawRectangle = function () {

	ctx.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<
	ctx.moveTo(0, 0);
	ctx.lineTo(0, 0);
	ctx.stroke();
	ctx.save();
	//$("#canvasId").remove();
	var i = 0, width = optionWidth - optionWidth / 10, height = optionHeight - optionHeight / 10, colWidth, currX = optionWidth / 20, currY = optionHeight / 20;

	var xyz = currX;
	ctx.rect(currX, currY, width, height);
	ctx.lineWidth = 3;
	ctx.strokeStyle = "black";
	ctx.stroke();
	colWidth = (width / Fraction.questionArr[Fraction.questionCtr]['question'][1]);

	for (i = 0; i < Fraction.questionArr[Fraction.questionCtr]['question'][1]; i++) {
		ctx.beginPath();
		ctx.moveTo(xyz, currY);
		ctx.lineTo(xyz, height + optionHeight / 20);
		ctx.strokeStyle = "black";
		ctx.stroke();
		ctx.fillStyle = "#FFFFFF";
		if (i < Fraction.questionArr[Fraction.questionCtr]['question'][0]) {
			ctx.fillStyle = Fraction.fillColor;//"#04AB90";
			var img = document.getElementById("image");
		}
		ctx.fillRect(xyz, currY, colWidth, height);
		ctx.fill();
		xyz = xyz + colWidth;
	}
}

Fraction.setOptions = function () {
	var i = 0, randOption1 = 0, randOption2 = 0, arr = [];
	arr = [];
	for (i = 0; i < 3; i++) {
		randOption1 = Math.floor(Math.random() * 7 + 1);
		randOption2 = Math.floor(Math.random() * 8 + 2);
		while (randOption1 >= randOption2)
			randOption1 = Math.floor(Math.random() * 7 + 1);
		arr.push(randOption1);
		arr.push(randOption2);
		if (JSON.stringify(Fraction.ansArr).includes(JSON.stringify(arr))) {
			arr = [];
			i--;
			continue;
		}
		else
			Fraction.ansArr.push(arr);
		arr = [];
	}
	Fraction.shuffle(Fraction.ansArr);
}

Fraction.checkAnswer = function (div) {
	Fraction.gamePlayedFlag = true;
	document.getElementById("playSound").pause();
	Fraction.clearSound();
	$(".options").css("pointer-events", "none");
	if (document.getElementById(div).children[0].innerHTML == Fraction.questionArr[Fraction.questionCtr]['question'][0] && document.getElementById(div).children[1].innerHTML == Fraction.questionArr[Fraction.questionCtr]['question'][1]) {
		scoredMarks = 10;
		Fraction.correctCnt++;
		document.getElementById(div).style.backgroundColor = "green";
		$("#" + div).addClass("animated bounce");
		document.getElementById("playSound").src = Utils.Path + "sounds/CorrectAksharkhadi.mp3";
	}
	else {
		scoredMarks = 0;
		document.getElementById(div).style.backgroundColor = "red";
		$("#" + div).addClass("animated shake");
		document.getElementById("playSound").src = Utils.Path + "sounds/wrongSoundAksharkhadi.mp3";
	}

	document.getElementById("playSound").play();
	//alert("wrong");
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, quesId, scoredMarks, totalMarks, level, startTime);
	console.log(resId, quesId, scoredMarks, totalMarks, level, startTime);
	Fraction.questionArr.splice(Fraction.questionCtr, 1);
	Fraction.nextTimeout = setTimeout(function () {
		if (Fraction.fractionFlag) {
			Fraction.showFractionQuestion();
			Fraction.fractionFlag = false;
		}
		else {
			Fraction.nextQuestion();
		}
	}, 2000);
}
Fraction.clearSound = function () {
	clearTimeout(Fraction.AnsQuestionTimer);
	clearInterval(Fraction.noResponseTimer);
	clearTimeout(Fraction.timeOut);
	Fraction.AnsQuestionTimer = null;
	Fraction.timeOut = null;
}
Fraction.shuffle = function (array) {
	var ctr = array.length, temp, index;
	while (ctr > 0) {
		index = Math.floor(Math.random() * array.length);
		ctr--;
		temp = array[ctr];
		array[ctr] = array[index];
		array[index] = temp;
	}
}
Fraction.nextQuestion = function () {
	if (Fraction.gamePlayedFlag == false) {
		Fraction.skippedCnt++;
		Fraction.questionCtr++;
	}
	if (Fraction.questionArr.length == 0)
		Fraction.showLastPage();
	else if (Fraction.questionCtr >= Fraction.questionArr.length && Fraction.questionArr.length != 0)
		Fraction.showPopup();
	else {
		Fraction.resetVariables();
		Fraction.setQuestionAndOption();
	}
}
Fraction.resetVariables = function () {
	clearTimeout(Fraction.nextTimeout);
	document.getElementById("playSound").pause();
	$(".options").removeClass("animated bounce");
	$(".options").removeClass("animated shake");
	$(".options").css("pointer-events", "auto");
	$(".options").css("background-color", "");
	var width, height;
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.save();
	$("#questionDiv").show();
	$("#fractionQuestion").hide();
	Fraction.initializeVariables();
}

Fraction.showSkippedQuestions = function () {
	$('#responseBoxDiv').hide();
	Fraction.skipFlag = true;
	Fraction.skippedCnt = 0
	Fraction.questionCtr = 0;
	Fraction.resetVariables();
	Fraction.setQuestionAndOption();
}
Fraction.showPopup = function () {
	document.getElementById('playSound').pause();
	Fraction.clearSound();
	$('#responseBoxDiv').show();
	$('#questionMsg').text(Fraction.modalData.responseMsg);
	$('#Yes').text(Fraction.modalData.yes);
	$('#No').text(Fraction.modalData.no);
}

Fraction.showLastPage = function () {
	$('#responseBoxDiv').hide();
	Fraction.giveStars();
	document.getElementById('playSound').pause();
	$('#gameOver').text(Fraction.hardcodedData.gameOver);
	document.getElementById('endpage').style.display = "block";
	document.getElementById('gamePage').style.display = "none";
	Fraction.clearSound();
	document.getElementById('nextgameDiv').classList.add('blink_me');
	if (Fraction.correctCnt > 0) {
		document.getElementById('playSound').src = "sounds/instruction/star" + Fraction.correctCnt + ".mp3";
		document.getElementById('playSound').play();
	}
	if (Utils.mobileDeviceFlag)
		Android.StudentCertification(Fraction.correctCnt, Fraction.totalQue, "3");
}
Fraction.giveStars = function () {
	var fractionVar, i, numberOfStars = Fraction.correctCnt;
	fractionVar = numberOfStars - Math.floor(numberOfStars);
	for (i = 1; i <= Math.floor(numberOfStars); i++)
		document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/star1.png");
	$("#starDiv").css("visibility", "visible");
};
Fraction.showFractionQuestion = function () {
	$("#questionDiv").hide();
	$("#fractionQuestion").show();
	$(".options").empty();
	document.getElementById("fractionQuestion").innerHTML = Fraction.ans;
	Fraction.setFractionOptions();
	var rNo = Math.random() * 1;
	rNo = rNo.toFixed(2);
	console.log(rNo);
}

Fraction.setFractionOptions = function () {
	var i = 0, randOption = 0;
	Fraction.ansArr = [];
	Fraction.ans = Fraction.coloredParts / Fraction.totalParts;
	Fraction.ans = Fraction.ans.toFixed(2);
	console.log(Fraction.ans);
	Fraction.ansArr.push(Fraction.ans);
	for (i = 0; i < 3; i++) {
		randOption = Math.random() * 1;
		randOption = randOption.toFixed(2);
		if (Fraction.ansArr.includes(randOption)) {
			i--;
			continue;
		}
		else
			Fraction.ansArr.push(randOption);
	}
	console.log(Fraction.ansArr);
	Fraction.shuffle(Fraction.ansArr);
	for (i = 1; i <= Fraction.ansArr.length; i++) {
		document.getElementById("optionDiv" + i).innerHTML = Fraction.ansArr[i - 1];
	}

}

Fraction.playInstruction = function () {
	Fraction.clearSound();
	document.getElementById("playSound").src = Utils.Path + "sounds/fractionInstruction1.mp3";
	document.getElementById("playSound").play();
	if (Fraction.AnsQuestionTimer) {
		clearTimeout(Fraction.AnsQuestionTimer);
		Fraction.AnsQuestionTimer = null;
	}
	Fraction.AnsQuestionTimer = setTimeout(function () {
		Fraction.startTimer();
	}, 5000);
}
Fraction.startTimer = function () {
	if (Fraction.noResponseTimer) {
		clearInterval(Fraction.noResponseTimer);
		Fraction.noResponseTimer = null;
		Fraction.seconds = 0;
	}
	Fraction.noResponseTimer = setInterval(function () {
		Fraction.seconds++;
		if (Fraction.seconds >= 7) {
			document.getElementById("playSound").src = Utils.Path + "sounds/instruction/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(Fraction.noResponseTimer);
			Fraction.timeOut = setTimeout(function () {
				Fraction.seconds = 0;
				Fraction.startTimer();
			}, 2000);
		}
	}, 1000);
}

Fraction.goNext = function () {
	clearInterval(Fraction.noResponseTimer);
	if (Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}