
// Started on 9 Jan 2019
var PTP={};
var Utils = {};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0;
PTP.timer=0,PTP.wrongAttempt=0;
var randomLetter,randomClueCategory;
PTP.height=100;
var sec=minute= 0;
var handler;
PTP.queCounter=0;
PTP.queArray=[];
PTP.levelNoData=0;
sentenceCount=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()
	{
		PTP.init();
	},100);
});

PTP.init=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+"images/bg.png)";
	//document.getElementById('rightDiv').style.backgroundImage="url("+Utils.Path+"images/board.png)";
	//document.getElementById('leftDiv').style.backgroundImage="url("+Utils.Path+"images/board.png)";
	$('#homeDiv').css('visibility','hidden');
	$("#coverPage").show();
	//$('#inputDiv,#logoDiv,#gamePage,#endPage,#animationDiv').hide();
	$('#instructionDiv').text(PTP.hardcodeddata.startingInstruction);
	$('#playerCntSpan').text("Enter the number of Players : ");
	$('#playImg').attr('onclick','PTP.showInputDiv();');
	PTP.setimages();																				PTP.instrctionDivs(instructionDiv, 6, 'instruction', 'instrClass');
																			
}
PTP.instrctionDivs=function(parentDiv, numberOfDivs, idName, classname)
{
	var temp=12, optionDiv;
	for (var i = 0; i < numberOfDivs; i++) {
		optionDiv = document.createElement("div");
		optionDiv.setAttribute("id", "" + idName + '' + i);
		optionDiv.setAttribute("class", classname + " col-xs-" + temp + " col-md-" + temp + " col-lg-" + temp + " col-sm-" + temp+"");
		parentDiv.appendChild(optionDiv);
		$("#"+idName + '' + i).text(PTP.startingInstruction[i]);

	}
}
PTP.showInputDiv=function(){
	$('#playImg').attr('onclick','PTP.playGame();');
	$("#instructionPage").hide();
	$("#inputDiv").show();
	$('#homeDiv').css('visibility','visible');
}

//set images
PTP.setimages=function()
{
	document.getElementById('playImg').src=Utils.Path+"images/play.png";
	$("#themeImg").prop("src",Utils.Path+"images/story_or_game_bg.jpg");
	document.getElementById('home').src=Utils.Path+"images/Home.png";
	document.getElementById('logo').src=Utils.Path+"images/logo.png";
	document.getElementById("children").src=Utils.Path+"images/childrens.png";
	document.getElementById("instructionDivOuter").style.background=Utils.Path+"url('images/notpad.png')";
	document.getElementById("instructionDivOuter").style.backgroundSize="100% 100%";
	document.getElementById("inputDiv").style.background=Utils.Path+"url('images/noumber_of_players.png')";
	document.getElementById("inputDiv").style.backgroundSize="100% 100%";
	document.getElementById("counterSpan").style.background=Utils.Path+"url('images/Baki_bache.png')";
	document.getElementById("counterSpan").style.backgroundSize="100% 100%";
	document.getElementById("wordPadDiv").style.background=Utils.Path+"url('images/word_pad.png')";
	document.getElementById("wordPadDiv").style.backgroundSize="100% 100%";
	document.getElementById('correctImg').src=Utils.Path+"images/right.png";
	document.getElementById('wrongImg').src=Utils.Path+"images/rong.png";
	document.getElementById('clock').src="images/wach.png"
	document.getElementById('doneDiv').style.background=Utils.Path+"url('images/noumber_of_players.png')";
	document.getElementById("doneDiv").style.backgroundSize="100% 100%";
	document.getElementById('correctImg').setAttribute('onclick','PTP.checkAnswer("correct")');
	document.getElementById('wrongImg').setAttribute('onclick','PTP.checkAnswer("wrong")');
	document.getElementById('replayImg').src=Utils.Path+"images/replay.png";
	document.getElementById('replayImg').setAttribute('onclick','PTP.goToHome()');
   document.getElementById('animationImg').src=Utils.Path+"images/hand-and-box.gif";
}

PTP.playGame=function()
{
	$('#homeDiv').css('visibility','visible');
	var randomTime=0;PTP.wrongAttempt=0;
	PTP.playerCount=parseInt(document.getElementById('playerCnt').value);
	if(PTP.playerCount<2){
		$('#animationDiv').hide();
		//if(PTP.playerCount<2)
			alert("Please enter the valid player count");
	}
	else if(PTP.playerCount>15)
	{
		alert("Please enter less than 15 players count");
		//$("#playerCnt").text("2");
	}
	else
	{
		$("#logoDiv,#levelPage,#gamePage").show();
		$('#coverPage,#quePage').hide();
		PTP.createLevelDivs(levelPage, 4, 'level', 'LevelsClass');
	}
	//PTP.piecesId=PTP.populate(PTP.piecesId,piecesCnt,piecesCnt);//get unique and shuffled shapes
};
PTP.createLevelDivs = function (parentDiv, numberOfDivs, idName, classname) {
	var temp=6, optionDiv, imgDiv;
	for (var i = 1; i <= numberOfDivs; i++) {
		optionDiv = document.createElement("div");
		optionDiv.setAttribute("id", "" + idName + '' + i);
		optionDiv.setAttribute("class", "noPadding " + classname + " col-xs-" + temp + " col-md-" + temp + " col-lg-" + temp + " col-sm-" + temp);
		parentDiv.appendChild(optionDiv);
			optionDiv.setAttribute("onclick","PTP.showLevel(this.id)");
		optionDiv.setAttribute("data",i-1);

			imgDiv = document.createElement("img");
			imgDiv.setAttribute("id",'img' + i);
			optionDiv.appendChild(imgDiv);
			imgDiv.setAttribute("class", "imgClass img-responsive noPadding col-lg-6 col-md-6 col-xs-6 col-sm-6 col-sm-offset-3 col-lg-offset-3 col-xs-offset-3 col-md-offset-3");
			$("#img" + i).prop("src", Utils.Path + "images/level"+i+".png");
	}
}
PTP.showLevel=function(obj){
	$('#levelPage').hide();
	//#quePage').hide();
	$('#logoImage,#quePage').show();
	randomClueCategory=document.getElementById(obj).getAttribute("data");
	$("#playerRCnt").text("समूह के बाकी बच्चे");
	PTP.playAudioSpecificTime();
	PTP.levelNoData=document.getElementById(obj).getAttribute("data");
	//console.log(PTP.levelNoData);
}

PTP.playAudioSpecificTime=function(){
	PTP.height=100;
	clearInterval(PTP.gameTimer);
	//clearInterval(PTP.myTimer);
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearInterval(PTP.progressBarTimer); 
	PTP.progressBarTimer=null;
	//clearInterval(PTP.gameTimer);
	clearTimeout(PTP.timerAudio);
	PTP.timerAudio=null;
	let randomAudio=Math.floor(Math.random()* (PTP.backgroundAudios.length));
	document.getElementById('playSound').src='';
	document.getElementById('playSound').src=Utils.Path+"sounds/"+PTP.backgroundAudios[randomAudio];
	var max=20,min=5;	
	$("#responseBoxDiv").hide();
	document.getElementById('playSound').play();
	//$("#timerSpan").hide();
	$("#progressBarDiv,#clockDiv,#correctDiv,#wrongDiv").css("visibility","hidden");
	clearInterval(PTP.myTimer);
	$(".mainDivs,#gamePage").hide();
	//document.body.style.backgroundImage="url("+Utils.Path+"images/explosion.gif)";
	$("#animationDiv").show();

	randomTime=Math.floor(Math.random()* (max-min)+1)+min;
	console.log("background Music Time: "+ randomTime);
	PTP.stopAudio=setTimeout(function(){

		document.getElementById('playSound').pause();
		$(".mainDivs").show();
		//document.body.style.backgroundImage="url("+Utils.Path+"images/kksbgnew.png)";
		//$("#themeImgDiv").hide();
		//PTP.setTimer();
		PTP.gameTimer=setInterval(handler, 1000);
		handler();
			if(PTP.levelNoData!=3)
				PTP.setQuestionData();
			else
				PTP.showQueGrid();
	},randomTime*1000);
};

PTP.setQuestionData=function(){
	PTP.queCounter++;
	clearInterval(PTP.gameTimer);
	//clearInterval(PTP.myTimer);
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearInterval(PTP.progressBarTimer); 
	PTP.progressBarTimer=null;
	//clearInterval(PTP.gameTimer);
	clearTimeout(PTP.timerAudio);
	PTP.timerAudio=null;
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearInterval(PTP.progressBarTimer);
	PTP.progressBarTimer=null;
	$("#gamePage").show();
	$("#animationDiv").hide();
	if(PTP.queCounter<=3)
	{
		
		randomNumber=Math.floor(Math.random()*PTP.questionsCategory[randomClueCategory].List.length);
		console.log(randomClueCategory +" , "+randomNumber);
		$("#categoryQue").text(PTP.questionsCategory[randomClueCategory].List[randomNumber].clue);
		$("#categoryQue").css("font-size","6.5vw");
	}
	else if(PTP.queArray.length == 0)
	{
		randomNumber=Math.floor(Math.random()*PTP.sentenceData[randomClueCategory].list.length);
		console.log(randomClueCategory +" , "+randomNumber);
		$("#categoryQue").text(PTP.sentenceData[randomClueCategory].list[randomNumber].EnglishSentence);
		for(var i=0;i<(Object.entries(PTP.sentenceData[randomClueCategory].list[randomNumber].sentence_list).length);i++)
		{
			PTP.queArray.push(Object.entries(PTP.sentenceData[randomClueCategory].list[randomNumber].sentence_list)[i]);
		}
		console.log(PTP.queArray);
		sentenceCount=0;
		PTP.sentenceData[randomClueCategory].list.splice(randomNumber,1);
		$("#categoryQue").css("font-size","4vw");
	}
	else
	{
		$("#categoryQue").css("font-size","4vw");
		$("#categoryQue").text(PTP.queArray[sentenceCount][1]);
		if(sentenceCount<(PTP.queArray.length-1))
			sentenceCount++;
		else
			PTP.queArray=[];
	}
	document.getElementById('playSound1').src=Utils.Path+"sounds/Cymbalbell.mp3";
	document.getElementById('playSound1').play();
	$("#counterSpan").text(PTP.playerCount);
	PTP.answerAudio=setTimeout(function(){
			//PTP.playInstruction();
			PTP.startTimer();
	},100);
  	console.log(minute+"**"+PTP.timer);
//	document.getElementById("playertimer").innerHTML=PTP.timer;
	$("#progressBarDiv,#clockDiv,#StopTimerDiv").css("visibility","visible");
	PTP.questionsCategory[randomClueCategory].List.splice(randomNumber,1);
};

PTP.showQueGrid=function(){
	PTP.queCounter++;
	clearInterval(PTP.myTimer);
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearInterval(PTP.progressBarTimer);
	PTP.progressBarTimer=null;
	$("#gamePage").show();
	$("#animationDiv").hide();

	randomNumber=Math.floor(Math.random()*PTP.sentenceData[randomClueCategory].list.length);
		console.log(randomClueCategory +" , "+randomNumber);
			PTP.createSentenceDivs();
		//$("#categoryQue").text(PTP.sentenceData[randomClueCategory].list[randomNumber].EnglishSentence);

	document.getElementById('playSound1').src=Utils.Path+"sounds/Cymbalbell.mp3";
	document.getElementById('playSound1').play();
	$("#counterSpan").text(PTP.playerCount);
	PTP.answerAudio=setTimeout(function(){
			//PTP.playInstruction();
			PTP.startTimer();
	},100);
  	console.log(minute+"**"+PTP.timer);
	//document.getElementById("playertimer").innerHTML=PTP.timer;
	$("#progressBarDiv,#clockDiv,#StopTimerDiv").css("visibility","visible");
	PTP.sentenceData[randomClueCategory].list.splice(randomNumber,1);
}
PTP.createSentenceDivs=function()
{
	document.getElementById("wordPadDiv").innerHTML="";
	$("#categoryQue").hide();
	$("#wordPadDiv").css("padding-top","12%");
	for(var j=1,k=0;j<=5;j++,k++)
	{
		for(var i=0;i<3;i++)
		{
			var sentenceDiv = document.createElement("Div");
			sentenceDiv.setAttribute("id","sentenceDiv"+j+""+i);
			sentenceDiv.setAttribute("class","nopadding options col-sm-4 col-lg-4 col-md-4 col-xs-4");
			document.getElementById('wordPadDiv').appendChild(sentenceDiv);
			if(j==1)
			{
				$(sentenceDiv).text(i+1);
				$(".options").css("border-top","2px solid black");
			}
			else
			{
				$(sentenceDiv).text(PTP.sentenceData[randomClueCategory].list[randomNumber].Array_List[k-1][i]);
				if(PTP.sentenceData[randomClueCategory].list[randomNumber].Array_List[k-1][i]=='nan')
					$("#sentenceDiv"+j+""+i).css("color","transparent");
			}
		}
	}
	//$(".options").css("font-Size","3vw");
}
function getDuration(src,callback)
{
	var duration=0;
	if(getDurationFlag){
		$('#playSound1').on("loadedmetadata", function(){
			getDurationFlag=false;
			duration=$('#playSound1').prop('duration');
			$('#playSound1').unbind('loadedmetadata');
			callback(duration);
	    });
	} 
    $('#playSound1').prop('src',src);
}

PTP.playInstruction=function(){
	clearTimeout(PTP.answerAudio);
	getDurationFlag=true;
	//callback=PTP.startTimer;
//	getDuration(Utils.Path+"sounds/Instructions/PTPInstructions.mp3",callback);
}

PTP.startTimer=function()
{
	var subtract;
	document.getElementById('playSound1').play();
	PTP.timerAudio=setTimeout(function(){
		document.getElementById('playSound').src=Utils.Path+"sounds/Clock_tik_tik.mp3";
		document.getElementById('playSound').play();

		if(PTP.progressBarTimer)
	{
		clearInterval(PTP.progressBarTimer);
		PTP.progressBarTimer=null;
	}	
	subtract=100/30;
	PTP.progressBarTimer=setInterval(function() 
	{
		if(PTP.height<=0)
		{
			clearInterval(PTP.progressBarTimer);
			PTP.progressBarTimer=null;
			document.getElementById('playSound').pause(); 
			$("#progressBarDiv,#clockDiv,#StopTimerDiv").css("visibility","hidden");
			$("#correctDiv,#wrongDiv").css("visibility","visible");
			document.getElementById('playSound1').pause();
			document.getElementById('playSound1').src=Utils.Path+"sounds/04_Sentence.mp3";
			document.getElementById('playSound1').play();

			$("#correctDiv,#wrongDiv").show();
			//PTP.checkAnswer("wrong");
		}
		if(PTP.height<=20)
			$('#progressBar').addClass("progress-bar-danger");

		PTP.countDown(subtract);
	},800);	
	},1000);	
}

// function which decrements the timer 
PTP.countDown=function(subtract)
{	
	PTP.height-=subtract;
   document.getElementById("progressBar").style.height = PTP.height + '%'; 
};

handler = function() {
	if (++sec === 60) {
	  sec = 0;
	  if (++minute === 60) minute = 0;
	}
	//document.getElementById("timerSpan").innerHTML = (minute < 10 ? "0" + minute : minute) + ":" + (sec < 10 ? "0" + sec : sec);
  };
  
PTP.checkAnswer=function(answer){
	$("#progressBar").css("height","100%");
	document.getElementById('playSound1').pause();
	document.getElementById('playSound').pause();
	$("#progressBarDiv,#clockDiv,#StopTimerDiv").css("visibility","hidden");
	$("#responseBoxDiv").show();	
	$("#gamePage").hide();
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearTimeout(PTP.timerAudio);
	PTP.timerAudio=null;
	getDurationFlag=true;
	
	if(answer=="correct")
	{
		$("#resultTxt").text("Great! Correct Answer! Remaining players will continue. ");
		$("#answerImg").prop("src","images/thumbsup.gif");
		callback=PTP.runAfterCorrectSelection;
		getDuration(Utils.Path+"sounds/Buzzercorrect1.mp3",callback);
		//alert("Great!! Correct Answer. Stay in Group");
	}	
	else
	{
		//alert("Oops !! Wrong Answer. Leave the Group");	
		$("#resultTxt").text("Oops! Wrong Answer. Leave the Group");	
		$("#answerImg").prop("src","images/thumbsdown.gif");
		PTP.playerCount--;	
		callback=PTP.runAfterWrongSelection;
		getDuration(Utils.Path+"sounds/wrong_ans.mp3",callback);		
	}	
}

PTP.runAfterCorrectSelection=function(duration){
	document.getElementById('playSound1').play();
	PTP.timerAudio=setTimeout(function(){
		PTP.animationResponse();
	},duration*2000);	
}
PTP.runAfterWrongSelection=function(duration){
	if(PTP.playerCount==1){
		setTimeout(function(){
			showLastPage();
		},2000);	
	}
	else
	{
		document.getElementById('playSound1').play();
		PTP.timerAudio=setTimeout(function(){
			getDurationFlag=true;
			callback=PTP.moveForward;
			getDuration(Utils.Path+"sounds/"+PTP.playerCount+".mp3",callback);			
			

		},duration*1000);	
	}
}
PTP.moveForward=function(duration){
		document.getElementById('playSound1').play();
		PTP.timerAudio=setTimeout(function(){
			document.getElementById('playSound1').src=Utils.Path+"sounds/03_a_Sentence.mp3";
			document.getElementById('playSound1').play();
			PTP.timerAudio=setTimeout(function(){
				PTP.animationResponse();
							
			},duration*2500);
		},duration*1000);		
}
PTP.animationResponse=function(){
	$("#animationDiv").hide();
	clearInterval(PTP.gameTimer);
	clearInterval(PTP.myTimer);
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearInterval(PTP.progressBarTimer); 
	PTP.progressBarTimer=null;
		//$("#animationDiv").show();
		$('#progressBar').removeClass("progress-bar-danger");
		PTP.height=100;
	document.getElementById("progressBar").style.width = PTP.height + '%'; 
		PTP.playAudioSpecificTime();
		
}
function showLastPage()
{
	clearInterval(PTP.progressBarTimer);
	PTP.progressBarTimer=null;
   $("#gamePage,#animationDiv,#responseBoxDiv").hide();
    document.getElementById('endPage').style.display='block';
	$("#clockDiv,#progressBarDiv").css("visibility","hidden");
	//document.body.style.backgroundImage="";
	document.getElementById('status').innerHTML="Remaining Player is the Winner!";
	document.getElementById('playSound').src=Utils.Path+"sounds/03sec_MusicTrack.mp3";
	document.getElementById('playSound').play();
   // document.getElementById('endPage').style.backgroundImage="url("+Utils.Path+"images/winner.gif)";
   document.body.style.backgroundColor="#000";
    //document.getElementById('wrong').innerHTML=PTP.hardcodeddata.wrongMsg+PTP.wrongAttempt;
    //document.getElementById('time').innerHTML=PTP.hardcodeddata.timeMsg+PTP.timer + " sec"; 
}
PTP.goToHome=function()
{
	location.reload();
}
PTP.stopTimer=function()
{
	PTP.height=100;
	clearInterval(PTP.gameTimer);
	//clearInterval(PTP.myTimer);
	clearTimeout(PTP.answerAudio);
	PTP.answerAudio=null;
	clearInterval(PTP.progressBarTimer); 
	PTP.progressBarTimer=null;
	//clearInterval(PTP.gameTimer);
	clearTimeout(PTP.timerAudio);
	PTP.timerAudio=null;
	clearInterval(PTP.progressBarTimer);
	PTP.progressBarTimer=null;
	document.getElementById('playSound').pause();
	$("#progressBarDiv,#clockDiv,#StopTimerDiv").css("visibility","hidden");
	$("#correctDiv,#wrongDiv").css("visibility","visible");
}