//16th may 2019
var Number123={};
var Utils={};
Utils.Path='';
var quesId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0,level=1,label=0;
var wordName='',totalNos=0,wordType='alphabet';
Utils.mobileDeviceFlag=false;

Number123.numberArr=[];
Number123.nextQueTimer=0;
Number123.questionCnt=0;
Number123.level=0;
Number123.gamePlayedFlag=false;
Number123.noResponseTimer=0;
Number123.correctCnt=0;
Number123.seconds=0;
Number123.timeOut=0;
Number123.question=[];
$(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()
	{
		$(document).prop('title',Number123.hardCodedData['gameTitle']);
		document.getElementById('gamePage').style.display='none';
		Number123.setImages();
		Number123.createStars();
		//commaSeperateNum();
		/* if(Number123.hardCodedData['languageFont']!=null)
			setFontFamilyForLang("fonts/"+Number123.hardCodedData['languageFont']);	 */
	},200);
});

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");            
}

//set all images
Number123.setImages=function()
{
	$('#home').prop("src",Utils.Path+"images/home.png");
	$('#logo').prop("src",Utils.Path+"images/logo.png");
	$('#playImage').prop("src",Utils.Path+"images/Play.png");
	$('#sound').prop("src",Utils.Path+"images/Sound.png");
	$('#nextGame').prop("src",Utils.Path+"images/Next.png");
	$('#nextQue').prop("src",Utils.Path+"images/skip.png");
	document.body.style.backgroundImage="url("+Utils.Path+"images/BG.png"+")";
	//$('#playAgain').prop("src",Utils.Path+"images/playAgain.png");
	//$('#credit').prop("src",Utils.Path+"images/credits.png");
}  

Number123.playGame=function()
{
	document.getElementById('coverPage').style.display='none';	
	document.getElementById('gamePage').style.display='block';	
	//document.getElementById('homeDiv').style.visibility='visible';
	document.body.style.backgroundImage="";
	document.getElementById('logoDiv').style.backgroundImage="url("+Utils.Path+"images/skyNwall.png"+")";
	document.getElementById('middleConatiner').style.backgroundImage="url("+Utils.Path+"images/background.png"+")";
	document.getElementById('middle').style.backgroundImage="url("+Utils.Path+"images/background.png"+")";
	document.getElementById('footer').style.backgroundImage="url("+Utils.Path+"images/bottomWall.png"+")";
	document.getElementById('widget').style.backgroundImage="url("+Utils.Path+"images/bottomWall.png"+")";
	/* getUniqueValArr(Number123.data,Number123.questionArr,5);
	console.log(Number123.questionArr); */
	Number123.createOptions();
	//Number123.uniqueValues(Number123.questionArr,5);
	Number123.playSound();
	Number123.levelFunction();
	Number123.showQuestion();
}
Number123.uniqueValues=function(start,end,outputArr,length)
{
	for(var i=0;i<length;i++)
	{
		var random=Math.floor(Math.random() * (end - start + 1) ) + start;
		
		if(outputArr.includes(random))
			i--;
		else
		{
			var number=Number123.convertNumberToStringWithComma(random);
			outputArr.push(number);
			continue;
		}
	}
	console.log(outputArr);
}
Number123.levelFunction=function()
{
	Number123.level=0;//Math.floor(Math.random());
	
	if(Number123.level==1)
	{
		Number123.uniqueValues(1000,100000,Number123.numberArr,5);
		Number123.createQueL1();	
	}
	else
	{ 
		Number123.uniqueValues(10,1000,Number123.numberArr,5);
		Number123.createQueL1();
	}
}

Number123.convertNumberToStringWithComma = function (randomNumber) {
    var numberWithComma = 0;
    var nolen = randomNumber.toString().length;
    if (nolen == 5 || nolen == 4)
        numberWithComma = randomNumber.toString().substring(0, (nolen - 3)) + "," + randomNumber.toString().substring((nolen - 3));
	else
		numberWithComma=randomNumber;
    return numberWithComma;
}

 Number123.createOptions=function()
{
	var div,divBar,span;
	//var parentDiv=document.getElementById('radioButtons');
	for(var i=0;i<4;i++)
	{
		div=document.createElement('div');
		$(div).prop('class','text-center options col-xs-3 col-sm-3 col-lg-3 col-md-3 nopadding');
		
		$(div).prop('id','option'+(i+1));
		$('#div'+(i+1)).append(div);
		
		span=document.createElement('span');
		$(span).prop('id','span'+(i+1));
		$(span).prop('class','spanElements');
		
		div.setAttribute('onclick','Number123.checkAnswer(this.id)');
		$(div).append(span);
	//	$(div).css({'background-image':'url(images/truck'+(i+1)+'.png)'});
		
		divBar=document.createElement('div');
		$(divBar).prop('id','bar'+(i+1));
		$(divBar).prop('class','bars');
		$('#div'+(i+1)).append(divBar);
		$(divBar).css({'background-image':'url(images/stopbar.png)'});
	}
}

Number123.createQueL1=function()
{
	for(var i=0;i<5;i++)
	{
		var questionObj={};
		questionObj['number']=Number123.numberArr[i];
		var string='';
		var number=Number123.numberArr[i].toString();
		if(number.length>2)
		{
			var firstNo=parseInt(number[0]);
			var remaining=eval(number.replace(number[0],''));
			if(remaining!=0)
				var questionTxt=Number123.jsonData[firstNo]+Number123.data[0]+Number123.jsonData[remaining];
			else
				var questionTxt=Number123.jsonData[firstNo]+Number123.data[0];
		}
		else
			var questionTxt=Number123.jsonData[number];
		
		questionObj['queTxt']=questionTxt;
		if(number.length==2)
			var optn=Number123.changeOptions(i,1,9);
		else
			var optn=Number123.changeOptions(i,11,99);
		
		questionObj['optionArr']=optn;
		Number123.question.push(questionObj);
	}
	//console.log(Number123.question);
}

Number123.createQueL2=function()
{
	for(var i=0;i<5;i++)
	{
		var questionObj={};
		questionObj['number']=Number123.numberArr[i];
		var number=Number123.numberArr[Number123.questionCnt];
		var stringSplit=number.split(',');
		var num=eval(stringSplit[1]).toString();
		if(num.length==3)
		{
			if(num[1]==0 && num[2]==0)
				var questionTxt=Number123.jsonData[stringSplit[0]]+Number123.data[1]+Number123.jsonData[stringSplit[1][0]]+Number123.data[0];
			else
			{
				var evalStr=eval(stringSplit[1].substring(1)).toString();
				var questionTxt=Number123.jsonData[stringSplit[0]]+Number123.data[1]+Number123.jsonData[stringSplit[1][0]]+Number123.data[0]+Number123.jsonData[evalStr];
			}
		}
		else if(num.length==2)
		{
			var evalStr=eval(stringSplit[1].substring(1)).toString();
			var questionTxt=Number123.jsonData[stringSplit[0]]+Number123.data[1]+Number123.jsonData[evalStr];
		}
		else if(num.length==1)
			var questionTxt=Number123.jsonData[stringSplit[0]]+Number123.data[1]+Number123.jsonData[num];
		else
			var questionTxt=Number123.jsonData[stringSplit[0]]+Number123.data[1];
			
		questionObj['queTxt']=questionTxt;
		var optn=Number123.changeOptionsL2(i,100,999);
		
		questionObj['optionArr']=optn;
		Number123.question.push(questionObj);
	}
}
Number123.changeOptions=function(i,start,end)
{
	var optionArr=[];
	var startingNo=Number123.numberArr[i].toString();
	optionArr.push(Number123.numberArr[i]);
	if(startingNo.length==3)
	{
		start=eval(startingNo[0]+"00");
		end=eval(startingNo[0]+"99");
	}
	else if(startingNo.length==2)
	{
		start=eval(startingNo[0]+0);
		end=eval(startingNo[0]+9);
	}
	Number123.uniqueValues(start,end,optionArr,3);
	shuffle(optionArr);
	return(optionArr);
}
Number123.changeOptionsL2=function(i,start,end)
{
	var optionArr=[];
	var startingNo=Number123.numberArr[i].split(',');
	optionArr.push(parseInt(startingNo[1]));
	if(startingNo[1][0]==0)
	{
		start=100;
		end=999;
	}
	else
	{
		start=eval(startingNo[1][0]+"00");
		end=eval(startingNo[1][0]+"99");
	}
	Number123.uniqueValues(start,end,optionArr,3);
	shuffle(optionArr);
	return(optionArr);
}

function shuffle(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;
	}
	return array;
}

Number123.showQuestion=function()
{
	var d=new Date();
	Number123.startTimer();
	scoredMarks=0;
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	$('#question').data('data',Number123.question[Number123.questionCnt]['number']);
	$('#question').text(Number123.question[Number123.questionCnt]['queTxt']);
	label=Number123.question[Number123.questionCnt]['queTxt'];
	if(Number123.level==0)
	{
		for(var i=0;i<Number123.question[Number123.questionCnt]['optionArr'].length;i++)
		{
			$('#option'+(i+1)).css({'background-image':'url(images/truck'+(i+1)+'.png)'});
			$("#option"+(i+1)).prop('value',Number123.question[Number123.questionCnt]['optionArr'][i]);
			$("#span"+(i+1)).text(Number123.question[Number123.questionCnt]['optionArr'][i]);
		} 
	}
	else{
		var startingNo=Number123.question[Number123.questionCnt]['number'].split(',');
		for(var i=0;i<Number123.question[Number123.questionCnt]['optionArr'].length;i++)
		{
			$('#option'+(i+1)).css({'background-image':'url(images/truck'+(i+1)+'.png)'});
			$("#option"+(i+1)).prop('value',Number123.question[Number123.questionCnt]['optionArr'][i]);
			if(Number123.question[Number123.questionCnt]['optionArr'][i].toString().length==2)
				$("#span"+(i+1)).text(startingNo[0]+','+'0'+Number123.question[Number123.questionCnt]['optionArr'][i]);
			else if(Number123.question[Number123.questionCnt]['optionArr'][i].toString().length==1)
				$("#span"+(i+1)).text(startingNo[0]+','+'00'+Number123.question[Number123.questionCnt]['optionArr'][i]);
			else
				$("#span"+(i+1)).text(startingNo[0]+','+Number123.question[Number123.questionCnt]['optionArr'][i]);
		} 
	}
}

Number123.checkAnswer=function(eleId)
{
	document.getElementById('playSound').pause();
	clearInterval(Number123.noResponseTimer);
	clearTimeout(Number123.timeOut);
	Number123.timeOut=null;
	document.getElementById('playSound').pause();
	Number123.gamePlayedFlag=true;
	Number123.attempCnt++;
	$('.options').css({'pointer-events':'none'});
	
	if($('#'+eleId).text()==Number123.question[Number123.questionCnt]['number'])
	{
		$('.options').css({'pointer-events':'none'});
		$('#soundBtn').css({'pointer-events':'none'});
		$('#playSound').prop('src',Utils.Path+'sound/CorrectSound.mp3');
		Number123.moveCar(eleId,100);
		Number123.correctCnt++;
		scoredMarks=10;
	}
	else
	{
		scoredMarks=0;
		$('#soundBtn').css({'pointer-events':'none'});
		$('#playSound').prop('src',Utils.Path+'sound/wrong.mp3');
		$('.options').css({'pointer-events':'none'});	
		Number123.moveCar(eleId,55);
	}
	document.getElementById('playSound').play();
	Number123.nextQuestionTimeout=setTimeout(function()
	{
		Number123.nextQue();
	},3500);
}

Number123.moveCar=function(eleId,value)
{
	Number123.vehichlepos=0;
	Number123.moveCarInterval=setInterval(function()
	{
		Number123.vehichlepos=Number123.vehichlepos+0.2;
		document.getElementById(eleId).style.left=Number123.vehichlepos +'%';
		if(Number123.vehichlepos > value)
		{
			clearInterval(Number123.moveCarInterval);
			if(value==55)
			{
				$('#'+eleId).css({'background-image':'url(images/'+eleId+'.png'+')'})
				//$('.options').not('#'+eleId).css({'pointer-events':'auto'});
			}
			Number123.vehichlepos=0;
		}
	},3);
}
Number123.nextQue=function()
{
	
	if(Number123.gamePlayedFlag==false)
		Number123.questionCnt++;
	else
    {
        Number123.calculateScore();
        Number123.question.splice(Number123.questionCnt,1);
    }
	
	if(Number123.question.length==0)
		Number123.showLastPage();
	else if(Number123.questionCnt>=Number123.question.length && Number123.question.length!=0)
		Number123.showPopup();
	else	
	{
		Number123.resetVariables();
		Number123.showQuestion();
	}
}

Number123.calculateScore=function()
{
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,level,startTime,label);
}


Number123.playSound=function()
{
	document.getElementById('playSound').pause();
	clearInterval(Number123.noResponseTimer);
	clearTimeout(Number123.timeOut);
	Number123.timeOut=null;
	$('#playSound').prop('src',Utils.Path+'sound/Number123_instruction.mp3');
	document.getElementById('playSound').play();
}

Number123.resetVariables=function()
{
	document.getElementById('playSound').pause();
	$('#question').removeClass('gameOver');
	$('#soundBtn').css({'pointer-events':'auto'});
	$('.options').css({'left':0});
	Number123.attempCnt=0;
	clearInterval(Number123.moveCarInterval);
	Number123.moveCarInterval=null;
	clearTimeout(Number123.nextQuestionTimeout);
	Number123.nextQuestionTimeout=null;
	$('.options').css({'pointer-events':'auto'});
	document.getElementById('playSound').pause();
	clearInterval(Number123.noResponseTimer);
	clearTimeout(Number123.timeOut);
	Number123.timeOut=null;
	Number123.gamePlayedFlag=false;
	//$('#question').text('');
}

Number123.showSkippedQuestions=function()
{
	$('#responseBoxDiv').hide();
	Number123.questionCnt=0;
	Number123.resetVariables();
    Number123.showQuestion();
}
Number123.showLastPage=function()
{
	$('#responseBoxDiv').hide();
	//$("body").css("background-image", "url(" + Utils.Path + 'images/background.jpg' + ")");
	Number123.giveStars();
	document.getElementById('playSound').pause();
	gameOver.innerHTML=Number123.hardCodedData.gameOver;
   $('#question').css('visibility','hidden');
    $('#gamePage').hide();
	$('#endpage').show();
	clearInterval(Number123.noResponseTimer);
	clearTimeout(Number123.timeOut);
	document.getElementById('nextDiv').classList.add('blink_me');
	if(Number123.correctCnt>0)
	{
		document.getElementById('playSound').src="sound/instruction/star"+Number123.correctCnt+".mp3";
		document.getElementById('playSound').play();
	}
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(Number123.correctCnt,Number123.totalQue,"6");
}
Number123.showPopup=function()
{
	document.getElementById('playSound').pause();
	clearInterval(Number123.noResponseTimer);
	clearTimeout(Number123.timeOut);
	Number123.timeOut=null;
	$('#responseBoxDiv').show();
	$('#questionMsg').text(Number123.modalData.responseMsg);
	$('#Yes').text(Number123.modalData.yes);
	$('#No').text(Number123.modalData.no);
}
Number123.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);
	}
};

Number123.giveStars=function()
{
	var fractionVar,i,numberOfStars=Number123.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");
};

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

Number123.startTimer=function()
{
	if(Number123.noResponseTimer)
	{
        clearInterval(Number123.noResponseTimer);
        Number123.noResponseTimer=null;
        Number123.seconds=0;
	}	
	Number123.noResponseTimer=setInterval(function() 
	{
		Number123.seconds++;
		if(Number123.seconds>=5)
		{
			document.getElementById("playSound").src=Utils.Path+"sound/instruction/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(Number123.noResponseTimer);
			Number123.timeOut=setTimeout(function()
			{
				Number123.seconds=0;
				Number123.startTimer();
			},2000);
		}
	},1000);
}