//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.questionArr=[];
Number123.nextQueTimer=0;
Number123.questionCnt=0;
Number123.level=0;
Number123.gamePlayedFlag=false;
Number123.attempCnt=0;
Number123.levelFlag=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;
	setTimeout(function()
	{
		$(document).prop('title',Number123.hardCodedData['gameTitle']);
		document.getElementById('gamePage').style.display='none';
		document.getElementById('levelPage').style.display='none';
		Number123.setImages();
		/* 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");
	$('#nextQue').prop("src",Utils.Path+"images/Next.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");
	$('#level1').prop('src',Utils.Path+"images/level1.png");
	$('#level2').prop('src',Utils.Path+"images/level2.png");
	$('#levelDiv1').data('level',0);
	$('#levelDiv2').data('level',1);
}  

Number123.playGame=function()
{
	Number123.levelFlag=true;
	document.getElementById('coverPage').style.display='none';	
	document.getElementById('gamePage').style.display='none';	
	document.getElementById('levelPage').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('levelMiddle').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('footer1').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.setQuestion();
	//Number123.getQuestion();
}
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(id)
{
	Number123.questionArr=[];
	Number123.levelFlag=false;
	Number123.level=parseInt($('#'+id).data('level'));//Math.floor(Math.random());
	Number123.playSound();
	document.getElementById('gamePage').style.display='block';	
	document.getElementById('levelPage').style.display='none';
	if(Number123.level==1)
		Number123.uniqueValues(10000,99999,Number123.questionArr,5);
	else
		Number123.uniqueValues(1000,9999,Number123.questionArr,5);
	Number123.setlevel2Que();	
}

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);
		$(div).data('number',i+1);
		
		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.setlevel1Que=function()
{
	d=new Date();
	scoredMarks=0;
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	var string='';
	var number=Number123.questionArr[Number123.questionCnt].toString();
	$('#question').data('data',Number123.questionArr[Number123.questionCnt]);
	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];
	$('#question').text(questionTxt);
	label=questionTxt;
	if(number.length==2)
		Number123.changeOptions(1,9);
	else
		Number123.changeOptions(11,99);
}

Number123.changeOptions=function(start,end)
{
	var optionArr=[];
	var startingNo=Number123.questionArr[Number123.questionCnt].toString();
	optionArr.push(Number123.questionArr[Number123.questionCnt]);
	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);
	console.log(optionArr);
	shuffle(optionArr);
	for(var i=0;i<optionArr.length;i++)
	{
		$('#option'+(i+1)).css({'background-image':'url(images/truck'+(i+1)+'.png)'});
		$("#option"+(i+1)).prop('value',optionArr[i]);
		$("#span"+(i+1)).text(optionArr[i]);
	}
}

Number123.setlevel2Que=function()
{
	label=0;
	d=new Date();
	scoredMarks=0;
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	var number=Number123.questionArr[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]]+' सौ ';
		}
		else
		{
			var evalStr=eval(stringSplit[1].substring(1)).toString();
			var questionTxt=Number123.jsonData[stringSplit[0]]+Number123.data[1]+Number123.jsonData[stringSplit[1][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];
	
	$('#question').data('data',Number123.questionArr[Number123.questionCnt]);
	$('#question').text(questionTxt);
	label=questionTxt;
	Number123.changeOptionsL2(100,999);
}

Number123.changeOptionsL2=function(start,end)
{
	var optionArr=[];
	var startingNo=Number123.questionArr[Number123.questionCnt].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);
	console.log(optionArr);
	shuffle(optionArr);
	for(var i=0;i<optionArr.length;i++)
	{
		$('#option'+(i+1)).css({'background-image':'url(images/truck'+(i+1)+'.png)'});
		$("#option"+(i+1)).prop('value',optionArr[i]);
		if(optionArr[i].toString().length==2)
			$("#span"+(i+1)).text(startingNo[0]+','+'0'+optionArr[i]);
		else if(optionArr[i].toString().length==1)
			$("#span"+(i+1)).text(startingNo[0]+','+'00'+optionArr[i]);
		else
			$("#span"+(i+1)).text(startingNo[0]+','+optionArr[i]);
	}
}

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.checkAnswer=function(eleId)
{
	document.getElementById('playSound').pause();
	Number123.gamePlayedFlag=true;
	Number123.attempCnt++;
	$(eleId).css({'pointer-events':'none'});

	if($('#'+eleId).text()==Number123.questionArr[Number123.questionCnt])
	{
		$('.options').css({'pointer-events':'none'});
		$('#playSound').prop('src',Utils.Path+'sound/CorrectSound.mp3');
		$('#soundBtn').css({'pointer-events':'none'});
		Number123.moveCar(eleId,100);
		if(Number123.attempCnt==1)
			scoredMarks=10;
		else if (Number123.attempCnt==2)
			scoredMarks=5;
		else 
			scoredMarks=0;
		Number123.nextQuestionTimeout=setTimeout(function()
		{
			Number123.nextQue();
		},3500);
	}
	else
	{
		scoredMarks=0;
		$('#playSound').prop('src',Utils.Path+'sound/wrong.mp3');
		$('#soundBtn').css({'pointer-events':'none'});
		$('.options').css({'pointer-events':'none'});	
		Number123.moveCar(eleId,55);
	}
	document.getElementById('playSound').play();
	
}

Number123.moveCar=function(eleId,value)
{
	var num=$('#'+eleId).data('number');
	$('#'+eleId).css({'background-image':'url(images/'+num+'truckrun.gif)'});
	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()
{
	Number123.calculateScore();
	Number123.questionCnt++;
	if(Number123.questionCnt>=5)
	{
		document.getElementById('playSound').pause();
		//gameOver.innerHTML=Number123.hardCodedData.gameOver;
		Number123.gamePlayedFlag=false;
		Number123.AcknowledgementPage();
		$('#endpage').show();
		$('#gamePage').hide();
		$('#question').addClass('gameOver');
		$('#question').text(Number123.hardCodedData.gameOver);
	}
	else
	{
		Number123.resetVariables();
		if(Number123.level==1)
			Number123.setlevel2Que();
		else
			Number123.setlevel2Que();
	}
}

Number123.calculateScore=function()
{
	if(Utils.mobileDeviceFlag && Number123.gamePlayedFlag==false)
	{
		scoredMarks=-1;
		Android.addScore(resId,quesId,scoredMarks,totalMarks,level,startTime,label);
	}
	else if(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,level,startTime,label);
}

Number123.AcknowledgementPage=function()
{
	var i=0,div;
	for(i=0;i<Object.keys(Number123.AcknowledgementPageData).length;i++)
	{
		div=document.createElement('div');
		div.className="ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML=Object.keys(Number123.AcknowledgementPageData)[i]+" : "+Object.values(Number123.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div=document.createElement('div');
	div.className="ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=Number123.hardCodedData['createdOn'];
	acknowledgementDiv.appendChild(div);
}

Number123.backToHome=function()
{
	document.getElementById('playSound').pause();
	$('#question').text('');
	if(Number123.levelFlag)
		location.reload();
	else
	{
		Number123.levelFlag=true;
		document.getElementById('gamePage').style.display='none';	
		document.getElementById('levelPage').style.display='block';
		if(Utils.mobileDeviceFlag && Number123.gamePlayedFlag)
			Android.addScore(resId,quesId,scoredMarks,totalMarks,level,startTime,label);
	}
	
	
}

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

Number123.playAgain=function()
{
	Number123.questionCnt=0;
	Number123.questionArr=[];
	Number123.resetVariables();
	$("#endpage").hide();
	$('#gamePage').show();
	$('#acknowledgementDiv').empty();
	$('#acknowledgementDiv').css('visibility','hidden');
	Number123.levelFunction();
	Number123.playSound();
}

Number123.showCredits=function()
{
	$("#acknowledgementDiv").css('visibility','visible');
}

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