//16th may 2019
var ListenAndShow={};
var Utils={};
Utils.Path='';
var quesId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0,level=2;
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();
		document.getElementById('playSound').src="sounds/instruction/Blends.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;
	if(Utils.mobileDeviceFlag)
		ListenAndShow.practiceFlag=Android.isPractice();
	//ListenAndShow.practiceFlag=true;
	ListenAndShow.chartFlag=false;
	ListenAndShow.instructionCnt=0;
	ListenAndShow.arr=[];
	ListenAndShow.soundArr=[];
	ListenAndShow.wordsLearnedFlag=false;
	ListenAndShow.nextQuestionTimeout=0;
	ListenAndShow.soundTimeout=0;
	ListenAndShow.attemptCount=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('nextQuestion').src=Utils.Path+"images/Next.png";
	document.getElementById('playAgain').src=Utils.Path+"images/playAgain.png";
	document.getElementById('credit').src=Utils.Path+"images/credits.png";
	document.getElementById('soundBtn').src=Utils.Path+"images/Sound.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('playSound').pause();
	document.getElementById('coverPage').style.display='none';	
	document.getElementById('homeDiv').style.visibility='visible';
	$('#homeDiv').css({'z-index':'3000'});
	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();
	
}
//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<12;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();
	scoredMarks=0;
	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()
{
	ListenAndShow.playQuestionAudio();
	document.getElementById('question').innerHTML=ListenAndShow.questionArr[ListenAndShow.questionCnt].langWord;	
	wordName=ListenAndShow.questionArr[ListenAndShow.questionCnt].word;
	quesId=ListenAndShow.questionArr[ListenAndShow.questionCnt].questionId;
	for(var i=0;i<4;i++)
	{
		var randNum=Math.floor(Math.random()*ListenAndShow.wordsData.length);
		if(ListenAndShow.arr.includes(ListenAndShow.wordsData[randNum]) || ListenAndShow.wordsData[randNum].langWord==ListenAndShow.questionArr[ListenAndShow.questionCnt].langWord)
		{
			i--;
			continue;
		}
		else
			ListenAndShow.arr.push(ListenAndShow.wordsData[randNum]);		
	}
	ListenAndShow.arr.push(ListenAndShow.questionArr[ListenAndShow.questionCnt]);
}

ListenAndShow.checkAnswer=function(id)
{
	var data,div,parentEle,word,wordList=[];
	ListenAndShow.gamePlayedFlag=true;
	ListenAndShow.attemptCount++;
	data=document.getElementById(id).getAttribute('data');
	$('#'+id).parent().css({'pointer-events':'none','opacity':'0.5'});
	
	document.getElementById('playSound').pause();
	if(data==document.getElementById('question').innerHTML)
	{
		//$('.bubbleClass').stop(true,false);
		$('.bubble').css({'pointer-events':'none'});
		$('#soundImgDiv').css({'pointer-events':'none'});
		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='bottom:-8.5vh;color:black;right:-1vw;font-size:4.5vw'>"+data+"</sub>";
			for(var i=0;i<wordList.length;i++)
			{
				parentEle=document.getElementById('words');
				div=document.createElement('div');
				div.setAttribute('id','spanDiv'+i);
				div.setAttribute('class','relatedWords');
				div.setAttribute('data',wordList[i].sound);
				div.setAttribute('onclick','ListenAndShow.playClickedWordsSnd(this.id);');
				word=wordList[i].word;
				div.innerHTML="<strong style='color:rgb(221,19,123)'>"+word.substring(0, document.getElementById(id).innerHTML.length)+"</strong>"+word.substring(document.getElementById(id).innerHTML.length, word.length);//to get the blend and remaining letters of sentence substr is used blend is added in strong tag
				ListenAndShow.soundArr.push(wordList[i].sound);
				parentEle.appendChild(div);
				$('.relatedWords').css({'pointer-events':'none'});
			}
			document.getElementById('suffix').style.display='block';
			document.getElementById('words').style.display='block';
			//document.getElementById('image').style.display='none';	
			ListenAndShow.loadmetaDataFlag=true;
			source=ListenAndShow.soundArr[ListenAndShow.instructionCnt];
			callback=ListenAndShow.playWordSound;
			ListenAndShow.getDuration(source,callback);
		}
		else
		{
			document.getElementById(id).removeAttribute('data-target','#myModal');
			ListenAndShow.nextQuestionTimeout=setTimeout(function()
			{
				ListenAndShow.nextQuestion();
			},1000);
		}
		if(!ListenAndShow.practiceFlag)
			scoredMarks=10;
		else
		{
			if(ListenAndShow.attemptCount==1)
				scoredMarks=10;
			else if(ListenAndShow.attemptCount==2)
				scoredMarks=5;
		}
		ListenAndShow.wordsLearnedFlag=true;
	}
	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');
		if(!ListenAndShow.practiceFlag)
		{
			document.getElementById('playSound').src=Utils.Path+'sounds/instruction/Try_again.mp3';
			document.getElementById('playSound').play();
			if(!ListenAndShow.wordsLearnedFlag)
				scoredMarks=0;
		}
		else
		{
			if(ListenAndShow.attemptCount>=2)
			{
				$('.bubble').css({'pointer-events':'none'});
				scoredMarks=0;
				document.getElementById('playSound').src=Utils.Path+'sounds/instruction/wrongbeat3.mp3';
				ListenAndShow.nextQuestionTimeout=setTimeout(function()
				{
					ListenAndShow.nextQuestion();
				},1000);
			}
			else
				document.getElementById('playSound').src=Utils.Path+'sounds/instruction/Try_again.mp3';
			document.getElementById('playSound').play();
		}
	}
}
//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;
	ListenAndShow.attemptCount=0;
	document.getElementById('bubbleDiv').innerHTML='';
	document.getElementById('words').innerHTML='';
	//document.getElementById('image').style.display='none';
	$('.suffixAndWord').css({'display':'block'});
	$('.bubble').css({'pointer-events':'auto'});
	$('#soundImgDiv').css({'pointer-events':'auto'});
	$('#myModal').modal('hide');
	document.getElementById('playSound').pause();
}
ListenAndShow.nextQuestion=function()
{
	ListenAndShow.calculateScore();
	ListenAndShow.questionCnt++;
	if(ListenAndShow.questionCnt>=ListenAndShow.questionArr.length)
	{
		ListenAndShow.AcknowledgementPage();
		clearTimeout(ListenAndShow.soundTimeout);
		ListenAndShow.gamePlayedFlag=false;
		document.getElementById('playSound').pause();
		gameOver.innerHTML=ListenAndShow.hardCodedData.gameOver;
		document.getElementById('bubbleDivPage').style.display="none";
		document.getElementById('question').innerHTML='';
		document.getElementById('endpage').style.display="block";
	}
	else
	{
		ListenAndShow.resetVariables();
		ListenAndShow.NextPage();
	}
}
ListenAndShow.calculateScore=function()
{
	if(Utils.mobileDeviceFlag && ListenAndShow.gamePlayedFlag==false)
	{
		scoredMarks=-1;
		console.log(resId,quesId,scoredMarks,totalMarks,2,startTime);
		Android.addScore(resId,quesId,scoredMarks,totalMarks,2,startTime);
	}
	else if(Utils.mobileDeviceFlag)
	{
		Android.addScore(resId,quesId,scoredMarks,totalMarks,2,startTime);
		console.log(resId,quesId,scoredMarks,totalMarks,2,startTime);
	}
	if(Utils.mobileDeviceFlag && ListenAndShow.wordsLearnedFlag)
		Android.addLearntData(wordName,totalNos,wordType);
	console.log(wordName,totalNos,wordType);
}
ListenAndShow.AcknowledgementPage=function()
{
	var i=0,div;
	for(i=0;i<Object.keys(ListenAndShow.AcknowledgementPageData).length;i++)
	{
		div=document.createElement('div');
		div.className="ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML=Object.keys(ListenAndShow.AcknowledgementPageData)[i]+" : "+Object.values(ListenAndShow.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div=document.createElement('div');
	div.className="ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=ListenAndShow.hardCodedData['createdOn'];
	acknowledgementDiv.appendChild(div);
}

ListenAndShow.playAgain=function()
{
	ListenAndShow.initialiseVar();
	ListenAndShow.resetVariables();
	document.getElementById("endpage").style.display="none";
	document.getElementById('bubbleDivPage').style.display='block';
	document.getElementById('question').style.visibility='visible';
	$('#acknowledgementDiv').empty();
	document.getElementById('acknowledgementDiv').style.visibility='hidden';
	ListenAndShow.NextPage();
}
ListenAndShow.showCredits=function()
{
	document.getElementById("acknowledgementDiv").style.visibility="visible";
}

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.backToHome=function()
{
	if(Utils.mobileDeviceFlag && ListenAndShow.gamePlayedFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,2,startTime);
	if(!ListenAndShow.practiceFlag)
	{
		if(ListenAndShow.chartFlag)
		{
			ListenAndShow.chartFlag=false;
			document.getElementById('bubbleDivPage').style.display='none';
			document.getElementById('alphabetChartDiv').style.display='block';
			document.getElementById('question').innerHTML=''
			document.getElementById("endpage").style.display="none";
			$('#acknowledgementDiv').empty();
			ListenAndShow.initialiseVar();
			ListenAndShow.resetVariables();
		}
		else
			location.reload();
	}
	else
		location.reload();
	
	
}
ListenAndShow.playQuestionAudio=function()
{
	document.getElementById('playSound').src="sounds/"+ListenAndShow.questionArr[ListenAndShow.questionCnt].langSound;
	document.getElementById('playSound').play();
}
/* ListenAndShow.totalWordsLength=function()
{
	var totalLength=0;
	for(var i=0;i<ListenAndShow.wordsData.length;i++)
	{
		for(var j=0;j<ListenAndShow.wordsData[i].list.length;j++)
			totalLength++;
	}
	console.log(totalLength);
} */