//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=1,quesId=0,label='';
ListenAndSpell.loadmetaDataFlag=false;
ListenAndSpell.gamePlayedFlag=false;
ListenAndSpell.startIndex=[];
ListenAndSpell.nextQuestionCnt=0;
ListenAndSpell.soundInterval=0;
ListenAndSpell.instructionCnt=0;
ListenAndSpell.queSnd=0;
ListenAndSpell.correctCnt=0;
ListenAndSpell.attemptCnt=0;
ListenAndSpell.seconds=0;
ListenAndSpell.AnsQuestionTimer=0;
ListenAndSpell.playAllSoundArr=[];
ListenAndSpell.questionArr=[];
ListenAndSpell.levelIndexFlag=true;
ListenAndSpell.levelNo=1;
ListenAndSpell.queCnt=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();
		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");            
}

//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('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('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.displayData=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.levelNo].data,ListenAndSpell.questionArr,5);
	ListenAndSpell.createDiv();
	ListenAndSpell.setQuestion();
	ListenAndSpell.createStars();
	/* getUniqueValArr(ListenAndSpell.data,ListenAndSpell.questionArr,5);
	ListenAndSpell.createDiv();
	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;
	ListenAndSpell.makeItQue=ListenAndSpell.questionArr[ListenAndSpell.queCnt].list[randomRhyme].sound;
	
	//document.getElementById('example').innerHTML=ListenAndSpell.data[randomWord].suffix;
	ListenAndSpell.queSnd=ListenAndSpell.questionArr[ListenAndSpell.queCnt].sound;
	ListenAndSpell.que=ListenAndSpell.questionArr[ListenAndSpell.queCnt].suffix.split("");
	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(ListenAndSpell.queSnd,"Make_it.mp3",ListenAndSpell.makeItQue);
	console.log(ListenAndSpell.playAllSoundArr);
	
	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.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.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.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)
	{
		clearTimeout(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
		{
			clearTimeout(ListenAndSpell.soundInterval);
			ListenAndSpell.soundInterval=null;
			$('#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);
		}
		if(ListenAndSpell.instructionCnt<=ListenAndSpell.que.length)
		{
			document.getElementById('letter'+(ListenAndSpell.instructionCnt-1)).style.color="black";
		}
	},duration*1500);
}

//on click of sound nd playing instruction
ListenAndSpell.playInstruction=function()
{
	clearTimeout(ListenAndSpell.AnsQuestionTimer);
	clearInterval(ListenAndSpell.noResponseTimer);
	clearTimeout(ListenAndSpell.timeOut);
	setTimeout(function()
	{
		document.getElementById('playSound').src="sounds/Make_it.mp3";
		document.getElementById('playSound').play();	
		setTimeout(function()
		{
			document.getElementById('playSound').src="sounds/"+ListenAndSpell.makeItQue;
			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);
}

//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;
	$('#sound').css({'pointer-events':'none'});
	clearInterval(ListenAndSpell.noResponseTimer);
	clearTimeout(ListenAndSpell.timeOut);
	clearTimeout(ListenAndSpell.AnsQuestionTimer);
	$('.options').css({'pointer-events':'none'});
	ListenAndSpell.gamePlayedFlag=true;
	ListenAndSpell.attemptCnt++;
	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])
	{
		scoredMarks=10;
		ListenAndSpell.correctCnt++;
		letter.innerHTML=clickedLetter;
		$(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/"+ListenAndSpell.correctSnd[randomSound];
		document.getElementById('playSound').play();
		ListenAndSpell.attemptFlag=false;
	}
	else
	{
		scoredMarks=0;
		ListenAndSpell.attemptFlag=true;
		$(letter).text(clickedLetter);
		$('#'+id).css({"color":"rgba(255, 0, 0)"});
		$(letter).css({"color":"rgba(255, 0, 0)"});
		randomSound=Math.floor(Math.random()*ListenAndSpell.wrongSnd.length);
		document.getElementById('playSound').src="sounds/"+ListenAndSpell.wrongSnd[randomSound];
		document.getElementById('playSound').play();
	}
	if(ListenAndSpell.nextQuesTimer)
	{
		clearTimeout(ListenAndSpell.nextQuesTimer);
		ListenAndSpell.nextQuesTimer=null;
	}
	ListenAndSpell.nextQuesTimer=setTimeout(function()
	{
		ListenAndSpell.Next();
	},3000);
}

//load new question
ListenAndSpell.Next=function()
{
	$('.options').css({'pointer-events':'none'});
	ListenAndSpell.nextQuestionCnt++;
	ListenAndSpell.queCnt++;
	ListenAndSpell.calculateScore();
	if(ListenAndSpell.nextQuestionCnt>=5)
	{
		ListenAndSpell.gamePlayedFlag=false;
		ListenAndSpell.giveStars();
		document.getElementById('nextDiv').classList.add('blink_me');
		clearTimeout(ListenAndSpell.nextQuesTimer);
		clearInterval(ListenAndSpell.soundInterval);
		clearInterval(ListenAndSpell.noResponseTimer);
		clearTimeout(ListenAndSpell.timeOut);
		document.getElementById('playSound').pause();
		if(ListenAndSpell.correctCnt>0)
		{
			document.getElementById('playSound').src="sounds/star"+ListenAndSpell.correctCnt+".mp3";
			document.getElementById('playSound').play();
		}
		document.getElementById('gamePage').style.display="none";
		document.getElementById('endpage').style.display="block";
		//document.getElementById('example').style.display="none";
		document.getElementById('gameOver').innerHTML=ListenAndSpell.hardCodedData.gameOver;
		if(Utils.mobileDeviceFlag)
			Android.StudentCertification(ListenAndSpell.correctCnt,ListenAndSpell.nextQuestionCnt,"5");
	}
	else
	{
		ListenAndSpell.reset();
		ListenAndSpell.setQuestion();
	}
}
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(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
}
ListenAndSpell.reset=function()
{
	$('.textSpan').remove();
	$('.optionsSpan').remove();
	$('#showWordDiv').empty();
	clearTimeout(ListenAndSpell.nextQuesTimer);
	document.getElementById('playSound').pause();
	ListenAndSpell.startIndex=[];
	ListenAndSpell.playAllSoundArr=[];
	$('.options').css('pointer-events','auto');
	ListenAndSpell.queWord=0;
	ListenAndSpell.instructionCnt=0;
	ListenAndSpell.gamePlayedFlag=false;
	clearInterval(ListenAndSpell.soundInterval);
	clearInterval(ListenAndSpell.noResponseTimer);
	ListenAndSpell.wrong=0;
	ListenAndSpell.correct=0;
}
ListenAndSpell.playAgain=function()
{
	ListenAndSpell.reset();
	ListenAndSpell.nextQuestionCnt=0;
	ListenAndSpell.queCnt=0;
	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)
	{
		scoredMarks=0;
		Android.addScore(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		console.log(resId,quesId,scoredMarks,totalMarks,1,startTime,label);
		ListenAndSpell.attemptFlag=false;
	}
}

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.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/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(ListenAndSpell.noResponseTimer);
			ListenAndSpell.timeOut=setTimeout(function()
			{
				ListenAndSpell.seconds=0;
				ListenAndSpell.startTimer();
			},2000);
		}
	},1000);
} 
ListenAndSpell.goNext=function()
{
	clearInterval(ListenAndSpell.noResponseTimer);
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}
