//12 Oct
var ListenAndSpell={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
ListenAndSpell.makeItQue=0;
ListenAndSpell.nextQuesTimer=0;
var startTime=0,scoredMarks=0,totalMarks=10,resId=0,level=2,quesId=0,label='';
var wordName='',totalNos=0,wordType='alphabet';
ListenAndSpell.loadmetaDataFlag=false;
ListenAndSpell.gamePlayedFlag=false;
ListenAndSpell.attemptFlag=false;
ListenAndSpell.startIndex=[];
ListenAndSpell.nextQuestionCnt=0;
ListenAndSpell.wrong=0;
ListenAndSpell.soundInterval=null;
ListenAndSpell.instructionCnt=0;
ListenAndSpell.queSnd=0;
ListenAndSpell.playAllSoundArr=[];
ListenAndSpell.sndTimer=0;
ListenAndSpell.QueTimer=0;
ListenAndSpell.questionArr=[];
ListenAndSpell.queCnt=0;
ListenAndSpell.levelIndexFlag=false;
ListenAndSpell.levelNo=0;
$(document).ready(function()
{
	$(".se-pre-con").fadeOut("slow");
	if(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag=true;
	if(Utils.mobileDeviceFlag)
	{
		ListenAndSpell.levelNo=Android.getLevel(); 
		ListenAndSpell.levelIndexFlag=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/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";
	if(ListenAndSpell.levelIndexFlag)
		ListenAndSpell.levelNo=ListenAndSpell.levelNo-1;
	else
	{
		ListenAndSpell.levelNo=Math.floor(Math.random()*2)+1;
		ListenAndSpell.levelNo=ListenAndSpell.levelNo-1;
	}
	getUniqueValArr(ListenAndSpell.data,ListenAndSpell.questionArr,5);
	ListenAndSpell.createDiv();
	ListenAndSpell.setQuestion();
	/* ListenAndSpell.createDiv();
	getUniqueValArr(ListenAndSpell.data,ListenAndSpell.questionArr,5);
	ListenAndSpell.setQuestion(); */
}
ListenAndSpell.createDiv=function()
{
	var spanDiv,optionDiv;
	for(var i=0;i<6;i++)
	{
		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');
		//$(spanDiv).css('background-image',"url("+Utils.Path+'images/window.png'+")");
		wordDiv.appendChild(spanDiv);
	}
	for(var i=0;i<6;i++)
	{
		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 i=0,d,randomWord,randomRhyme,span,queWord=[],soundIdx,makeItArr=[],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();
	randomRhyme=Math.floor((Math.random() * ListenAndSpell.questionArr[ListenAndSpell.queCnt].list.length));
	
	ListenAndSpell.queWord=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomRhyme].word;
	makeItQueSound=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomRhyme].sound;

	randomWordToShow=Math.floor((Math.random() * ListenAndSpell.questionArr[ListenAndSpell.queCnt].list.length));
	while(randomRhyme==randomWordToShow)
		randomWordToShow=Math.floor((Math.random() * ListenAndSpell.questionArr[ListenAndSpell.queCnt].list.length));
	ListenAndSpell.que=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomWordToShow].word.split("");
	shownWordSound=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomWordToShow].sound;
	ListenAndSpell.showWord();
	for(var i=0;i<ListenAndSpell.que.length;i++)
	{
		soundIdx=$.inArray(ListenAndSpell.que[i],ListenAndSpell.alphabets);
		source=ListenAndSpell.alphabetSound[soundIdx].soundURL;
		ListenAndSpell.playAllSoundArr.push(source)
	}
	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].list[randomRhyme].questionId);
	label=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomRhyme].word;
	displayWord=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomRhyme].word.split("");

	
	if(displayWord.length==2 || displayWord.length==3)
		j=3;
	else if(displayWord.length==4 || displayWord.length==5)
		j=2;
	else
		j=1;
	ListenAndSpell.startIndex.push(j);
	for(var k=0;k<displayWord.length;k++)
	{
		span=document.createElement('span');
		span.setAttribute("id","wordSpan"+j);
		span.setAttribute("class","textSpan text-center col-xs-12 col-sm-12 col-lg-12 col-md-12 noPadding");
		span.innerHTML=displayWord[k];
		$("#spanDiv"+j).append(span);
		j++;
	}
	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'+")");
	}
	document.getElementById('wordSpan'+ListenAndSpell.startIndex[0]).style.color="rgba(0, 0, 0,0)";
	ListenAndSpell.setOptions();
}

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");		
   });
}
ListenAndSpell.showWord=function()
{
	var span;
	for(var i=0;i<ListenAndSpell.que.length;i++)
	{
		span=document.createElement('span');
		span.setAttribute('id','letter'+i);
		span.setAttribute('class','col-xs-1 col-sm-1 col-md-1 col-lg-1 letterSpan');
		span.innerHTML=ListenAndSpell.que[i];
		showWordDiv.appendChild(span);
	}
}
ListenAndSpell.playWordSound=function(duration)
{
	var soundIdx,source;

	document.getElementById("playSound").play();
	if(ListenAndSpell.instructionCnt<ListenAndSpell.que.length)
	{
		document.getElementById('letter'+ListenAndSpell.instructionCnt).style.color="red";
	}
	ListenAndSpell.instructionCnt++;
	if(ListenAndSpell.soundInterval)
	{
		clearInterval(ListenAndSpell.soundInterval);
		ListenAndSpell.soundInterval=null;
	}
	ListenAndSpell.soundInterval=setTimeout(function()
	{
		if(ListenAndSpell.instructionCnt<ListenAndSpell.playAllSoundArr.length)
		{
			ListenAndSpell.loadmetaDataFlag=true;
			source=ListenAndSpell.playAllSoundArr[ListenAndSpell.instructionCnt];
			ListenAndSpell.getDuration(source,ListenAndSpell.playWordSound);

		}
		else
		{
			clearInterval(ListenAndSpell.soundInterval);
			ListenAndSpell.soundInterval=null;
			$('#sound').css({'pointer-events':'auto'});
			$('.options').css({'pointer-events':'auto'});	
		}
		if(ListenAndSpell.instructionCnt<=ListenAndSpell.que.length)
		{
			document.getElementById('letter'+(ListenAndSpell.instructionCnt-1)).style.color="black";
		}
	},duration*1500);
}
ListenAndSpell.playInstruction=function()
{
	document.getElementById('playSound').pause();
	clearTimeout(ListenAndSpell.AnsQuestionTimer);
	clearTimeout(ListenAndSpell.sndTimer);
	clearTimeout(ListenAndSpell.QueTimer);
	clearInterval(ListenAndSpell.noResponseTimer);
	clearTimeout(ListenAndSpell.timeOut);
	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'});	
		},1000);
	},1000);
}

//set options
ListenAndSpell.setOptions=function()
{
	var queWord,queWordArr=[],span,optionDiv,optionArray=[];
	queWordArr=ListenAndSpell.queWord.split("");
	optionArray.push(queWordArr[0]);
	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);
	}
}

//check answer on drop
ListenAndSpell.checkAnswer=function(id)
{
	var clickedLetter,letter;
	ListenAndSpell.gamePlayedFlag=true;
	//ListenAndSpell.attemptFlag=true;
	clickedLetter=document.getElementById(id).innerHTML;
	letter=document.getElementById('spanDiv'+ListenAndSpell.startIndex[0]).children[0];//.children[0];
	$('#'+id).css('pointer-events','none');
	if(clickedLetter==displayWord[0])
	{
		clearTimeout(ListenAndSpell.QueTimer);
		clearTimeout(ListenAndSpell.sndTimer);
		letter.innerHTML=clickedLetter;
		$('.options').css('pointer-events','none');
		$('#sound').css({'pointer-events':'none'});
		$(letter).css({"color":"green"});
		$('#'+id).css({"color":"rgba(0, 0, 0,#333)"});
		//randomSound=Math.floor(Math.random()*ListenAndSpell.correctSnd.length);
		document.getElementById('playSound').src="sounds/instruction/You_did_it.mp3";
		document.getElementById('playSound').play();
		ListenAndSpell.attemptFlag=false;
		if(ListenAndSpell.wrong==1)
			scoredMarks=8;
		else if(ListenAndSpell.wrong==2)
			scoredMarks=6;
		else if(ListenAndSpell.wrong==3)
			scoredMarks=4;
		else if(ListenAndSpell.wrong==4)
			scoredMarks=1;
		else
			scoredMarks=10;
		if(Utils.mobileDeviceFlag)
			Android.addLearntData(ListenAndSpell.queWord,totalNos,wordType);
		console.log(ListenAndSpell.queWord,totalNos,wordType);
		if(ListenAndSpell.nextQuesTimer)
		{
			clearTimeout(ListenAndSpell.nextQuesTimer);
			ListenAndSpell.nextQuesTimer=null;
		}
		ListenAndSpell.nextQuesTimer=setTimeout(function()
		{
			ListenAndSpell.Next();
		},2000);
	}
	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/Try_again.mp3";
		document.getElementById('playSound').play();
	}
}

//load new question
ListenAndSpell.Next=function()
{
	ListenAndSpell.calculateScore();
	ListenAndSpell.queCnt++;
	ListenAndSpell.nextQuestionCnt++;
	if(ListenAndSpell.nextQuestionCnt>=5)
	{
		ListenAndSpell.gamePlayedFlag=false;
		ListenAndSpell.AcknowledgementPage();
		clearTimeout(ListenAndSpell.nextQuesTimer);
		clearInterval(ListenAndSpell.soundInterval);
		gameOver.innerHTML=ListenAndSpell.hardCodedData.gameOver;
		document.getElementById('playSound').pause();
		document.getElementById('gamePage').style.display="none";
		document.getElementById('endpage').style.display="block";
		//document.getElementById('exampleDiv').style.visibility="hidden";
	}
	else
	{
		ListenAndSpell.resetVar();
		ListenAndSpell.setQuestion();
	}
}

ListenAndSpell.AcknowledgementPage=function()
{
	var i=0,div;
	//document.getElementById("endpage").style.display="block";
	

	console.log(Object.keys(ListenAndSpell.AcknowledgementPageData).length)
	for(i=0;i<Object.keys(ListenAndSpell.AcknowledgementPageData).length;i++)
	{
		div=document.createElement('div');
		div.className="fontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML=Object.keys(ListenAndSpell.AcknowledgementPageData)[i]+" : "+Object.values(ListenAndSpell.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div=document.createElement('div');
	div.className="fontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=ListenAndSpell.hardCodedData['gameDate'];
	acknowledgementDiv.appendChild(div);

}

ListenAndSpell.credits=function()
{
	document.getElementById("acknowledgementDiv").style.visibility="visible";
}
ListenAndSpell.calculateScore=function()
{
	if(Utils.mobileDeviceFlag && ListenAndSpell.gamePlayedFlag==false)
	{
		scoredMarks=-1;
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		console.log(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
	}
	else if(ListenAndSpell.attemptFlag)
	{
		scoredMarks=0;
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		console.log(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		ListenAndSpell.attemptFlag=false;
	}
	else if(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
}
ListenAndSpell.resetVar=function()
{
	$('.textSpan').remove();
	$('.optionsSpan').remove();
	$('#showWordDiv').empty();
	clearTimeout(ListenAndSpell.nextQuesTimer);
	document.getElementById('playSound').pause();
	ListenAndSpell.playAllSoundArr=[];
	ListenAndSpell.startIndex=[];
	$('#sound').css({'pointer-events':'auto'});
	$('.options').css('pointer-events','auto');
	ListenAndSpell.queWord=0;
	ListenAndSpell.instructionCnt=0;
	ListenAndSpell.gamePlayedFlag=false;
	clearInterval(ListenAndSpell.soundInterval);
	ListenAndSpell.wrong=0;
	ListenAndSpell.correct=0;
}
ListenAndSpell.playAgain=function()
{
	ListenAndSpell.resetVar();
	ListenAndSpell.nextQuestionCnt=0;
	ListenAndSpell.queCnt=0;
	$('#acknowledgementDiv').empty();
	document.getElementById('acknowledgementDiv').style.visibility="hidden";
	ListenAndSpell.questionArr=[];
	getUniqueValArr(ListenAndSpell.data,ListenAndSpell.questionArr,5);
	ListenAndSpell.setQuestion();
	//document.getElementById('exampleDiv').style.visibility='visible';
	document.getElementById("gamePage").style.display="block";
	document.getElementById("endpage").style.display="none";
}
//onclick of home
ListenAndSpell.callHome=function()
{
	location.reload(true);
	if(Utils.mobileDeviceFlag && ListenAndSpell.gamePlayedFlag)
	{
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		console.log(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		ListenAndSpell.attemptFlag=false;
	}
}
ListenAndSpell.showCredit=function()
{
	document.getElementById('acknowledgementDiv').style.visibility="visible";
}
