var Abacus = {}, Utils = {};
Utils.Path = '';
var Language, audioCounter = 0, globalCounter = 1, timerForFunCall_CountBalls1, timerForFunCall_CountBalls2, imageChangetimer, startTime, firstTimeAnsWrong = false, skipedCnt = 0, noOfTimeQuestionAnswered = 0;
Abacus.alreadyShownObject = [], levelNumber = 1, scoredMarks = 0, totalMarks = 10, questionId = 0;
Utils.mobileDeviceFlag = false;
Abacus.attemptFlag = false;
$(document).ready(function () {
	// check whether it is Tablet or Desktop
	$("#coverPage,#gamePage,#endPage").hide();
	$(".se-pre-con").show();
	if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag = true;
	/* if (Utils.mobileDeviceFlag)
		Utils.Path = Android.getMediaPath("NumberKas"); */

	setTimeout(function () {
		Language = "Hindi";
		//		console.log(Language);
		$(".homeImg").css("visibility", "hidden");
		//setFontFamilyForLang(langWiseJSON[Language].font);
		Abacus.setImagesAndLabels();
		Abacus.registerEventListener();
		$(".se-pre-con").fadeOut("slow");
	}, 100);
});

// set font family to body for selected lang. if required.
setFontFamilyForLang = function (fontFilePath) {
	var newStyle = "<style>" +
		"@font-face {  " +
		"font-family: 'CustomFontFamily';" +
		"src: url('" + fontFilePath + "') format('truetype');" +
		"}  </style>";
	$("head").append(newStyle);
	$("body").css("font-family", "CustomFontFamily");
}

//Select JSON data for lang. & set all images
Abacus.setImagesAndLabels = function () {
	audioTag = new Audio();
	audioTag1 = new Audio();
	// select data from JSON as per selected lang.
	Abacus.numberTextJSON = langWiseJSON[Language].numberTextJSON;
	Abacus.numberSoundsJSON = langWiseJSON[Language].numberSoundsJSON;
	$("body").css("background-image", "url('" + Utils.Path + langWiseJSON[Language].coverPage + "')");

	$('#levelPage,#gamePage').hide();
	$("#levelOneImage").prop("src", Utils.Path + "img/level1.png");
	$("#levelTwoImage").prop("src", Utils.Path + "img/level2.png");
	$("#levelThreeImage").prop("src", Utils.Path + "img/level3.png");
	$(".homeIcon,.homeImg").prop("src", Utils.Path + "img/home.png");
	$(".playIcon").prop("src", Utils.Path + "img/play.png");
	$(".nextIcon").prop("src", Utils.Path + "img/next.png");
	$(".prathamlogo").prop("src", Utils.Path + "img/prathamlogo.png");
	$(".ballFor1").prop("src", Utils.Path + "img/ballFor1.png");
	$(".ballFor10").prop("src", Utils.Path + "img/ballFor10.png");
	$(".ballFor100").prop("src", Utils.Path + "img/ballFor100.png");
	$(".ballFor1000").prop("src", Utils.Path + "img/ballFor1000.png");
	$(".kakaji").prop("src", Utils.Path + "img/pointing.png");
	$(".soundIcon").prop("src", Utils.Path + "img/Sound.png");
	$("#replayImage").prop("src", Utils.Path + "img/Replay.png");
	$("#coverPage").show();
}

// register all on click event listener
Abacus.registerEventListener = function () {
	$("#levelOneImage").on("click", function () { Abacus.level = 1; Abacus.createAbacusTemplateForRange(); });
	$("#levelTwoImage").on("click", function () { Abacus.level = 2; Abacus.createAbacusTemplateForRange(); });
	$("#levelThreeImage").on("click", function () { Abacus.level = 3; Abacus.createAbacusTemplateForRange(); });
	$(".nextIcon").on("click", function () {
		$(".nextIcon").addClass("animated pulse");
		setTimeout(function () { $(".nextIcon").removeClass("animated pulse"); }, 700);
		Abacus.nextQuestion();
	});
	$(".homeIcon,.playIcon").on("click", Abacus.showLevelPage);
}

//when click on Play or Home ,display level page
Abacus.showLevelPage = function () {
	skipedCnt = 0;
	Abacus.skipFlag = true;
	if (Abacus.attemptFlag) {
		scoredMarks = 0;
		Abacus.attemptFlag = false;
		Abacus.calculateScore();
	}
	document.getElementById('playSound').pause();
	clearTimeout(Abacus.instructionTimer);
	clearTimeout(timerForFunCall_CountBalls1);
	clearTimeout(timerForFunCall_CountBalls2);
	clearTimeout(Abacus.nextQ);
	noOfTimeQuestionAnswered = 0;
	Abacus.alreadyShownObject = [];
	clearInterval(Abacus.setHighlighting);
	//$("#AbacusGameMainDiv").css("background-image", "url('" + Utils.Path + "img/BodyBG.jpg')");
	$("body").css("background-image", "url('" + Utils.Path + "img/BodyBG.jpg')");
	$('#levelPage').show();
	$("#coverPage,#gamePage").hide();
	$('#abacusPad').empty();
	$(".homeImg").css("visibility", "visible");
	audioTag.pause();
}

// create template with numbers as headers & and attach respective number of balls images below Number
Abacus.createAbacusTemplateForRange = function (startNo, endNo) {
	if (Abacus.level == 1) {
		startNo = 1;
		endNo = 10;
	}
	else if (Abacus.level == 2) {
		startNo = 10;
		endNo = 100;
	}
	else {
		startNo = 100;
		endNo = 1000;
	}
	$(".homeImg").css("visibility", "hidden");
	var abacusTemplate = '', TotalNoOfColumn = 10, NumberOnColumn = startNo, copyNumber;
	Abacus.StartNoOfLevel = startNo;
	Abacus.EndNoOfLevel = endNo;
	for (var columnNo = 1; columnNo <= TotalNoOfColumn; columnNo++) {
		copyNumber = NumberOnColumn;
		copyNumber = Abacus.convertNumberToStringWithComma(copyNumber);
		abacusTemplate += '<div id=column' + columnNo + ' class="column col-lg-1 col-md-1 col-sm-1 col-xs-1" >' +
			'<div id=number' + columnNo + ' class="abacusNumber " data=' + NumberOnColumn + ' onclick="Abacus.checkAnswer(this,' + columnNo + ');">' + copyNumber + '</div>';
		for (var BallsRow = 1; (BallsRow <= columnNo && BallsRow <= 5); BallsRow++) {
			if (columnNo > 5 && (columnNo - BallsRow) >= 5)
				abacusTemplate += '<div class="ballsInColumn_Div row">' +
					'<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 Col1BallsDiv" style="padding:0px;">' +
					'<img class=" animated ballsInColumn ballNo' + BallsRow + '" src="' + Utils.Path + 'img/ballFor' + startNo + '.png"></div>' +
					'<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="padding:0px;">' +
					'<img class="animated ballsInColumn  ballNo' + (BallsRow + 5) + '" src="' + Utils.Path + 'img/ballFor' + startNo + '.png"></div>' +
					'</div>';
			else
				abacusTemplate += '<div class="ballsInColumn_Div row">' +
					'<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 Col1BallsDiv" style="padding:0px;">' +
					'<img class="animated ballsInColumn ballNo' + BallsRow + '" src="' + Utils.Path + 'img/ballFor' + startNo + '.png"></div>' +
					'</div>';
		}
		if (columnNo == 10)
			abacusTemplate += '<div class="row BallForRoundup">' +
				'<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="padding:0px;">' +
				'<img class="ballsInColumn " src="' + Utils.Path + 'img/ballFor' + (startNo * 10) + '.png"></div>' +
				'</div>';
		abacusTemplate += '</div>';
		NumberOnColumn += startNo;
	}
	$('#abacusPad').append(abacusTemplate);
	$('.column >.ballsInColumn_Div').hide();
	$('.column >.BallForRoundup').hide();
	$(".abacusNumber").css("background-image", "url('" + Utils.Path + "img/ButtonBGForBall" + startNo + ".png')");
	// set size of ball as per value of ball
	if (Abacus.StartNoOfLevel == 1)
		$(".ballsInColumn").addClass("BallFor1WidthInAbacusPad");
	if (Abacus.StartNoOfLevel == 10)
		$(".ballsInColumn").addClass("BallFor10WidthInAbacusPad");
	if (Abacus.StartNoOfLevel == 100)
		$(".ballsInColumn").addClass("BallFor100WidthInAbacusPad");
	$('#levelPage').hide();
	$('#gamePage').show();
	Abacus.selectRandomNumberFromRange();
	//Abacus.nextQuestion();
}

// select a random from the selected range , on which player has to click. 
Abacus.selectRandomNumberFromRange = function () {
	firstTimeAnsWrong = false;
	Abacus.skipFlag = true;
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	clearInterval(Abacus.setHighlighting);
	skipedCnt++;
	$(".soundIcon").css("pointer-events", "auto");
	document.getElementById('playSound').pause();

	clearInterval(Abacus.setHighlighting);
	clearTimeout(timerForFunCall_CountBalls1);
	clearTimeout(timerForFunCall_CountBalls2);
	clearTimeout(Abacus.nextQ);
	clearTimeout(imageChangetimer);
	clearTimeout(Abacus.instructionTimer);
	$('.ballsInColumn_Div,.BallForRoundup').hide();
	$(".kakaji").prop("src", Utils.Path + "img/pointing.png");
	$(".abacusNumber").css("pointer-events", "auto");
	//syntax : Math.floor(Math.random() * (max - min + 1)) + min
	var oneToTenDigit = Math.floor(Math.random() * (10 - 1 + 1)) + 1; // in range(1,9)
	while ($.inArray(oneToTenDigit, Abacus.alreadyShownObject) != -1)
		var oneToTenDigit = Math.floor(Math.random() * (10 - 1 + 1)) + 1; // in range(1,9)
	Abacus.alreadyShownObject.push(oneToTenDigit);
	var NewRandomNumber = oneToTenDigit * Abacus.StartNoOfLevel;
	// if current selected No. & previous No. is same ,then again select another randomNumber to avoid repeating  
	//	if(Abacus.randomNumber!=NewRandomNumber){
	Abacus.randomNumber = NewRandomNumber;
	$(".circleNumber").html(Abacus.numberTextJSON[Abacus.randomNumber]).addClass("blink_me");
	//	}
	//	else
	//		Abacus.nextQuestion();
	//	console.log(Abacus.randomNumber);
	//Abacus.readText();
	audioTag.pause();
	/* 	audioTag.src = Utils.Path + Abacus.numberSoundsJSON[Abacus.randomNumber];
		audioTag.play(); */
	Abacus.playInstruction();
	audioTag.onended = function () {
		audioTag.pause();
	}
	Abacus.highlightDivs();
}
Abacus.playInstruction = function () {
	/* document.getElementById('playSound').src = Utils.Path + Abacus.numberSoundsJSON[Abacus.randomNumber];
	document.getElementById('playSound').play(); */
	Abacus.soundFlag = true;
	/*audioTag.pause();
	if (Abacus.oneToTenDigit == 10 || Abacus.level == 2) {
		if (Abacus.level == 2) {
			var tempDigit = Abacus.oneToTenDigit * 10;
			getDuration(Utils.Path + Abacus.numberSoundsJSON[tempDigit]);
		}
		else
			getDuration(Utils.Path + Abacus.numberSoundsJSON[Abacus.oneToTenDigit]);
	
	}
	else */
	//document.getElementById('playSound').src = Utils.Path + langWiseJSON[Language].instruction;

	//document.getElementById('playSound').play();
	getDuration(Utils.Path + langWiseJSON[Language].instruction);
}
function getDuration(src, functionName) {			//gets duration of sound 
	var duration = 0;
	if (Abacus.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			Abacus.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			Abacus.playNextSound(duration);
		});
		$('#playSound').prop('src', src);
	}
}
Abacus.playNextSound = function (duration)								//function for instruction
{
	document.getElementById('playSound').play();
	if (Abacus.instructionTimer) {
		clearTimeout(Abacus.instructionTimer);
		Abacus.instructionTimer = null;
	}
	Abacus.instructionTimer = setTimeout(function () {
		document.getElementById('playSound').pause();
		document.getElementById('playSound').src = Utils.Path + Abacus.numberSoundsJSON[Abacus.randomNumber];
		document.getElementById('playSound').play();
		/* setTimeout(function () {
			if (Abacus.objPointerFlag) {
				Abacus.objPointerFlag = false;
				$(".pointerClass").css({ "pointer-events": "auto" });
			}
			$(".optionClass").css({ "pointer-events": "auto" });
		}, duration * 800); */
	}, duration * 1000);
}
Abacus.highlightDivs = function () {
	var cnt = 0;
	if (Abacus.setHighlighting) {
		clearInterval(Abacus.setHighlighting);
		Abacus.setHighlighting = null;
	}
	Abacus.setHighlighting = setInterval(function () {
		//	for (var i = 0; i < $("#abacusPad").children().length; i++) {

		$($("#abacusPad").children()[cnt]).addClass("blink_me");
		//	}
		if (Abacus.removeHighlighting) {
			clearTimeout(Abacus.removeHighlighting);
			Abacus.removeHighlighting = null;
		}
		Abacus.removeHighlighting = setTimeout(function () {
			$(".column").removeClass("blink_me");
			if (cnt == 9)
				sign = '-';
			else if (cnt == 0)
				sign = '+';
			cnt = eval(cnt + sign + '1');

		}, 500);
	}, 800);
}
//check ,whether asked No. & Preseed No. is same. if same Count all Balls In that Column one by one
Abacus.checkAnswer = function (element, pressedColumnNo) {

	Abacus.skipFlag = false;
	audioTag.pause();
	noOfTimeQuestionAnswered++;
	document.getElementById('playSound').pause();
	clearInterval(Abacus.setHighlighting);
	clearTimeout(timerForFunCall_CountBalls1);
	clearTimeout(timerForFunCall_CountBalls2);
	clearTimeout(imageChangetimer);
	clearTimeout(Abacus.instructionTimer);
	if (Abacus.randomNumber != document.getElementById(element.id).getAttribute('data')) {
		Abacus.attemptFlag = true;
		$(".kakaji").prop("src", Utils.Path + "img/Angry.png");
		audioTag.src = Utils.Path + "sounds/BuzzerWrong.mp3";
		audioTag.play();
		imageChangetimer = setTimeout(function () { $(".kakaji").prop("src", Utils.Path + "img/pointing.png"); }, 900);
		//if (!firstTimeAnsWrong) {
		scoredMarks = 0;
		/* 	console.log(Abacus.randomNumber, scoredMarks, totalMarks, Abacus.level, startTime);
			if (Utils.mobileDeviceFlag)
				Android.addScore(resId, Abacus.randomNumber, scoredMarks, totalMarks, Abacus.level, startTime);
			firstTimeAnsWrong = true;
		} */
	}
	else {
		if (!Abacus.attemptFlag)
			scoredMarks = 10;
		Abacus.calculateScore();
		/* console.log(Abacus.randomNumber, scoredMarks, totalMarks, Abacus.level, startTime);
		if (Utils.mobileDeviceFlag)
			Android.addScore(resId, Abacus.randomNumber, scoredMarks, totalMarks, Abacus.level, startTime); */
		clearTimeout(imageChangetimer);
		$(".abacusNumber,.soundIcon").css("pointer-events", "none");
		$(".circleNumber").removeClass("blink_me animated slideInDown");
		$(".kakaji").prop("src", Utils.Path + "img/Happy.png");

		audioTag.src = Utils.Path + langWiseJSON[Language].correctSound[Math.floor(Math.random() * langWiseJSON[Language].correctSound.length)];
		audioTag.play();
		$('.ballsInColumn_Div').hide();
		$('.BallForRoundup').hide();
		$('#column' + pressedColumnNo + '>.ballsInColumn_Div > div > .ballsInColumn').removeClass("zoomIn");
		$('#column' + pressedColumnNo + '>.ballsInColumn_Div').show();
		$('#column' + pressedColumnNo + '>.BallForRoundup').hide();
		Abacus.currentColumn = pressedColumnNo;
		globalCounter = 1;

		/*audioTag1.onended=function(){
     	 	audioTag1.pause();
			timerForFunCall_CountBalls1=setTimeout(function(){
								Abacus.CountBallsInColumn(Abacus.currentColumn);
		    },500);
		}*/
		timerForFunCall_CountBalls1 = setTimeout(function () {
			Abacus.CountBallsInColumn(Abacus.currentColumn);
		}, 1800);
	}

}

//count all the balls in column one by one ,with sound
Abacus.CountBallsInColumn = function (columnNo) {
	var ballsInColumn = $('#column' + columnNo + '>.ballsInColumn_Div > div > .ballsInColumn').length;
	if (ballsInColumn >= globalCounter) {
		audioTag.src = Utils.Path + Abacus.numberSoundsJSON[globalCounter * Abacus.StartNoOfLevel];
		audioTag.play();
		$('#column' + columnNo + '>.ballsInColumn_Div > div > .ballNo' + globalCounter).addClass("zoomIn");
		globalCounter++;
		timerForFunCall_CountBalls2 = setTimeout(function () {
			Abacus.CountBallsInColumn(columnNo);
		}, 1300);
	}
	else {
		globalCounter = 1;
		if (columnNo == 10) {
			$('#column' + columnNo + '>.ballsInColumn_Div').hide();
			$('#column' + columnNo + '>.BallForRoundup > div > img').css("width", "100%");
			$('#column' + columnNo + '>.BallForRoundup').show();
		}
		if (Abacus.nextQ) {
			clearTimeout(Abacus.nextQ);
			Abacus.nextQ = null;
		}
		Abacus.nextQ = setTimeout(function () {
			Abacus.nextQuestion();
		}, 800);
	}
	//Abacus.calculateScore();
}
Abacus.nextQuestion = function () {
	if (Abacus.attemptFlag) {
		scoredMarks = 0;
		Abacus.attemptFlag = false;
		Abacus.calculateScore();
	}
	if (Abacus.skipFlag) {
		scoredMarks = -1;
		Abacus.calculateScore();
	}
	noOfTimeQuestionAnswered = 0;
	clearInterval(Abacus.setHighlighting);
	clearTimeout(timerForFunCall_CountBalls1);
	clearTimeout(timerForFunCall_CountBalls2);
	clearTimeout(Abacus.nextQ);
	clearTimeout(imageChangetimer);
	clearTimeout(Abacus.instructionTimer);
	audioTag.pause();
	if (skipedCnt == 5) {
		document.getElementById('playSound').pause();
		$(".homeImg").css("visibility", "visible");
		$("#AbacusGameMainDiv").hide();
		$("#endPage").show();
		$("#gameOverDiv").text(Abacus.hardcoded);
	}
	else
		Abacus.selectRandomNumberFromRange();
}
/* Abacus.readText = function () {
	document.getElementById('playSound').src = Utils.Path + Abacus.numberSoundsJSON[Abacus.randomNumber];
	document.getElementById('playSound').play();
} */
Abacus.convertNumberToStringWithComma = function (randomNumber) {
	var numberWithComma = randomNumber;
	var nolen = randomNumber.toString().length;
	if (nolen == 4)
		numberWithComma = randomNumber.toString().substring(0, (nolen - 3)) + "," + randomNumber.toString().substring((nolen - 3));
	return numberWithComma;

}
Abacus.playAgain = function () {
	skipedCnt = 0;
	Abacus.alreadyShownObject = [];
	noOfTimeQuestionAnswered = 0;
	$("#AbacusGameMainDiv").show();
	$("#endPage").hide();
	$("#abacusPad").empty();
	Abacus.createAbacusTemplateForRange();

}
Abacus.calculateScore = function () {
	Abacus.attemptFlag = false;
	console.log(resId, questionId, scoredMarks, totalMarks, levelNumber, startTime, Abacus.numberTextJSON[Abacus.randomNumber]);
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, levelNumber, startTime, Abacus.numberTextJSON[Abacus.randomNumber]);

}
