//starting Date:09-01-2019
var Fraction = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
Fraction.questionCtr = 0;
Fraction.soundFlag = false;
Fraction.attemptFlag = false;
Fraction.firstAttemptFlag = true;
Fraction.storedArr = [];
var questionId = 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;
$(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("Fraction"); 
	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 = [];
}

//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/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";
	document.getElementById("gameOver").innerHTML = Fraction.hardcodedData.gameOver;
}
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();
	$(".header").css("visibility", "visible");
	element = document.getElementById("questionDiv");
	canvas.style.width = "100%";
	canvas.width = element.offsetWidth;
	canvas.height = element.offsetHeight;
	optionHeight = element.offsetHeight;
	optionWidth = element.offsetWidth;
	Fraction.displayQuestion();
}

//displays question
Fraction.displayQuestion = function () {
	//var c = document.getElementById("circle");
	//var ctx = c.getContext("2d");
	//ctx.beginPath();
	//moveTo(100,100);
	//ctx.arc(100, 100, 40, 0.5*Math.PI,  0);
	//ctx.stroke();
	//ctx.beginPath();
	//ctx.arc(100, 100, 40, 0,  0.5* Math.PI);
	//ctx.lineTo(100,100);
	//ctx.fill();
	//ctx.stroke();

	Fraction.calculateFraction();
}

Fraction.calculateFraction = function () {
	var rNo, arr = [];
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	if (!(Fraction.soundFlag)) {
		Fraction.playInstruction();
		Fraction.soundFlag = true;
	}
	Fraction.totalParts = Math.floor(Math.random() * 8 + 2);
	console.log(Fraction.totalParts);
	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);
	while (JSON.stringify(Fraction.storedArr).includes(JSON.stringify(arr))) {
		arr = [];
		Fraction.totalParts = Math.floor(Math.random() * 8 + 2);
		console.log(Fraction.totalParts);
		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);
	}
	Fraction.storedArr.push(arr);
	Fraction.questionCtr++;
	rNo = Math.floor(Math.random() * Fraction.colorArr.length);
	Fraction.fillColor = Fraction.colorArr[rNo];
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.clearRect(0, 0, canvas.width, canvas.height);


	console.log(Fraction.coloredParts);
	rNo = Math.floor(Math.random() * 2);
	if (rNo == 0)
		Fraction.drawWheel();
	else
		Fraction.drawRectangle();
	Fraction.setOptions();

}
Fraction.drawWheel = function () {
	//ctx.clearRect(0,0,500,200);
	//ctx.clearRect(0,0,canvas.width,canvas.height);
	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.totalParts;
		//ctx = canvas.getContext("2d");

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

		for (var i = 0; i < Fraction.totalParts; i++) {
			var angle = -(startAngle + i * arc);
			if (i < Fraction.coloredParts) {
				ctx.fillStyle = Fraction.fillColor;
				var img = document.getElementById("image");
				$(img).css("z-index", "1");
				//ctx.drawImage(img,leftValue,topValue,30,30);
				//ctx.drawImage(img,leftValue+50,topValue+10,30,30);
				//ctx.drawImage(img,leftValue+50,topValue-10,30,30);
				//var imgData = ctx.getImageData(10, 10, 50, 50);
				//ctx.putImageData(imgData, 10, 70);
			}
			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);
			console.log(angle + arc);


			ctx.stroke();
			ctx.fill();
			//ctx.closePath();
			//ctx.save();      	
			randomNum = Math.floor(Math.random() * outsideRadius);
			console.log("randomNum  " + randomNum);
			if (i < Fraction.coloredParts) {

				var coordinatesX = (outsideRadius * 3.5 / 5) * Math.cos(angle + arc / 2);
				console.log(coordinatesX);
				var coordinateY = (outsideRadius * 3.5 / 5) * Math.sin(angle + arc / 2);
				console.log(coordinateY);
				//ctx.drawImage(img, leftValue + coordinatesX, topValue + coordinateY, 20, 20);
			}
			ctx.restore();
		}
	}
}

Fraction.drawRectangle = function () {
	//ctx.clearRect(0,0,500,200);
	//ctx.clearRect(0,0,canvas.width,canvas.height);
	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 canvas = document.getElementById("circle");
	//	ctx = canvas.getContext("2d");
	var xyz = currX;
	ctx.rect(currX, currY, width, height);
	ctx.lineWidth = 3;
	ctx.strokeStyle = "black";
	ctx.stroke();
	colWidth = (width / Fraction.totalParts);
	console.log("diiii" + colWidth);
	//ctx.beginPath();
	//	ctx.fillRect(xyz,80,30,60); //= "#04AB90";

	for (i = 0; i < Fraction.totalParts; i++) {
		ctx.beginPath();
		ctx.moveTo(xyz, currY);
		ctx.lineTo(xyz, height + optionHeight / 20);
		ctx.strokeStyle = "black";
		ctx.stroke();
		ctx.fillStyle = "#FFFFFF";
		if (i < Fraction.coloredParts) {
			ctx.fillStyle = Fraction.fillColor;//"#04AB90";
			var img = document.getElementById("image");
			//ctx.drawImage(img, currX, currY, 30, 30);
		}
		ctx.fillRect(xyz, currY, colWidth, height);
		//ctx.lineWidth = 3;		
		ctx.fill();
		xyz = xyz + colWidth;
	}
}

// Fraction.setOptions = function () {
// 	var i = 0, randOption1 = 0, randOption2 = 0;
// 	Fraction.ans = Fraction.coloredParts + "/" + Fraction.totalParts;
// 	Fraction.ansArr.push(Fraction.ans);
// 	for (i = 0; i < 3; i++) {
// 		randOption1 = Math.floor(Math.random() * 8 + 2);
// 		randOption2 = Math.floor(Math.random() * 7 + 1);
// 		while (randOption1 <= randOption2 || (randOption2 / randOption1 == Fraction.ans))
// 			randOption1 = Math.floor(Math.random() * 8 + 2);
// 		if (Fraction.ansArr.includes(randOption2 + "/" + randOption1)) {
// 			i--;
// 			continue;
// 		}
// 		else
// 			Fraction.ansArr.push(randOption2 + "/" + randOption1);
// 	}
// 	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.setOptions = function () {
	var i = 0, randOption1 = 0, randOption2 = 0, arr = [], divisionArr = [];
	arr.push(Fraction.coloredParts);
	arr.push(Fraction.totalParts)
	divisionArr.push(Fraction.coloredParts / Fraction.totalParts)
	Fraction.ansArr.push(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)) || divisionArr.includes(randOption1 / randOption2)) {
			arr = [];
			i--;
			continue;
		}
		else {
			Fraction.ansArr.push(arr);
			divisionArr.push(randOption1 / randOption2)
		}
		arr = [];
	}
	console.log(Fraction.ansArr);
	Fraction.shuffle(Fraction.ansArr);
	for (i = 1; i <= Fraction.ansArr.length; i++) {
		document.getElementById("numer" + i).innerHTML = Fraction.ansArr[i - 1][0];
		document.getElementById("denomr" + i).innerHTML = Fraction.ansArr[i - 1][1];
	}
}

Fraction.checkAnswer = function (div) {
	document.getElementById("playSound").pause();
	Fraction.attemptFlag = true;
	if (document.getElementById(div).children[0].innerHTML == Fraction.coloredParts && document.getElementById(div).children[1].innerHTML == Fraction.totalParts) {
		document.getElementById(div).style.backgroundColor = "green";
		$("#" + div).addClass("animated bounce");
		$(".options").css("pointer-events", "none");
		document.getElementById("playSound").src = Utils.Path + "sounds/CorrectAksharkhadi.mp3";
		//document.getElementById("playSound").play();
		//alert("correct");
		if (Fraction.firstAttemptFlag)
			scoredMarks = 10;
		Fraction.nextQuestionTimer = setTimeout(function () {
			if (Fraction.fractionFlag) {
				Fraction.showFractionQuestion();
				Fraction.fractionFlag = false;
			}
			else {
				Fraction.nextQuestion();
			}
		}, 2000);
	}
	else {
		Fraction.firstAttemptFlag = false;
		scoredMarks = 0;
		document.getElementById(div).style.backgroundColor = "red";
		$("#" + div).addClass("animated shake");
		document.getElementById("playSound").src = Utils.Path + "sounds/wrongSoundAksharkhadi.mp3";
		setTimeout(function () {
			document.getElementById(div).style.backgroundColor = "";
			$("#" + div).removeClass("animated shake");
		}, 1500);
	}

	document.getElementById("playSound").play();
	//alert("wrong");
}

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 () {
	$(".options").css("background-color", "");
	$(".options").removeClass("animated bounce");
	$(".options").css("pointer-events", "auto");
	clearTimeout(Fraction.nextQuestionTimer);

	if (!Fraction.attemptFlag)
		scoredMarks = -1;
	console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	Fraction.attemptFlag = false;
	Fraction.firstAttemptFlag = true;
	document.getElementById("playSound").pause();
	var width, height;
	//Fraction.fractionFlag = true;
	//width=canvas.width;
	//height=canvas.height;
	//console.log(width);
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.save();
	$("#questionDiv").show();
	$("#fractionQuestion").hide();
	//canvas =document.getElementById("canvasId");
	//ctx = canvas.getContext("2d");
	//$(".options").empty();
	Fraction.initializeVariables();
	if (Fraction.questionCtr < 5) {
		Fraction.calculateFraction();
	}

	else {
		Fraction.endGame();

	}
}
Fraction.endGame = function () {
	$("#gamePage").hide();
	$("#endPage").show();

}

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.callhome = function () {
	if (Fraction.attemptFlag) {
		console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
		if (Utils.mobileDeviceFlag)
			Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	}
	location.reload();
}

Fraction.createAcknowledgementDivs = function () {
	var i = 0, div;
	for (i = 0; i < Object.keys(Fraction.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(Fraction.AcknowledgementPageData)[i] + " : " + Object.values(Fraction.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 = Fraction.hardcodedData['createdOn'];
	div.style.marginBottom = "2vh";
	acknowledgementDiv.appendChild(div);
}

Fraction.showAcknowledgement = function () {
	$("#acknowledgementDiv").show();

}

Fraction.playAgain = function () {
	Fraction.storedArr = [];
	Fraction.soundFlag = true;
	$("#acknowledgementDiv").hide();
	$("#endPage").hide();
	$("#gamePage").show();
	Fraction.questionCtr = 0;
	Fraction.displayQuestion();
}
Fraction.playInstruction = function () {
	document.getElementById("playSound").src = Utils.Path + "sounds/fractionInstruction1.mp3";
	document.getElementById("playSound").play();
}