//8th april 2019
var ListenAndShow={};
var Utils={};
Utils.Path='';
var quesId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0,level=1;
var wordName='',totalNos=0,wordType='alphabet';
Utils.mobileDeviceFlag=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.getElementById('playImgDiv').classList.add('slideInUp');
		ListenAndShow.initialiseVar();
		ListenAndShow.setImages();
		ListenAndShow.createStars();
		document.getElementById('playSound').src="sounds/instruction/phonemes.mp3";
		document.getElementById('playSound').play();
		if(ListenAndShow.hardCodedData['languageFont']!=null)
			setFontFamilyForLang("fonts/"+ListenAndShow.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");            
}

ListenAndShow.initialiseVar=function()
{
	ListenAndShow.questionArr=[];
	ListenAndShow.questionCnt=0;
	ListenAndShow.loadmetaDataFlag=false;
	ListenAndShow.gamePlayedFlag=false;
	ListenAndShow.practiceFlag=true;
	ListenAndShow.chartFlag=false;
	ListenAndShow.wordsLearnedFlag=false;
	ListenAndShow.instructionCnt=0;
	ListenAndShow.arr=[];
	ListenAndShow.soundArr=[];
	ListenAndShow.noResponseTimer=0;
	ListenAndShow.AnsQuestionTimer=0;
	ListenAndShow.seconds=0;
	ListenAndShow.timeOut=0;
	ListenAndShow.nextQuestionTimeout=0;
	ListenAndShow.soundTimeout=0;
	ListenAndShow.skippedCnt=0;
	ListenAndShow.totalQue=5;
	ListenAndShow.correctCnt=0;
	getUniqueValArr(ListenAndShow.wordsData,ListenAndShow.questionArr,5);
	totalNos=ListenAndShow.wordsData.length;
}
//set all images
ListenAndShow.setImages=function()
{
	/* document.getElementById('home').src=Utils.Path+"images/home.png"; */
	document.getElementById('logo').src=Utils.Path+"images/logo.png";
	//document.getElementById('shark').src=Utils.Path+"images/shark.gif";
	document.getElementById('playImage').src=Utils.Path+"images/Play.png";
	//document.getElementById('nextImg').src=Utils.Path+"images/Next.png";
	document.getElementById('nextGame').src=Utils.Path+"images/Next.png";
	document.getElementById('nextQuestion').src=Utils.Path+"images/Skip.png";
	/* document.getElementById('playAgain').src=Utils.Path+"images/playAgain.png"; */
	document.getElementById('soundBtn').src=Utils.Path+"images/Sound.png";
	/* document.getElementById('credit').src=Utils.Path+"images/credits.png"; */
	//document.getElementById('teacherImg').src=Utils.Path+"images/Teacher-Fish_01.png";
	document.body.style.backgroundImage=Utils.Path+'url(images/'+ListenAndShow.hardCodedData.cover_page+')';
	//document.getElementById('nextQueBtn').src=Utils.Path+"images/nextGame.png";	
}  
//on click play  
ListenAndShow.playGame=function()
{
	//document.getElementById('shark').classList.add('sharkJump');
	/* setTimeout(function()
	{ */
		document.getElementById('coverPage').style.display='none';	
		document.getElementById('homeDiv').style.visibility='visible';
		document.body.style.backgroundImage=Utils.Path+'url(images/BG_Underwater.png)';
		if(!ListenAndShow.practiceFlag)
		{
			ListenAndShow.createChart();
			document.getElementById('alphabetChartDiv').style.display='block';
		}
		else
			ListenAndShow.NextPage();
	/* },1000); */
	
}
//create alphabet chart
ListenAndShow.createChart=function()
{
	var wordDiv,counter=0,para,rowDiv;
	
	for(var k=0;k<3;k++)
	{
		rowDiv=document.createElement('div');
		rowDiv.setAttribute('id','rowDiv'+(k+1));
		$(rowDiv).css({'display':'inline-flex'});
		alphabetDiv.appendChild(rowDiv);	
		for(var i=0;i<11;i++)
		{
			if(counter<ListenAndShow.wordsData.length)
			{
				wordDiv=document.createElement('div');
				wordDiv.setAttribute('id','wordDiv'+(counter+1));
				wordDiv.setAttribute('class','words text-center');
				$(wordDiv).css({'color':ListenAndShow.wordsData[counter].color});
				wordDiv.setAttribute('data',counter);
				wordDiv.style.backgroundImage=Utils.Path+'url(images/bubble-_Blue.png)';
				for(var j=0;j<2;j++)
				{
					para=document.createElement('p');
					if(j==1)
						para.innerHTML=ListenAndShow.wordsData[counter].langWord;
					else
					{
						para.setAttribute('class','langWord');
						para.innerHTML=ListenAndShow.wordsData[counter].word;
					}
					$(para).css({'margin':'2vh 0 0 0'});
					wordDiv.appendChild(para);
				}
				wordDiv.setAttribute('onclick','ListenAndShow.playSound(this.id)');
				rowDiv.appendChild(wordDiv);
				counter++;
			}
		}
	}
}
//play on click of chart elements
ListenAndShow.playSound=function(id)
{
	var eleData;
	eleData=document.getElementById(id).getAttribute('data');
	document.getElementById('playSound').src="sounds/"+ListenAndShow.wordsData[eleData].langSound;
	document.getElementById('playSound').play();
}
//on click of next on chart page
ListenAndShow.NextPage=function()
{
	var d,randomNo1,randomNo2;
	d=new Date();
	ListenAndShow.chartFlag=true;
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	if(!ListenAndShow.practiceFlag)
		document.getElementById('alphabetChartDiv').style.display='none';
	document.getElementById('bubbleDivPage').style.display='block';
	randomNo1=Math.floor(Math.random()*ListenAndShow.fishImgsLeft.length);
	document.getElementById('fish1').src=Utils.Path+"images/"+ListenAndShow.fishImgsLeft[randomNo1]+".gif";
	randomNo2=Math.floor(Math.random()*ListenAndShow.fishImgsRight.length);
	document.getElementById('fish2').src=Utils.Path+"images/"+ListenAndShow.fishImgsRight[randomNo2]+".gif";
	ListenAndShow.showQuestion();
	shuffle(ListenAndShow.arr);
	for(var i=1;i<=ListenAndShow.arr.length;i++)
	{
		ListenAndShow.createBubbleDivs(bubbleDiv,1,i,ListenAndShow.arr[i-1]);
		ListenAndShow.animateBubblesTop("div"+i);
	}
}
ListenAndShow.createBubbleDivs=function(parentDiv,numberOfDivs,idNo,data)
{
	var bubblesDiv,letter;
    for(var i=1;i<=numberOfDivs;i++)
    {
        bubblesDiv= document.createElement("div");
        bubblesDiv.setAttribute("id","div"+idNo); 
        bubblesDiv.setAttribute("class","bubbleClass bubble"); 
		bubblesDiv.style.backgroundImage=Utils.Path+'url(images/bubble-_Blue.png)';
        parentDiv.appendChild(bubblesDiv);
        
        letter=document.createElement("p");
        letter.setAttribute("id","letter"+idNo);
		letter.setAttribute("class","fontClass  text-center");
		letter.setAttribute("data",data.langWord);
		letter.setAttribute('data-toggle','modal');
		letter.setAttribute('data-target','#myModal');
		letter.setAttribute("onclick","ListenAndShow.checkAnswer(this.id);");
       	letter.innerHTML=data.word;
        bubblesDiv.appendChild(letter);
    }
}
//move bubbles upward
ListenAndShow.animateBubblesTop=function(div)
{
	var speed=0;
    speed=Math.floor((Math.random()*10000)+4500);
    $("#"+div).css({'top':$('#bubbleDiv').height()+80});
    $("#"+div).animate(
    {
        'top':'-='+($(document).height()+($("#"+div).outerHeight()))
    },speed, function()
    {
     $(this).stop();
      id = $(this).prop('id');
     ListenAndShow.animateBubblesTop(id);
    });
}

ListenAndShow.showQuestion=function()
{
	document.getElementById('question').innerHTML=ListenAndShow.questionArr[ListenAndShow.questionCnt].langWord;
	wordName=ListenAndShow.questionArr[ListenAndShow.questionCnt].word;
	ListenAndShow.playQuestionAudio();
	questionId=ListenAndShow.questionArr[ListenAndShow.questionCnt].questionId;
	if(ListenAndShow.questionArr[ListenAndShow.questionCnt].word.toLowerCase()=="a" || ListenAndShow.questionArr[ListenAndShow.questionCnt].word.toLowerCase()=="e" || ListenAndShow.questionArr[ListenAndShow.questionCnt].word.toLowerCase()=="i" || ListenAndShow.questionArr[ListenAndShow.questionCnt].word.toLowerCase()=="o" || ListenAndShow.questionArr[ListenAndShow.questionCnt].word.toLowerCase()=="u")
	{
		ListenAndShow.arr=ListenAndShow.vowelsArr.slice();
	}
	else
	{
		for(var i=0;i<5;i++)
		{
			var randNum=Math.floor(Math.random()*ListenAndShow.consonantArr.length);
			if(ListenAndShow.arr.includes(ListenAndShow.consonantArr[randNum]) || ListenAndShow.consonantArr[randNum].word==ListenAndShow.questionArr[ListenAndShow.questionCnt].word)
			{
				i--;
				continue;
			}
			else
			{
				ListenAndShow.arr.push(ListenAndShow.consonantArr[randNum]);		
			}
		}
		ListenAndShow.arr.push(ListenAndShow.questionArr[ListenAndShow.questionCnt]);
	}
}

ListenAndShow.checkAnswer=function(id)
{
	var data,div,wordList=[];
	ListenAndShow.gamePlayedFlag=true;
	clearTimeout(ListenAndShow.AnsQuestionTimer);
	clearInterval(ListenAndShow.noResponseTimer);
	clearTimeout(ListenAndShow.timeOut);
	document.getElementById('playSound').pause();
	$('.bubble').css({'pointer-events':'none'});
	$('#soundImgDiv').css({'pointer-events':'none'});
	data=document.getElementById(id).getAttribute('data');
	if(data==document.getElementById('question').innerHTML)
	{
		//$('.bubbleClass').stop(true,false);
		/* ListenAndShow.soundArr.push(ListenAndShow.questionArr[ListenAndShow.questionCnt].langSound);
		if(ListenAndShow.questionArr[ListenAndShow.questionCnt].list.length!=0)
		{
			if(ListenAndShow.questionArr[ListenAndShow.questionCnt].list.length>3)
				getUniqueValArr(ListenAndShow.questionArr[ListenAndShow.questionCnt].list,wordList,3);
			else
				wordList=ListenAndShow.questionArr[ListenAndShow.questionCnt].list.slice();
			document.getElementById('suffix').innerHTML=document.getElementById(id).innerHTML+"<sub style='margin-left:5vw'>"+data+"</sub>";
			for(var i=0;i<3;i++)
			{
				var div,parent=document.getElementById('words');
				div=document.createElement('div');
				div.setAttribute('id','spanDiv'+i);
				div.setAttribute('data',wordList[i].sound);
				div.setAttribute('class','relatedWords');
				div.setAttribute('onclick','ListenAndShow.playClickedWordsSnd(this.id);');
				var word=wordList[i].word;
				ListenAndShow.soundArr.push(wordList[i].sound)
				for(var j=0;j<word.length;j++)
				{
					var span;
					span=document.createElement('span');
					span.setAttribute('id','span'+i+j);
					span.innerHTML=word[j];
					div.appendChild(span);
				}
				parent.appendChild(div);
				console.log(word);
				var index=word.indexOf(document.getElementById(id).innerHTML.toLowerCase());
				document.getElementById('span'+i+index).style.color='red';	
			}
			document.getElementById('suffix').style.display='block';
			document.getElementById('words').style.display='block';
			ListenAndShow.loadmetaDataFlag=true;
			source=ListenAndShow.soundArr[ListenAndShow.instructionCnt];
			callback=ListenAndShow.playWordSound;
			ListenAndShow.getDuration(source,callback);
		}
		else
		{
			
		} */
		document.getElementById(id).removeAttribute('data-target','#myModal');
		document.getElementById('playSound').src=Utils.Path+'sounds/instruction/You_did_it.mp3';
		document.getElementById('playSound').play();
		ListenAndShow.nextQuestionTimeout=setTimeout(function()
		{
			ListenAndShow.skippedQuestion();
		},2000);
		scoredMarks=10;
		ListenAndShow.correctCnt++;
		if(Utils.mobileDeviceFlag)
			Android.addLearntData(wordName,totalNos,wordType);
		console.log(wordName,totalNos,wordType);
	}
	else
	{
		document.getElementById(id).setAttribute('data-toggle','');
		document.getElementById(id).setAttribute('data-target','');
		var parentEle=document.getElementById(id).parentElement.id;
		document.getElementById(parentEle).classList.add('shake');
		scoredMarks=0;
		document.getElementById('playSound').src=Utils.Path+'sounds/instruction/wrongbeat3.mp3';
		document.getElementById('playSound').play();
		ListenAndShow.nextQuestionTimeout=setTimeout(function()
		{
			ListenAndShow.skippedQuestion();
		},2000);
	}
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime);
	console.log(resId,quesId,scoredMarks,totalMarks,1,startTime);
	ListenAndShow.questionArr.splice(ListenAndShow.questionCnt,1);
}
//getDuration to play sound
ListenAndShow.getDuration=function(src,callback)
{
	var duration=0;
	$('#playSound').prop('src',Utils.Path+"sounds/"+src);
	$('#playSound').on("loadedmetadata", function()
	{
		if(ListenAndShow.loadmetaDataFlag)
		{
			ListenAndShow.loadmetaDataFlag=false;
			duration=$('#playSound').prop('duration');
			callback(duration);
		}
		else
		$('#playSound').unbind("loadedmetadata");		
   });
}

//play word sound
ListenAndShow.playWordSound=function(duration)
{
	var soundIdx,source;
	document.getElementById("playSound").play();
	if(ListenAndShow.soundTimeout)
	{
		clearTimeout(ListenAndShow.soundTimeout);
		ListenAndShow.soundTimeout=null;
	}
	ListenAndShow.instructionCnt++;
	ListenAndShow.soundTimeout=setTimeout(function()
	{
		if(ListenAndShow.instructionCnt<ListenAndShow.soundArr.length)
		{
			ListenAndShow.loadmetaDataFlag=true;
			source=ListenAndShow.soundArr[ListenAndShow.instructionCnt];
			ListenAndShow.getDuration(source,ListenAndShow.playWordSound);
			$('#spanDiv'+(ListenAndShow.instructionCnt-1)).addClass('bounceIn');
		}
		else
		{
			clearTimeout(ListenAndShow.soundTimeout);
			ListenAndShow.soundTimeout=null;
			$('.relatedWords').css({'pointer-events':'auto'});
			$('.relatedWords').removeClass('bounceIn');
			//$('#myModal').modal('hide');
			//ListenAndShow.nextQuestion();
		}
	},duration*1500);
}
ListenAndShow.resetVariables=function()
{
	clearTimeout(ListenAndShow.soundTimeout);
	clearTimeout(ListenAndShow.nextQuestionTimeout);
	ListenAndShow.soundArr=[];
	ListenAndShow.instructionCnt=0;
	ListenAndShow.arr=[];
	ListenAndShow.gamePlayedFlag=false;
	ListenAndShow.wordsLearnedFlag=false;
	document.getElementById('bubbleDiv').innerHTML='';
	document.getElementById('words').innerHTML='';
	clearTimeout(ListenAndShow.AnsQuestionTimer);
	clearInterval(ListenAndShow.noResponseTimer);
	clearTimeout(ListenAndShow.timeOut);
	//document.getElementById('image').style.display='none';
	$('.suffixAndWord').css({'display':'block'});
	$('#soundImgDiv').css({'pointer-events':'auto'});
	$('.bubble').css({'pointer-events':'auto'});
	$('#myModal').modal('hide');
	document.getElementById('playSound').pause();
}

ListenAndShow.skippedQuestion=function()
{	
	if(ListenAndShow.gamePlayedFlag==false)
	{
		ListenAndShow.skippedCnt++;
		ListenAndShow.questionCnt++;
	}
	if(ListenAndShow.questionArr.length==0)
		ListenAndShow.showLastPage();
	else if(ListenAndShow.questionCnt>=ListenAndShow.questionArr.length && ListenAndShow.questionArr.length!=0)
		ListenAndShow.showPopup();
	else	
	{
		ListenAndShow.resetVariables();
		ListenAndShow.NextPage();
	}
}

ListenAndShow.showSkippedQuestions=function()
{
	$('#responseBoxDiv').hide();
	ListenAndShow.skipFlag=true;
	ListenAndShow.skippedCnt=0
	ListenAndShow.questionCnt=0;
	ListenAndShow.resetVariables();
	ListenAndShow.NextPage();
}
ListenAndShow.showPopup=function()
{
	document.getElementById('playSound').pause();
	clearTimeout(ListenAndShow.AnsQuestionTimer);
	ListenAndShow.AnsQuestionTimer=null;
	clearInterval(ListenAndShow.noResponseTimer);
	clearTimeout(ListenAndShow.timeOut);
	ListenAndShow.timeOut=null;
	$('#responseBoxDiv').show();
	$('#questionMsg').text(ListenAndShow.modalData.responseMsg);
	$('#Yes').text(ListenAndShow.modalData.yes);
	$('#No').text(ListenAndShow.modalData.no);
}

ListenAndShow.showLastPage=function()
{
	$('#responseBoxDiv').hide();
	ListenAndShow.giveStars();
	document.getElementById('playSound').pause();
	gameOver.innerHTML=ListenAndShow.hardCodedData.gameOver;
	document.getElementById('bubbleDivPage').style.display="none";
	document.getElementById('question').style.visibility='hidden';
	document.getElementById('endpage').style.display="block";
	clearTimeout(ListenAndShow.AnsQuestionTimer);
	clearInterval(ListenAndShow.noResponseTimer);
	clearTimeout(ListenAndShow.timeOut);
	document.getElementById('nextDiv').classList.add('blink_me');
	if(ListenAndShow.correctCnt>0)
	{
		document.getElementById('playSound').src="sounds/instruction/star"+ListenAndShow.correctCnt+".mp3";
		document.getElementById('playSound').play();
	}
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(ListenAndShow.correctCnt,ListenAndShow.totalQue,"5");
}

ListenAndShow.playClickedWordsSnd=function(eleId)
{
	var soundData;
	soundData=document.getElementById(eleId).getAttribute('data');
	$('.relatedWords').removeClass('bounceIn');
	$('#'+eleId).addClass('bounceIn');
	document.getElementById('playSound').src=Utils.Path+"sounds/"+soundData;
	document.getElementById('playSound').play();
}

ListenAndShow.playQuestionAudio=function()
{
	document.getElementById('playSound').src="sounds/"+ListenAndShow.questionArr[ListenAndShow.questionCnt].langSound;
	document.getElementById('playSound').play();
	if(ListenAndShow.AnsQuestionTimer)
	{
		clearTimeout(ListenAndShow.AnsQuestionTimer);
		ListenAndShow.AnsQuestionTimer=null;
	}
	ListenAndShow.AnsQuestionTimer=setTimeout(function()
	{
		ListenAndShow.startTimer();
	},5000);
}

ListenAndShow.startTimer=function()
{
	if(ListenAndShow.noResponseTimer)
	{
	clearInterval(ListenAndShow.noResponseTimer);
	ListenAndShow.noResponseTimer=null;
	ListenAndShow.seconds=0;
	}	
	ListenAndShow.noResponseTimer=setInterval(function() 
	{
		ListenAndShow.seconds++;
		if(ListenAndShow.seconds>=5)
		{
			document.getElementById("playSound").src=Utils.Path+"sounds/instruction/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(ListenAndShow.noResponseTimer);
			ListenAndShow.timeOut=setTimeout(function()
			{
				ListenAndShow.seconds=0;
				ListenAndShow.startTimer();
			},2000);
		}
	},1000);
} 
ListenAndShow.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");
};
ListenAndShow.giveStars=function()
{
	var fractionVar,i,numberOfStars=ListenAndShow.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");
};
ListenAndShow.goNext=function()
{
	clearInterval(ListenAndShow.noResponseTimer);
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}