var PattaPalat={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMark=1,resId=0,getDurationFlag=true,callback='';
PattaPalat.todaysData=[];

$(document).ready(function()
{
	if(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag=true;
	$(".se-pre-con").fadeOut("slow");
	setTimeout(function()
	{
		PattaPalat.setimage();
	
	if(Utils.mobileDeviceFlag)
	{	
   		PattaPalat.todaysData=getTodaysLetters();
	}
	else
		PattaPalat.todaysData=getTodaysLetters();
	
	console.log(PattaPalat.todaysData);
	},100);
		
},300);
PattaPalat.setimage=function()
{
	$('body').css('backgroundImage','url('+Utils.Path+'images/Judva.png)');
		$('#gamePage').hide();
		$('#lastPage').hide();
		PattaPalat.setImages();
		//PattaPalat.playGame();
}
function getTodaysLetters(){
	var temp=[];
	temp=populate(PattaPalat.Consonants,temp,2);
	return temp;
}

function populate(array1, array2, length)
{
	var randomIndex;
	while (array2.length !== length) 
	{
	randomIndex = Math.floor(Math.random()*array1.length);
	if($.inArray(array1[randomIndex],array2) === -1)
	array2.push(array1[randomIndex]);
	}
	return array2;
}
//function to set images
PattaPalat.setImages=function()
{
	$('#logo').prop("src",Utils.Path+"images/logo.png");
	$('#modalImg').prop("src",Utils.Path+"images/open.png");
	$('#playbtnid').prop("src",Utils.Path+"images/play.png");
	$('#homeImg').prop("src",Utils.Path+"images/home.png");
	document.getElementById("homeImg").style.visibility="hidden";
	document.getElementById('soundImg').setAttribute("onclick","PattaPalat.playLetter()");
	$('#soundImg').css('pointer-events','none');
	$("#modalMsg").text(PattaPalat.hardCodedData.correctMsg);
};

PattaPalat.resetData=function()
{
	//PattaPalat.copyJson={}
	PattaPalat.shuffledArray=[];
	PattaPalat.characterArr=[];
	PattaPalat.correctCnt=0;
	PattaPalat.currentCard1=-1;
	PattaPalat.currentCard2=-1;
	PattaPalat.totalCharacters=6;
	PattaPalat.playedLetterCnt=0;
	PattaPalat.letters=[];
	PattaPalat.intervl;
	PattaPalat.totalPlayCnt=0;
	PattaPalat.starCnt=1;
	PattaPalat.totalCorrectCnt=0;
	PattaPalat.letterSound;
};

function shuffleArray(array)
{
	var i,j,temp;
	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;
	}
	return array;
}

PattaPalat.randomGenerator=function(array){
		return (Math.floor(Math.random() * array.length+0));
};

//this function will execute on click of play button
PattaPalat.playGame=function()
{	
	$('body').css('backgroundImage','url('+Utils.Path+'images/Bg.jpg)');
	document.getElementById("homeImg").style.visibility="visible";
	document.getElementById("playbtnid").style.visibility="hidden";
	$('#soundImg').prop("src",Utils.Path+"images/Sound.png");
	PattaPalat.resetData();
	$("#gamePage").show();
	PattaPalat.letters=PattaPalat.todaysData.slice(0);
	//PattaPalat.copyJson=JSON.parse(JSON.stringify(PattaPalat.Data));
	PattaPalat.createStars();
	PattaPalat.generateCardData();
	PattaPalat.createCards("mainDiv",PattaPalat.totalCharacters,"cardDiv");
};

PattaPalat.createStars=function(){
	var temp,newImage,newDiv,i,numberOfStars=2;
	for(i=1;i<=numberOfStars;i++)
	{
		newDiv= document.createElement("div");
		newDiv.setAttribute("id","starDiv"+i); 
		newDiv.setAttribute("class","noPadding col-xs-5 col-md-5 col-lg-5 col-sm-5"); 

		newImage= document.createElement("img");
		newImage.setAttribute("id","starImg"+i); 
		newImage.setAttribute("class","img-responsive"); 
		newImage.setAttribute("src",Utils.Path+"images/star5.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
};

PattaPalat.giveStars=function(id){
	$("#starImg"+id).prop("src",Utils.Path+"images/star4.png");
};

PattaPalat.generateCardData=function()
{
	var letterIndex,firstLetter,duration,d,oldLetter;
	d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	console.log(startTime);
	PattaPalat.totalCorrectCnt=0;
	letterIndex=PattaPalat.randomGenerator(PattaPalat.todaysData);
	
	firstLetter=PattaPalat.todaysData[letterIndex];
	PattaPalat.letterSound=($.inArray(firstLetter,PattaPalat.Consonants))
	questionId=PattaPalat.Data[PattaPalat.letterSound].questionId;
	//console.log(questionId);
	$('.cardsImg').css('pointer-events','none');

	PattaPalat.playLetter();
	
	PattaPalat.showLetters();
	PattaPalat.todaysData.splice(letterIndex,1);
	oldLetter=firstLetter;
	PattaPalat.characterArr=PattaPalat.fillCharacterArray(firstLetter,PattaPalat.Consonants);
	PattaPalat.shuffledArray=shuffleArray(PattaPalat.characterArr);
	//console.log(PattaPalat.shuffledArray);
};
//Chng (Callback)
function getDuration(src,callback)
{
	var duration=0;
	if(getDurationFlag){
		$('#playSound').on("loadedmetadata", function(){
			getDurationFlag=false;
			duration=$('#playSound').prop('duration');
			$('#playSound').unbind('loadedmetadata');
			callback(duration);
	    });
	} 
    $('#playSound').prop('src',src);
}


PattaPalat.playLetter=function()
{
	clearTimeout(PattaPalat.answerAudio);
	getDurationFlag=true;
	callback=PattaPalat.playInstruction;
	getDuration(Utils.Path+"sounds/hindi/"+PattaPalat.Data[PattaPalat.letterSound].sound,callback)
}

PattaPalat.playInstruction=function(duration){
	document.getElementById("playSound").play();
	PattaPalat.answerAudio=setTimeout(function(){
		PattaPalat.playAudio(PattaPalat.hardCodedData.instruction);
	},duration*1000);
}

// Show Letters After each Question Load
PattaPalat.showLetters=function(){
	$('.cardsImg').css('pointer-events','none');
	setTimeout(function(){
		$('.cardsImg').prop("src",Utils.Path+"images/open.png");
		$('.letter').show();	
		setTimeout(function(){
			$('.cardsImg').prop("src",Utils.Path+"images/close.png");
			$('.letter').hide();
			$('.cardsImg').css('pointer-events','auto');
			$('#soundImg').css('pointer-events','auto');
		},4000);
	},1000);
};

//Fill characters in array
PattaPalat.fillCharacterArray=function(letter,letterArray)
{
	var temp=[],randomIndex,length=6;
	temp=Array(2).fill(letter);	
	while(temp.length !== length) 
	{
		randomIndex = Math.floor(Math.random()*letterArray.length);
		if(($.inArray(letterArray[randomIndex],temp) === -1)  && ($.inArray(letterArray[randomIndex],PattaPalat.todaysData)=== -1) && ($.inArray(letterArray[randomIndex],PattaPalat.letters) === -1))
			temp.push(letterArray[randomIndex]);
	}
	return temp;
};

//to create no of cards div 
PattaPalat.createCards=function(parentDiv,numberOfDivs,idName)
{
	var newDiv,i;
	for(i=0;i<numberOfDivs;i++)
	{
		newDiv= document.createElement("div");
		newDiv.setAttribute("id",""+idName+''+i); 
		newDiv.setAttribute("class","noPadding cards col-xs-3 col-md-3 col-lg-3 col-sm-3 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1"); 
		$(newDiv).data("cardClick",0);
		
		var newImage= document.createElement("img");
		newImage.setAttribute("id","cardImg"+i); 
		newImage.setAttribute("class","img-responsive cardsImg"); 
		newImage.setAttribute("onclick","PattaPalat.cardClick(this)");
		newImage.setAttribute("src",Utils.Path+"images/close.png");

		var newSpan= document.createElement("span");
		newSpan.setAttribute("id","letterSpan"+i);
		newSpan.setAttribute("class","letter");
		$(newSpan).text(PattaPalat.shuffledArray[i]);
		
		$(newImage).show();
		$(newSpan).hide();	
		$(newDiv).append(newImage);
		$(newDiv).append(newSpan);
		$("#"+parentDiv).append(newDiv);
	}
};

PattaPalat.cardClick=function(obj)
{
	var id,card1,card2;
	id=$(obj).attr("id");
	id=parseInt(id.substring(7));
	if(PattaPalat.currentCard1<0)
	{	
		card1=obj;
		PattaPalat.currentCard1=id;
		document.getElementById("playSound").pause();
		document.getElementById('playSound').src=Utils.Path+"sounds/"+PattaPalat.hardCodedData.openWindow;
		document.getElementById("playSound").play();	
		$("#cardImg"+PattaPalat.currentCard1).css('pointer-events','none');
	}
	if(id!=PattaPalat.currentCard1 && PattaPalat.currentCard1!=-1)
	{
		card2=obj;
		PattaPalat.currentCard2=id;
		//PattaPalat.playAudio(PattaPalat.hardCodedData.openWindow);
		document.getElementById("playSound").pause();
		document.getElementById('playSound').src=Utils.Path+"sounds/"+PattaPalat.hardCodedData.openWindow;
		document.getElementById("playSound").play();	
		$("#cardImg"+PattaPalat.currentCard2).css('pointer-events','none');
	}
	$("#cardImg"+id).addClass("animated flipInY");
	$("#cardImg"+id).prop("src",Utils.Path+"images/open.png");
	
	setTimeout(function()
	{
		$("#cardImg"+id).removeClass("animated flipInY");
		$("#letterSpan"+id).show();
	},200);

	if(PattaPalat.currentCard1>=0 && PattaPalat.currentCard2>=0)
	{
		$(".cardsImg").css('pointer-events','none');
		$("#soundImg").css('pointer-events','none');
		setTimeout(function(){
			PattaPalat.validate(PattaPalat.currentCard1,PattaPalat.currentCard2);
		},2000);

	}
};

//Correct Wrong fun. added
PattaPalat.validate=function(card1,card2){
	clickedCard1Data=$("#letterSpan"+card1).text();
	clickedCard2Data=$("#letterSpan"+card2).text();
	if(clickedCard1Data===clickedCard2Data)
	{	
		getDurationFlag=true;
		callback=PattaPalat.forCorrect;
		getDuration(Utils.Path+"sounds/"+PattaPalat.hardCodedData.correctAudio,callback);
	}	
	else
	{
		getDurationFlag=true;
		callback=PattaPalat.forWrong;
		getDuration(Utils.Path+"sounds/"+PattaPalat.hardCodedData.wrongAudio,callback);
	}
};
PattaPalat.forCorrect=function(duration){
	//document.getElementById("playSound").src=Utils.Path+"sounds/"+PattaPalat.hardCodedData.correctAudio;

		scoredMarks=1;
		PattaPalat.totalPlayCnt++;
		PattaPalat.totalCorrectCnt++;
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMark,1,startTime);
		console.log(questionId,scoredMarks,totalMark,startTime);

		PattaPalat.answerAudio=setTimeout(function(){
				PattaPalat.playAudio(PattaPalat.hardCodedData.correctAudio);
				PattaPalat.answerAudio=setTimeout(function()
				{
					PattaPalat.playLetter();
					PattaPalat.afterBothCardShowHideCards();
					PattaPalat.correctCnt++;
					$("#responseBoxDiv").hide();
					PattaPalat.setDataAfterCorrect();
			},duration*1000);
							
			$("#soundImg").css('pointer-events','auto');
			$("#responseBoxDiv").show();
		},300);
}

PattaPalat.forWrong=function(duration){
	scoredMarks=0;PattaPalat.totalPlayCnt++;
	PattaPalat.correctCnt=0;
	if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMark,1,startTime);
		console.log(questionId,scoredMarks,totalMark,startTime);
	
	PattaPalat.playAudio(PattaPalat.hardCodedData.wrongAudio);
		setTimeout(function(){
			PattaPalat.playLetter();;
			PattaPalat.afterBothCardShowHideCards();
			PattaPalat.setDataAfterCorrect();
		},duration*1000);
}

PattaPalat.playAudio=function(audio){
	PattaPalat.answerAudio=setTimeout(function(){
		document.getElementById('playSound').pause();	
			document.getElementById('playSound').src=Utils.Path+"sounds/"+audio;
			document.getElementById("playSound").play();	
	},150);
};
PattaPalat.afterBothCardShowHideCards=function(){
	$("#letterSpan"+PattaPalat.currentCard1).hide();
	$("#cardImg"+PattaPalat.currentCard1).prop("src",Utils.Path+"images/close.png");
	$("#letterSpan"+PattaPalat.currentCard2).hide();
	$("#cardImg"+PattaPalat.currentCard2).prop("src",Utils.Path+"images/close.png");
	$(".cardsImg").css( 'pointer-events', 'auto');
	PattaPalat.currentCard1=PattaPalat.currentCard2=-1;
}
PattaPalat.setDataAfterCorrect=function()
{
	var length;
	if(PattaPalat.correctCnt==3||PattaPalat.totalPlayCnt==9)	
	{	
		PattaPalat.playedLetterCnt++;
		if(PattaPalat.correctCnt==3)
		{	PattaPalat.giveStars(PattaPalat.starCnt);
			PattaPalat.starCnt++;
		}
		/*if(Utils.mobileDeviceFlag)	
			Android.StudentLevelDetection(PattaPalat.totalCorrectCnt,PattaPalat.totalPlayCnt);
			
		console.log("Student Detection ("+PattaPalat.totalCorrectCnt+" "+PattaPalat.totalPlayCnt+")");*/
		
		PattaPalat.correctCnt=0;
		PattaPalat.totalPlayCnt=0;
		
		if(PattaPalat.playedLetterCnt==2)	
		{
			$("#lastPage").hide();
			$("#gamePage").hide();
			$("#soundImg").hide();
			clearTimeout(PattaPalat.tempTimer);
			clearInterval(PattaPalat.intervl);
			setTimeout(function(){
			$("#responseBoxDiv").hide();
			clearTimeout(PattaPalat.answerAudio);
			document.getElementById('playSound').src='';
			},250);
			$('#lastPage').show();
			$("#lastMsg").text(PattaPalat.hardCodedData.endMsg);
		}
		else
			PattaPalat.generateCardData();
	}
	PattaPalat.showLetters();
	if(PattaPalat.playedLetterCnt<=2)	
	{
		PattaPalat.shuffledArray=shuffleArray(PattaPalat.characterArr);
		length=PattaPalat.shuffledArray.length;
		for(var i=0;i<length;i++)	
			$("#letterSpan"+i).text(PattaPalat.shuffledArray[i]);
	}		
};
PattaPalat.homepage=function()
{
	location.reload(true);
}