var NumberOrdering = {};
var Utils = {};
Utils.Path = "";
Utils.mobileDeviceFlag = false;

NumberOrdering.noOfQuestions = 0;
NumberOrdering.questionArr = [];
NumberOrdering.Counter = 0;
NumberOrdering.questionCounter = 0;
NumberOrdering.questionOrderArr = [];
NumberOrdering.correctCounter = 0;
NumberOrdering.noResponseTimer = null;
NumberOrdering.seconds = 0;



var questionId = 0,
	startTime = 0,
	scoredMarks = 0,
	totalMarks = 10,
	label="",
	resId = 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;

	setTimeout(function() {
		$("#gameOverText").text(NumberOrdering.hardCodedData.gameovertext);
		NumberOrdering.setAllimages();
		NumberOrdering.init();
	},200);
});

NumberOrdering.setAllimages = function() {
	$("#playGame").prop("src",Utils.Path + "images/Play.png");
	$("#FinalOk").prop("src",Utils.Path + "images/doll.gif");
	$("#Next").prop("src",Utils.Path + "images/Skip.png");
	$("#Sound").prop("src",Utils.Path + "images/Sound.png");
	$("#Check").prop("src",Utils.Path + "images/Check.png");
	$("#nextGameImg").prop("src",Utils.Path + "images/Next.png");
	$("#level1").prop("src",Utils.Path + "images/green-Leaf-with-1.png");
	$("#level2").prop("src",Utils.Path + "images/green-Leaf-with-2.png");
	$("#Home").prop("src",Utils.Path + "images/Home.png");
	$("#creditImg").prop("src",Utils.Path + "images/Credit.png");
	$("#replayImg").prop("src",Utils.Path + "images/Replay.png");
	$("#logo").prop("src",Utils.Path + "images/logo.png");
};

NumberOrdering.setHardcodedData = function() {
	$(document).prop("title",NumberOrdering.AcknowledgementPageData.NameoftheGame);
	$("#questionMsg").text(NumberOrdering.hardCodedData.responseMsg);
	$("#Yes").text(NumberOrdering.hardCodedData.yes);
	$("#No").text(NumberOrdering.hardCodedData.no);
};
NumberOrdering.init = function() {
	$("#coverPage,#playGame,#playGameDiv").show();
	$("#gamePage,#levelDiv,#endPage").hide();
	$("#background").css({
		"background-image":
			"url(" +
			Utils.Path +
			"images/" +
			NumberOrdering.hardCodedData["coverPage"] +
			")"
	});
	$("#playGame").on("click",function() {
		NumberOrdering.playInstruction();
		NumberOrdering.startGame();
	});
	NumberOrdering.setHardcodedData();
	NumberOrdering.createStars();
	NumberOrdering.AcknowledgementPage();
	NumberOrdering.numbercount = 8;
	for(let i = 0; i < 5; i++)
		NumberOrdering.generateQuestions(i);
};

NumberOrdering.startGame = function() {
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	NumberOrdering.level = 0;
	//questionId++;
	NumberOrdering.replay = false;
	$("#NumbersDiv,.spaces,.align6InLine").empty();
	$("#gamePage,#Next").show();
	$("#coverPage,#FinalOk").hide();
	NumberOrdering.AllNumbers = [];
	NumberOrdering.answerCounter = 0;
	NumberOrdering.gameOpened = false;
	NumberOrdering.optionArray = ["ascending","descending"];
	NumberOrdering.chooseNumbers();
	clearTimeout(NumberOrdering.noResponseTimer);
	NumberOrdering.startTimer();
};
NumberOrdering.playInstruction = function() {
	clearInterval(NumberOrdering.noResponseTimer);
	NumberOrdering.seconds=0;
	NumberOrdering.soundFlag=true;
	src =  Utils.Path + "sounds/" + NumberOrdering.hardCodedData.instruction;
	NumberOrdering.getDuration(src);
};
NumberOrdering.addLevels = function() {
	$("#playGame,#playGameDiv,#gamePage").hide();
	$("#background").css({
		"background-image":
			"url(" + Utils.Path + "images/" + NumberOrdering.hardCodedData["BG"] + ")"
	});
	$("#levelDiv,#coverPage").show();
};

NumberOrdering.createInstructionSpans = function(instructionText) {
	document.getElementById('Title').innerHTML = "";
	let wordsArr = instructionText.split(" ");
	for(let i = 0; i < wordsArr.length; i++) {
		let span = document.createElement('span');
		span.setAttribute('id','span' + i);
		span.innerHTML = " " + wordsArr[i];
		if(i == 2)
			span.style.color = "yellow";
		document.getElementById('Title').appendChild(span);
	}
};
//generate questions array
NumberOrdering.generateQuestions = function(questionsNo) {
	let randomNumber = 0;
	switch(questionsNo) {
		case 0:
			NumberOrdering.arrOfNumbers = [];
			randomNumber = Math.floor(Math.random() * 99995);
			for(var i = 0; i < NumberOrdering.numbercount; i++) {
				NumberOrdering.arrOfNumbers.push(randomNumber);
				randomNumber++;
			}
			NumberOrdering.questionArr.push(NumberOrdering.arrOfNumbers);
			NumberOrdering.questionOrderArr.push(0);
			break;
		case 1:
			NumberOrdering.arrOfNumbers = [];
			randomNumber = Math.floor(Math.random() * (99995 - 1110) + 1110);
			for(var i = 0; i < NumberOrdering.numbercount; i++) {
				NumberOrdering.arrOfNumbers.push(randomNumber);
				randomNumber--;
			}
			NumberOrdering.questionArr.push(NumberOrdering.arrOfNumbers);
			NumberOrdering.questionOrderArr.push(1);
			break;
		case 2:
			NumberOrdering.arrOfNumbers = [];
			for(var i = 0; i < NumberOrdering.numbercount; i++) {
				randomNumber = Math.floor(Math.random() * 99995);
				while($.inArray(randomNumber,NumberOrdering.arrOfNumbers) >= 0) {
					randomNumber = Math.floor(Math.random() * 99995);
				}
				NumberOrdering.arrOfNumbers.push(randomNumber);
			}
			NumberOrdering.arrOfNumbers.sort(function(a,b) {
				return a - b;
			});
			NumberOrdering.questionArr.push(NumberOrdering.arrOfNumbers);
			NumberOrdering.questionOrderArr.push(0);
			break;
		case 3:
			NumberOrdering.arrOfNumbers = [];
			for(var i = 0; i < NumberOrdering.numbercount; i++) {
				randomNumber = Math.floor(Math.random() * (99995 - 1110) + 10);
				while($.inArray(randomNumber,NumberOrdering.arrOfNumbers) >= 0) {
					randomNumber = Math.floor(Math.random() * (99995 - 1110) + 1110);
				}
				NumberOrdering.arrOfNumbers.push(randomNumber);
			}
			NumberOrdering.arrOfNumbers.sort(function(a,b) {
				return b - a;
			});
			NumberOrdering.questionArr.push(NumberOrdering.arrOfNumbers);
			NumberOrdering.questionOrderArr.push(1);
			break;
		case 4:
			NumberOrdering.generateQuestions(Math.floor(Math.random() * 4));
			break;
	}
};

NumberOrdering.chooseNumbers = function() {
	label = NumberOrdering.optionArray[NumberOrdering.questionOrderArr[NumberOrdering.questionCounter]];
	NumberOrdering.createInstructionSpans(NumberOrdering.hardCodedData["" + NumberOrdering.optionArray[NumberOrdering.questionOrderArr[NumberOrdering.questionCounter]]]);
	NumberOrdering.addSpacesForBarakhadi();
};


NumberOrdering.allowDrop = function(event) {
	event.preventDefault();
};

NumberOrdering.shuffleNumbers = function(array) {
	var i = 0,
		j = 0,
		temp = 0;
	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;
	}
};

NumberOrdering.addSpacesForBarakhadi = function() {
	var div,
		spanElement,
		outerDiv,
		k = 0;
	var tempArray = [];
	tempArray = NumberOrdering.questionArr[NumberOrdering.questionCounter].slice();
	NumberOrdering.shuffleNumbers(tempArray);
	for(var i = 0; i < 2; i++) {
		outerDiv = $(
			'<div style="margin-top:1%;margin-bottom:3%" class=" col-lg-12 col-md-12 col-xs-12 col-sm-12"></div>'
		);
		for(var j = 0; j < 4; j++) {
			innerDiv = $(
				'<div id="innerDiv' +
				k +
				'" class="text-center noPadding col-lg-3 col-md-3 col-xs-3 col-sm-3"></div>'
			);
			$(innerDiv).data("Answer",NumberOrdering.questionArr[NumberOrdering.questionCounter][k]);
			div = $(
				'<div id="div' +
				k +
				'"class="align6InLine noPadding text-center col-lg-10 col-md-10 col-xs-10 col-sm-10 col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 left" >' +
				NumberOrdering.questionArr[NumberOrdering.questionCounter][k] +
				"</div>"
			);
			$(innerDiv).droppable({
				drop: NumberOrdering.Handledrop,
				dragover: NumberOrdering.allowDrop
			});
			$(div).data("Answer",NumberOrdering.questionArr[NumberOrdering.questionCounter][k]);
			if(k < NumberOrdering.numbercount) {
				spanElement = $(
					'<p id="space' +
					k +
					'" class="text-center noPadding spaces" >' +
					tempArray[k] +
					"</p>"
				);
				$(div).draggable({
					cursor: "move",
					snap: "#div" + k,
					revert: "invalid",
					zIndex: 1,
					containment: "#NumbersDiv",
					scroll: false,
					start: function(event,ui) {
						document.getElementById('playSound').pause();
					},
				});
				$(div).append(spanElement);
				k++;
			}
			$(innerDiv).append(div);
			$(outerDiv).append(innerDiv);
		}
		$("#NumbersDiv").append(outerDiv);
	}
	$(".align6InLine").css({
    /*'border':'3px solid black',*/ color: "transparent",
		"background-image": "url(" + Utils.Path + "images/yellow-Leaf.png)",
		"background-repeat": "no-repeat",
		"background-size": "95% 100%"
	});
	//NumberOrdering.checkData();
};

NumberOrdering.allowDrop = function(event) {
	event.preventDefault();
};

NumberOrdering.checkData = function() {
	for(var i = 0; i < NumberOrdering.arrOfNumbers.length; i++) {
		if(
			$("#innerDiv" + i).data("Answer") ==
			$("#innerDiv" + i)
				.children("div")
				.children("p")
				.text()
		) {
			console.log("Match Found");
			NumberOrdering.answerCounter++;
			$("#space" + i)
				.parent()
				.css({
					"background-image": "url(" + Utils.Path + "images/green-Leaf.png)"
				});
		}
	}
};

/* NumberOrdering.playSoundForEachWord = function (element) {
	document.getElementById("playSound").src = $(element).data("sound");
	document.getElementById("playSound").play();
}; */

//function which executes on skip button
NumberOrdering.skipQuestion = function() {
	clearTimeout(NumberOrdering.nextQuestionTimer);
	//NumberOrdering.questionCounter++;
	NumberOrdering.clearAllAndShowNext();
}
//function which show skipped questions
NumberOrdering.showSkippedQuestions = function() {
	clearTimeout(NumberOrdering.noResponseTimer);
	NumberOrdering.questionCounter = 0;
	NumberOrdering.Counter = 0;
	$("#responseBoxDiv").hide();
	NumberOrdering.startGame();
}
//function which clears the leafs and next numbers are added
NumberOrdering.clearAllAndShowNext = function() {
	document.getElementById('playSound').pause();
	clearInterval(NumberOrdering.noResponseTimer);
	if(NumberOrdering.gameOpened == false)
		NumberOrdering.questionCounter++;
	else {
		if(NumberOrdering.answerCounter != NumberOrdering.numbercount) {
			scoredMarks = 0;
			console.log(resId,questionId,scoredMarks,totalMarks,1,startTime,label);
			if(Utils.mobileDeviceFlag)
				Android.addScore(
					resId,
					questionId,
					scoredMarks,
					totalMarks,
					1,
					startTime,
					label
				);
			NumberOrdering.questionArr.splice(NumberOrdering.questionCounter,1);
			NumberOrdering.questionOrderArr.splice(NumberOrdering.questionCounter,1);
		}
	}
	if(NumberOrdering.questionArr.length == 0)
		NumberOrdering.showEndPage();
	if(NumberOrdering.questionCounter == NumberOrdering.questionArr.length) {
		$("#responseBoxDiv").show();
	}
	else {
		$("#FinalOk").hide();
		$("#Next").removeClass("blink_me");

		if(NumberOrdering.nextQuestionTimer) {
			NumberOrdering.nextQuestionTimer = null;
			clearTimeout(NumberOrdering.nextQuestionTimer);
		}
		$("#NumbersDiv,.spaces,.align6InLine").empty();
		$("#Next").hide();
		NumberOrdering.startGame();
	}
};
//function which executes on drop
NumberOrdering.Handledrop = function(event,ui) {
	var destiDiv,sourceDiv;
	NumberOrdering.gameOpened = true;
	document.getElementById('playSound').play();
	sourceChild = ui.draggable;
	sourceDiv = $(ui.draggable).parent();
	destiDiv = $(this);
	destChild = $(this).children();
	$(sourceChild).css({
		top: "0px",
		left: "0px"
	});

	if(NumberOrdering.noResponseTimer) {
		clearInterval(NumberOrdering.noResponseTimer);
		NumberOrdering.noResponseTimer = null;
		NumberOrdering.seconds = 0;
	}
	NumberOrdering.startTimer();

	document.getElementById('playSound').src = Utils.Path + "sounds/ting.mp3";
	document.getElementById('playSound').play();
	$(sourceChild).appendTo(destiDiv);
	$(destChild).appendTo(sourceDiv);


	/* if(sourceDiv !== destiDiv) {
		var j = 0;
		for(var i = 0; i < NumberOrdering.arrOfNumbers.length; i++) {
			if(
				$("#innerDiv" + i).data("Answer") ==
				$("#innerDiv" + i)
					.children("div")
					.children("p")
					.text()
			) {
				j++;
				$("#innerDiv" + i)
					.children("div")
					.css({
						"background-image": "url(" + Utils.Path + "images/green-Leaf.png)"
					});
			} else {
				$("#innerDiv" + i)
					.children("div")
					.css({
						"background-image": "url(" + Utils.Path + "images/yellow-Leaf.png)"
					});
			}
		}
		NumberOrdering.answerCounter = j;
	}
	if(NumberOrdering.answerCounter == NumberOrdering.numbercount) {
		scoredMarks = 10;
		NumberOrdering.correctCounter++;
		$(".align6InLine").css({"pointer-events": "none"});
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(
				resId,
				questionId,
				scoredMarks,
				totalMarks,
				1,
				startTime
			);
		
		scoredMarks = 0;
		document.getElementById("playSound").src =
			Utils.Path + "sounds/welldone.mp3";
		document.getElementById("playSound").play();
		$("#FinalOk").show();
		$("#Next").css("visibility","hidden");
		NumberOrdering.questionArr.splice(NumberOrdering.questionCounter,1);
		NumberOrdering.questionOrderArr.splice(NumberOrdering.questionCounter,1);
		if(NumberOrdering.questionArr.length == 0) {
			setTimeout(function() {
				clearTimeout(NumberOrdering.nextQuestionTimer);
				NumberOrdering.showEndPage();
				$("#Next").css("visibility","hidden");
			},1000);
		} else {
			if(NumberOrdering.nextQuestionTimer) {
				clearTimeout(NumberOrdering.nextQuestionTimer);
				NumberOrdering.nextQuestionTimer = null;
			}
			NumberOrdering.nextQuestionTimer = setTimeout(function() {
				$("#FinalOk").hide();
				$("#Next").css("visibility","visible");
				NumberOrdering.clearAllAndShowNext();
			},1000)
		}
	} */
};
NumberOrdering.checkAnswer = function(){
	NumberOrdering.gameOpened = true;
		var j = 0;
		for(var i = 0; i < NumberOrdering.arrOfNumbers.length; i++) {
			if(
				$("#innerDiv" + i).data("Answer") ==
				$("#innerDiv" + i)
					.children("div")
					.children("p")
					.text()
			) {
				j++;
				$("#innerDiv" + i)
					.children("div")
					.css({
						"background-image": "url(" + Utils.Path + "images/green-Leaf.png)"
					});
			} else {
				$("#innerDiv" + i)
					.children("div")
					.css({
						"background-image": "url(" + Utils.Path + "images/yellow-Leaf.png)"
					});
			}
		}
		NumberOrdering.answerCounter = j;
	if(NumberOrdering.answerCounter == NumberOrdering.numbercount) {
		scoredMarks = 10;
		NumberOrdering.correctCounter++;
		$(".align6InLine ").css({"pointer-events": "none"});
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime,label);
		if(Utils.mobileDeviceFlag)
			Android.addScore(
				resId,
				questionId,
				scoredMarks,
				totalMarks,
				1,
				startTime,
				label
			);
		scoredMarks = 0;
		document.getElementById("playSound").src =
			Utils.Path + "sounds/welldone.mp3";
		document.getElementById("playSound").play();
		$("#FinalOk").show();
		$("#Next").css("visibility","hidden");
		NumberOrdering.questionArr.splice(NumberOrdering.questionCounter,1);
		NumberOrdering.questionOrderArr.splice(NumberOrdering.questionCounter,1);
		if(NumberOrdering.questionArr.length == 0) {
			setTimeout(function() {
				clearTimeout(NumberOrdering.nextQuestionTimer);
				NumberOrdering.showEndPage();
				$("#Next").css("visibility","hidden");
			},1000);
		} else {
			if(NumberOrdering.nextQuestionTimer) {
				clearTimeout(NumberOrdering.nextQuestionTimer);
				NumberOrdering.nextQuestionTimer = null;
			}
			NumberOrdering.nextQuestionTimer = setTimeout(function() {
				$("#FinalOk").hide();
				$("#Next").css("visibility","visible");
				NumberOrdering.clearAllAndShowNext();
			},1000)
		}
	} else {
		$(".align6InLine ").css({"pointer-events": "none"});
		$("#Next").css("visibility","hidden");
		if(NumberOrdering.nextQuestionTimer) {
			clearTimeout(NumberOrdering.nextQuestionTimer);
			NumberOrdering.nextQuestionTimer = null;
		}
		document.getElementById("playSound").src =	Utils.Path + "sounds/BuzzerWrong.mp3";
		document.getElementById("playSound").play();
		NumberOrdering.nextQuestionTimer = setTimeout(function() {
			$("#Next").css("visibility","visible");
			NumberOrdering.clearAllAndShowNext();
		},1000);
	}
}
//function which creates acknowledgement layout
NumberOrdering.AcknowledgementPage = function() {
	var i = 0,
		div;
	console.log(Object.keys(NumberOrdering.AcknowledgementPageData).length);
	for(
		i = 0;
		i < Object.keys(NumberOrdering.AcknowledgementPageData).length;
		i++
	) {
		div = document.createElement("div");
		div.className =
			"fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML =
			Object.keys(NumberOrdering.AcknowledgementPageData)[i] +
			" : " +
			Object.values(NumberOrdering.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div = document.createElement("div");
	div.className =
		"fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML = NumberOrdering.hardCodedData["createdOn"];
	acknowledgementDiv.appendChild(div);
};
//function which executes on endpage
NumberOrdering.showEndPage = function() {
	clearTimeout(NumberOrdering.noResponseTimer);
	document.getElementById("playSound").pause();
	clearTimeout(NumberOrdering.nextQuestionTimer);
	NumberOrdering.giveStars();
	NumberOrdering.noOfQuestions = 0;
	NumberOrdering.replay = true;
	$("#gamePage").hide();
	$("#endPage").show();
};
//function which plays the NoResponse audio
NumberOrdering.startTimer = function() {
	if(NumberOrdering.noResponseTimer) {
		clearInterval(NumberOrdering.noResponseTimer);
		NumberOrdering.noResponseTimer = null;
		NumberOrdering.seconds = 0;
	}
	NumberOrdering.noResponseTimer = setInterval(function() {
		NumberOrdering.seconds++;
		if(NumberOrdering.seconds >= 7) {
			document.getElementById("playSound").src = Utils.Path + "sounds/instructions/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(NumberOrdering.noResponseTimer)
			if(NumberOrdering.timeOut) {
				clearTimeout(NumberOrdering.timeOut);
				NumberOrdering.timeOut = null;
			}
			NumberOrdering.timeOut = setTimeout(function() {
				NumberOrdering.seconds = 0;
				NumberOrdering.startTimer();
			},2000);
		}
	},1000);
};
//function which creates star divs
NumberOrdering.createStars = function() {
	var newImage,newDiv,i,numberOfStars = 5;
	for(i = 1; i <= 5; i++) {
		newDiv = document.createElement("div");
		newDiv.setAttribute("id","starDiv" + i);
		newDiv.setAttribute("class","noPadding  col-xs-2 col-md-2 col-lg-2 col-sm-2");
		$("#starsDiv").append(newDiv);

		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/star1.png");
		$(newDiv).append(newImage);
	}
}
//function which calculates stars
NumberOrdering.giveStars = function() {
	var numberOfStars = 0,temp;
	NumberOrdering.total_No_of_Questions = 5;
	ans = NumberOrdering.total_No_of_Questions / 5;
	temp = NumberOrdering.correctCounter / ans;
	numberOfStars = Math.floor(temp);
	temp = Math.round(temp);
	for(let i = 1; i <= Math.floor(numberOfStars); i++)
		document.getElementById("starImg" + i).setAttribute("src",Utils.Path + "images/star2.png");
	if(numberOfStars != 0) {
		document.getElementById("playSound").src = Utils.Path + "sounds/instructions/" + "star" + numberOfStars + ".mp3";
		document.getElementById("playSound").play();
	}
	console.log(NumberOrdering.correctCounter,5,"2");
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(NumberOrdering.correctCounter,5,"2");
};
//function which executes on next game button click
NumberOrdering.nextGame = function() {
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
};
//function which executes on home btn
NumberOrdering.callHome = function() {
	console.log(resId,questionId,scoredMarks,totalMarks,1,startTime,label);
	if(Utils.mobileDeviceFlag)
		Android.addScore(
			resId,
			questionId,
			scoredMarks,
			totalMarks,
			1,
			startTime,
			label
		);
	location.reload(true);
};

NumberOrdering.getDuration=function(src){
	var duration = 0;
		if (NumberOrdering.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			NumberOrdering.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			NumberOrdering.playNextSound(duration);
		});
		$('#playSound').prop('src', src);
	}
}

NumberOrdering.playNextSound = function (duration)//plz ans ques function call
{
	document.getElementById('playSound').play();
	if (NumberOrdering.instructionTimer) {
	clearTimeout(NumberOrdering.instructionTimer);
	NumberOrdering.instructionTimer = null;
	}
	NumberOrdering.instructionTimer = setTimeout(function () {
	document.getElementById('playSound').pause();
	NumberOrdering.startTimer();
	}, duration * 1000);
}

