//12 Oct
var ListenAndSpell={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;

var startTime=0,scoredMarks=0,totalMarks=10,resId=0,level=1,quesId=0,label='';
var wordName='',totalNos=0,wordType='alphabet';
ListenAndSpell.loadmetaDataFlag=false;
ListenAndSpell.gamePlayedFlag=false;
ListenAndSpell.attemptFlag=false;
ListenAndSpell.questionArr=[],ListenAndSpell.queCnt=0,ListenAndSpell.makeItQueWord=0,ListenAndSpell.shownWord=0,
ListenAndSpell.playAllSoundArr=[],ListenAndSpell.startIndex=0,ListenAndSpell.nextQuestionCnt=0,
ListenAndSpell.wrong=0,ListenAndSpell.soundTimeout=null,ListenAndSpell.instructionCnt=0,ListenAndSpell.sndTimer=0,ListenAndSpell.seconds=0,
ListenAndSpell.QueTimer=0,ListenAndSpell.makeItQue=0,ListenAndSpell.nextQuesTimer=0,ListenAndSpell.correctCnt=0,ListenAndSpell.skippedCnt=0,ListenAndSpell.AnsQuestionTimer=0,ListenAndSpell.totalQue=5;
var disabledDiv=0,fillQuestionData=[];

$(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()
	{
		ListenAndSpell.setImages();
		ListenAndSpell.totalWordsLength();
		if(ListenAndSpell.hardCodedData['languageFont']!=null)
			setFontFamilyForLang("fonts/"+ListenAndSpell.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");            
}
ListenAndSpell.totalWordsLength=function()
{
	for(var i=0;i<ListenAndSpell.data.length;i++)
	{
		for(var j=0;j<ListenAndSpell.data[i].list.length;j++)
			totalNos++;
	}
}
//set all images
ListenAndSpell.setImages=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+ListenAndSpell.hardCodedData.coverPageImg+")";
	document.getElementById('nextImg').src=Utils.Path+'images/skip.png';
	document.getElementById('nextGame').src=Utils.Path+'images/Next.png';
	document.getElementById('soundImg').src=Utils.Path+'images/Sound.png';
	document.getElementById('play').src=Utils.Path+"images/Play.png";
	/* document.getElementById('playAgain').src=Utils.Path+"images/playAgain.png"; */
	/* document.getElementById('home').src=Utils.Path+"images/Home.png"; */
	document.getElementById('logo').src=Utils.Path+"images/pratham.png";
	/* document.getElementById('credit').src=Utils.Path+"images/credits.png"; */
	document.getElementById('wordOuterDiv').style.backgroundImage="url("+Utils.Path+'images/uperpach.png'+")";
	document.getElementById('footer').style.backgroundImage="url("+Utils.Path+'images/bottamPach.png'+")";
	document.getElementById('gamePage').style.display="none";
	document.getElementById('endpage').style.display="none";
}

//onclick of play
ListenAndSpell.playGame=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+'images/bg.png'+")";
/* 	document.getElementById('home').style.visibility="visible"; */
	document.getElementById('gamePage').style.display="block";
	document.getElementById('coverPage').style.display="none";
	getUniqueValArr(ListenAndSpell.data,fillQuestionData,5);
	makeQuestionArr();
	//ListenAndSpell.questionArr=0;
	ListenAndSpell.createDiv();
	ListenAndSpell.setQuestion();
	ListenAndSpell.createStars();
}
function makeQuestionArr()
{
	var tempArr=[],randomRhyme=0,randomWordToShow=0;
	for(var i=0;i<fillQuestionData.length;i++)
	{
		randomRhyme=Math.floor((Math.random() * fillQuestionData[i].list.length));
		tempArr.push(fillQuestionData[i].list[randomRhyme]);
		randomWordToShow=Math.floor((Math.random() * fillQuestionData[i].list.length));
		while(randomRhyme==randomWordToShow)
			randomWordToShow=Math.floor((Math.random() * fillQuestionData[i].list.length));
		tempArr.push(fillQuestionData[i].list[randomWordToShow]);
		ListenAndSpell.questionArr.push(tempArr);
		tempArr=[];
	}
	console.log(ListenAndSpell.questionArr);
}

//create divs for options and word
ListenAndSpell.createDiv=function()
{
	var spanDiv,optionDiv;
	for(var i=0;i<6;i++)
	{
		//word to highlight
		spanDiv=document.createElement('div');
		spanDiv.setAttribute('id','spanDiv'+(i+1));
		spanDiv.setAttribute('class','text text-center col-xs-1 col-sm-1 col-lg-1 col-md-1 noPadding');
		wordDiv.appendChild(spanDiv);
		
		//for options
		optionDiv=document.createElement('div');
		optionDiv.setAttribute('id','optionDiv'+(i+1));
		optionDiv.setAttribute('class','options text-center col-xs-1 col-sm-1 col-lg-1 col-md-1 noPadding');
		$(optionDiv).css('background-image',"url("+Utils.Path+'images/window.png'+")");
		options.appendChild(optionDiv);
	}
	$('#optionDiv1').css('background-image',"url("+Utils.Path+'images/closeWindow.png'+")");
}

//set Question
ListenAndSpell.setQuestion=function()
{
	var d,randomRhyme,makeItQueSound,randomWordToShow,shownWordSound,source,callback;
	d=new Date();
	$('#sound').css({'pointer-events':'none'});
	$('.options').css({'pointer-events':'none'});
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	
	ListenAndSpell.makeItQueWord=ListenAndSpell.questionArr[ListenAndSpell.queCnt][1].word;
	makeItQueSound=ListenAndSpell.questionArr[ListenAndSpell.queCnt][1].sound;

	ListenAndSpell.shownWord=ListenAndSpell.questionArr[ListenAndSpell.queCnt][0].word.split("");
	shownWordSound=ListenAndSpell.questionArr[ListenAndSpell.queCnt][0].sound;
	
	ListenAndSpell.setWord();
	ListenAndSpell.setOptions();

	ListenAndSpell.playAllSoundArr.push(shownWordSound,"make.mp3",makeItQueSound);
	
	ListenAndSpell.loadmetaDataFlag=true;
	source=ListenAndSpell.playAllSoundArr[ListenAndSpell.instructionCnt];
    callback=ListenAndSpell.playWordSound;
	ListenAndSpell.getDuration(source,callback);
	
	quesId=parseInt(ListenAndSpell.questionArr[ListenAndSpell.queCnt][1].questionId);
	label=ListenAndSpell.questionArr[ListenAndSpell.queCnt][1].word;	
}

//set word to highlight and set window image
ListenAndSpell.setWord=function()
{
	var letterPosition=0,span,soundIdx,source;
	
	if(ListenAndSpell.shownWord.length==2 || ListenAndSpell.shownWord.length==3)
		letterPosition=3;
	else if(ListenAndSpell.shownWord.length==4 || ListenAndSpell.shownWord.length==5)
		letterPosition=2;
	else
		letterPosition=1;
	ListenAndSpell.startIndex=letterPosition;
	disabledDiv=letterPosition;
	for(var k=0;k<ListenAndSpell.shownWord.length;k++)
	{
		span=document.createElement('span');
		span.setAttribute("id","wordSpan"+letterPosition);
		span.setAttribute("class","textSpan text-center col-xs-12 col-sm-12 col-lg-12 col-md-12 noPadding");
		span.innerHTML=ListenAndSpell.shownWord[k];
		$("#spanDiv"+letterPosition).append(span);
		soundIdx=$.inArray(ListenAndSpell.shownWord[k],ListenAndSpell.alphabets);
		source=ListenAndSpell.alphabetSound[soundIdx].soundURL;
		ListenAndSpell.playAllSoundArr.push(source);
		letterPosition++;
	}
	ListenAndSpell.setWindowImage();
}
//set window image
ListenAndSpell.setWindowImage=function()
{
	for(var i=0;i<6;i++)
	{
		if(document.getElementById('spanDiv'+(i+1)).innerHTML=="")
			$("#spanDiv"+(i+1)).css('background-image',"url("+Utils.Path+'images/closeWindow.png'+")");
		else
			$("#spanDiv"+(i+1)).css('background-image',"url("+Utils.Path+'images/window.png'+")");
	}
}
//set options
ListenAndSpell.setOptions=function()
{
	var span,optionDiv,optionArray=[];
	optionArray.push(ListenAndSpell.makeItQueWord[0]);//to get first letter of word
	getUniqueValArr(ListenAndSpell.alphabets,optionArray,4);
	shuffle(optionArray);
	for(var j=0;j<optionArray.length;j++)
	{
		span=document.createElement('span');
		span.setAttribute("id","optionSpan"+(j+1));
		span.setAttribute("class","optionsSpan noPadding col-xs-12 col-sm-12 col-lg-12 col-md-12");
		span.innerHTML=optionArray[j];
		span.setAttribute("onclick","ListenAndSpell.checkAnswer(this.id)");
		$('#optionDiv'+(j+2)).append(span);
	}
}

//getDuration to play sound
ListenAndSpell.getDuration=function(src,callback)
{
	var duration=0;
	$('#playSound').prop('src',"sounds/"+src);
	$('#playSound').on("loadedmetadata", function()
	{
		if(ListenAndSpell.loadmetaDataFlag)
		{
			ListenAndSpell.loadmetaDataFlag=false;
			duration=$('#playSound').prop('duration');
			callback(duration);
		}
		else
		$('#playSound').unbind("loadedmetadata");		
   });
}

//highlight and play word sound
ListenAndSpell.playWordSound=function(duration)
{
	var soundIdx,source;
	document.getElementById("playSound").play();
	if(ListenAndSpell.instructionCnt<ListenAndSpell.shownWord.length)
	{
		document.getElementById('wordSpan'+ListenAndSpell.startIndex).style.color="red";
	}
	ListenAndSpell.startIndex++;
	ListenAndSpell.instructionCnt++;
	if(ListenAndSpell.soundTimeout)
	{
		clearTimeout(ListenAndSpell.soundTimeout);
		ListenAndSpell.soundTimeout=null;
	}
	ListenAndSpell.soundTimeout=setTimeout(function()
	{
		if(ListenAndSpell.instructionCnt<ListenAndSpell.playAllSoundArr.length)
		{
			ListenAndSpell.loadmetaDataFlag=true;
			source=ListenAndSpell.playAllSoundArr[ListenAndSpell.instructionCnt];
			ListenAndSpell.getDuration(source,ListenAndSpell.playWordSound);
		}
		else
		{
			clearTimeout(ListenAndSpell.soundTimeout);
			ListenAndSpell.soundTimeout=null;
			$('#sound').css({'pointer-events':'auto'});
			$('.options').css({'pointer-events':'auto'});	
			document.getElementById('wordSpan'+disabledDiv).innerHTML='';
			if(ListenAndSpell.AnsQuestionTimer)
			{
				clearTimeout(ListenAndSpell.AnsQuestionTimer);
				ListenAndSpell.AnsQuestionTimer=null;
			}
			ListenAndSpell.AnsQuestionTimer=setTimeout(function()
			{
				ListenAndSpell.startTimer();
			},5000);
		}
		if(ListenAndSpell.instructionCnt<=ListenAndSpell.shownWord.length)
		{
			document.getElementById('wordSpan'+(ListenAndSpell.startIndex-1)).style.color="black";
		}
	},duration*1500);
}

//onclick sound play instruction
ListenAndSpell.playInstruction=function()
{
	clearTimeout(ListenAndSpell.AnsQuestionTimer);
	clearInterval(ListenAndSpell.noResponseTimer);
	clearTimeout(ListenAndSpell.timeOut);
	document.getElementById('playSound').pause();
	clearTimeout(ListenAndSpell.sndTimer);
	clearTimeout(ListenAndSpell.QueTimer);
	if(ListenAndSpell.sndTimer)
	{
		clearTimeout(ListenAndSpell.sndTimer);
		ListenAndSpell.sndTimer=null;
	}
	ListenAndSpell.sndTimer=setTimeout(function()
	{
		document.getElementById('playSound').src="sounds/make.mp3";
		document.getElementById('playSound').play();
		if(ListenAndSpell.QueTimer)
		{
			clearTimeout(ListenAndSpell.QueTimer);
			ListenAndSpell.QueTimer=null;
		}	
		ListenAndSpell.QueTimer=setTimeout(function()
		{
			document.getElementById('playSound').src="sounds/"+ListenAndSpell.playAllSoundArr[ListenAndSpell.playAllSoundArr.length-1];
			document.getElementById('playSound').play();
			$('#sound').css({'pointer-events':'auto'});
			$('.options').css({'pointer-events':'auto'});	
			if(ListenAndSpell.AnsQuestionTimer)
			{
				clearTimeout(ListenAndSpell.AnsQuestionTimer);
				ListenAndSpell.AnsQuestionTimer=null;
			}
			ListenAndSpell.AnsQuestionTimer=setTimeout(function()
			{
				ListenAndSpell.startTimer();
			},5000);
		},1000);
	},1000);
}

//check answer on click of options
ListenAndSpell.checkAnswer=function(id)
{
	var clickedLetter,letter;
	ListenAndSpell.gamePlayedFlag=true;
	clearInterval(ListenAndSpell.noResponseTimer);
	clearTimeout(ListenAndSpell.timeOut);
	clearTimeout(ListenAndSpell.AnsQuestionTimer);
	$('#sound').css({'pointer-events':'none'});
	$('.options').css('pointer-events','none');
	clickedLetter=document.getElementById(id).innerHTML;
	letter=document.getElementById('spanDiv'+disabledDiv).children[0];
	$('#'+id).css('pointer-events','none');
	if(clickedLetter==ListenAndSpell.makeItQueWord[0])
	{
		clearTimeout(ListenAndSpell.QueTimer);
		clearTimeout(ListenAndSpell.sndTimer);
		letter.innerHTML=clickedLetter;
		$(letter).css({"color":"green"});
		$('#'+id).css({"color":"rgba(0, 0, 0,#333)"});
		document.getElementById('playSound').src="sounds/instruction/You_did_it.mp3";
		ListenAndSpell.attemptFlag=false;
		ListenAndSpell.correctCnt++;
		scoredMarks=10;
		if(Utils.mobileDeviceFlag)
			Android.addLearntData(ListenAndSpell.makeItQueWord,totalNos,wordType);
		console.log(ListenAndSpell.makeItQueWord,totalNos,wordType);	
	}
	else
	{
		clearTimeout(ListenAndSpell.QueTimer);
		clearTimeout(ListenAndSpell.sndTimer);
		ListenAndSpell.wrong++;
		ListenAndSpell.attemptFlag=true;
		scoredMarks=0;
		$(letter).text(clickedLetter);
		$('#'+id).css({"color":"rgba(255, 0, 0)"});
		$(letter).css({"color":"rgba(255, 0, 0)"});
		document.getElementById('playSound').src="sounds/instruction/wrongbeat3.mp3";	
	}
	document.getElementById('playSound').play();
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
	console.log(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
	ListenAndSpell.questionArr.splice(ListenAndSpell.queCnt,1);
	if(ListenAndSpell.nextQuesTimer)
	{
		clearTimeout(ListenAndSpell.nextQuesTimer);
		ListenAndSpell.nextQuesTimer=null;
	}
	ListenAndSpell.nextQuesTimer=setTimeout(function()
	{
		ListenAndSpell.skippedQuestion();
	},2000);
}

//load next question

ListenAndSpell.skippedQuestion=function()
{	
	if(ListenAndSpell.gamePlayedFlag==false)
	{
		ListenAndSpell.skippedCnt++;
		ListenAndSpell.queCnt++;
	}
	if(ListenAndSpell.questionArr.length==0)
		ListenAndSpell.showLastPage();
	else if(ListenAndSpell.queCnt>=ListenAndSpell.questionArr.length && ListenAndSpell.questionArr.length!=0)
		ListenAndSpell.showPopup();
	else	
	{
		ListenAndSpell.resetVar();
		ListenAndSpell.setQuestion();
	}
}
ListenAndSpell.showSkippedQuestions=function()
{
	$('#responseBoxDiv').hide();
	ListenAndSpell.skipFlag=true;
	ListenAndSpell.skippedCnt=0
	ListenAndSpell.queCnt=0;
	ListenAndSpell.resetVar();
	ListenAndSpell.setQuestion();
}
ListenAndSpell.showPopup=function()
{
	document.getElementById('playSound').pause();
	clearTimeout(ListenAndSpell.AnsQuestionTimer);
	clearInterval(ListenAndSpell.noResponseTimer);
	clearTimeout(ListenAndSpell.timeOut);
	clearTimeout(ListenAndSpell.sndTimer);
	clearTimeout(ListenAndSpell.QueTimer);
	clearTimeout(ListenAndSpell.soundTimeout);
	ListenAndSpell.soundTimeout=null;
	ListenAndSpell.AnsQuestionTimer=null;
	ListenAndSpell.timeOut=null;
	$('#responseBoxDiv').show();
	$('#questionMsg').text(ListenAndSpell.modalData.responseMsg);
	$('#Yes').text(ListenAndSpell.modalData.yes);
	$('#No').text(ListenAndSpell.modalData.no);
}

ListenAndSpell.showLastPage=function()
{
	$('#responseBoxDiv').hide();
	ListenAndSpell.giveStars();
	clearTimeout(ListenAndSpell.nextQuesTimer);
	clearTimeout(ListenAndSpell.soundTimeout);
	gameOver.innerHTML=ListenAndSpell.hardCodedData.gameOver;
	document.getElementById('playSound').pause();
	if(ListenAndSpell.correctCnt>0)
	{
		document.getElementById('playSound').src="sounds/instruction/star"+ListenAndSpell.correctCnt+".mp3";
		document.getElementById('playSound').play();
	}
	document.getElementById('nextDiv').classList.add('blink_me');
	document.getElementById('gamePage').style.display="none";
	document.getElementById('endpage').style.display="block";
	if(Utils.mobileDeviceFlag)
			Android.StudentCertification(ListenAndSpell.correctCnt,ListenAndSpell.totalQue,"8");
}
//reset variables and timer
ListenAndSpell.resetVar=function()
{
	$('.textSpan').remove();
	$('.optionsSpan').remove();
	$('#showWordDiv').empty();
	clearTimeout(ListenAndSpell.nextQuesTimer);
	clearTimeout(ListenAndSpell.soundTimeout);
	document.getElementById('playSound').pause();
	ListenAndSpell.playAllSoundArr=[];
	ListenAndSpell.startIndex=[];
	$('.options').css('pointer-events','auto');
	ListenAndSpell.makeItQueWord=0;
	ListenAndSpell.instructionCnt=0;
	ListenAndSpell.gamePlayedFlag=false;
	ListenAndSpell.wrong=0;
	ListenAndSpell.correct=0;
}

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

ListenAndSpell.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);
	}
	//$("#starDiv").css("display","none");
};
ListenAndSpell.giveStars=function()
{
	var fractionVar,i,numberOfStars=ListenAndSpell.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");
};
ListenAndSpell.goNext=function()
{
	clearInterval(ListenAndSpell.noResponseTimer);
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}