//9 oct

var FindWord={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var resId=0,quesId=0,startTime=0,scoredMarks=0,totalMarks=10,label='';
FindWord.totalscore=0;
FindWord.indexArray=[];
FindWord.nextTimeout=0;
FindWord.questionArr=[];
FindWord.questionCnt=0;
FindWord.correctCnt=0;
FindWord.levelNo=0;
FindWord.playedGameFlag=false;
FindWord.attemptCnt=0;
FindWord.seconds=0;
FindWord.levelIndexFlag=false;
getDurationFlag=false;
FindWord.answerAudio=0;
var nextQueFlag=true;
$(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)
	{
		FindWord.levelNo=Android.getLevel(); 
		FindWord.levelIndexFlag=true;
	}
	setTimeout(function()
	{
		FindWord.setImages();
		if(FindWord.hardCodedData['languageFont']!=null)
			setFontFamilyForLang("fonts/"+FindWord.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");            
}

FindWord.setImages=function()
{
	if(FindWord.levelIndexFlag)
	{
		FindWord.levelNo=FindWord.levelNo-1;	
	}
	else
	{
		FindWord.levelNo=Math.floor(Math.random()*2)+1;
		FindWord.levelNo=FindWord.levelNo-1;
	}
	if(FindWord.levelNo==0)
		document.body.style.backgroundImage = "url("+Utils.Path+FindWord.hardCodedData.cover_page_L1+")";
	else
		document.body.style.backgroundImage = "url("+Utils.Path+FindWord.hardCodedData.cover_page_L2+")";
	document.getElementById('home').src=Utils.Path+"images/Home.png";
	document.getElementById('logo').src=Utils.Path+"images/logo.png";
	document.getElementById('playImage').src=Utils.Path+"images/Play.png";
	document.getElementById('playSoundBtn').src=Utils.Path+"images/Sound.png";
	/* document.getElementById('level1').src=Utils.Path+"images/level1.png";
	document.getElementById('level2').src=Utils.Path+"images/level2.png";
	document.getElementById('level1').setAttribute('data',0);
	document.getElementById('level2').setAttribute('data',1); */
	document.getElementById('nextQueBtn').src=Utils.Path+"images/Next.png";
	document.getElementById('next').src=Utils.Path+"images/Next.png";
	document.getElementById('suffixPart').style.backgroundImage="url("+Utils.Path+'images/board.png'+")";
}

// set suffix and sound
FindWord.playgame=function()
{
	FindWord.correct=0;
	FindWord.wrong=0;
	FindWord.round++;
	//document.getElementById("home").style.visibility="visible";
	document.getElementById("coverPage").style.display="none";
	document.getElementById("gamePage").style.display="block";
	// document.getElementById("levelDiv").style.display="block";
	document.getElementById('endpage').style.display="none";
	document.getElementById('suffixCnt').classList.add('bounceIn');
	document.body.style.backgroundImage = "url("+Utils.Path+'images/bg.png'+")";
	//document.body.style.backgroundImage = "url("+Utils.Path+'images/levelBg.png'+")";
	getUniqueValArr(FindWord.wordsData[FindWord.levelNo].data,FindWord.questionArr,5);
	FindWord.createDiv();
	FindWord.setQuestionAndOption();
	FindWord.createStars();

}
//create 16 div
FindWord.createDiv=function()			
{
	var parentDiv,wordDiv,outerDiv,wordSpan;
	parentDiv=document.getElementById("grid");
	
	for(var j=1;j<=16;j++)
	{
		wordSpan=document.createElement('span');
		wordSpan.setAttribute("id","word"+j);
		//wordSpan.setAttribute("class","col-xs-3 col-sm-3 col-md-3 col-lg-3 nopadding");
		wordSpan.setAttribute("onclick","FindWord.checkSuffix(this.id)");
		$(wordSpan).css('background-image',"url("+Utils.Path+'images/block.png'+")");
		$(wordSpan).css('background-repeat',"no-repeat");
		parentDiv.appendChild(wordSpan);
	}	
}
//set Question and other option
FindWord.setQuestionAndOption=function()
{
	var d,randomGridDiv=0,randomQuestion=0,num=0,indexOfSuffix,tempArr2=[],tempArr=[],gridCnt=16;
	d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	FindWord.reset();
	//$('.spanclass1').css('pointer-events','none');
	document.getElementById('suffixCnt').classList.add('bounceIn');
	setTimeout(function()
	{
		document.getElementById('suffixCnt').classList.remove('bounceIn');
	},500);
	if(FindWord.levelNo=='1')
	{
		document.getElementById("suffixPart").style.display='block';
		document.getElementById("suffixValue").innerHTML=FindWord.questionArr[FindWord.questionCnt].word;
		FindWord.suffixCount=Math.floor(Math.random() * 4) + 2;
		document.getElementById('suffixCnt').innerHTML=FindWord.suffixCount;
	}
	else
	{
		document.getElementById("suffixPart").style.display='none';
		FindWord.suffixCount=1;
	}
	for(var i=0;i<FindWord.suffixCount;i++)
	{
		randomGridDiv=(Math.floor(Math.random()*gridCnt)+1);
		if(FindWord.indexArray.includes(randomGridDiv))
		{
			i--;
			continue;
		}
		else
		{
			FindWord.indexArray[i]=randomGridDiv;
			document.getElementById("word"+randomGridDiv).setAttribute('class',"spanclass1 spanclass2 ");
			document.getElementById("word"+randomGridDiv).innerHTML=FindWord.questionArr[FindWord.questionCnt].word;
			document.getElementById("word"+randomGridDiv).setAttribute('index',randomGridDiv);
		}
	}
	for(var j=0;j<16-(FindWord.indexArray.length);j++)
	{
		num=(Math.floor(Math.random()*gridCnt)+1);
		indexOfSuffix=(Math.floor(Math.random() *(FindWord.wordsData[FindWord.levelNo].data.length-1)) + 0);
		if(FindWord.indexArray.includes(num) || tempArr2.includes(indexOfSuffix) || tempArr.includes(num) || FindWord.wordsData[FindWord.levelNo].data[indexOfSuffix]==FindWord.questionArr[FindWord.questionCnt])
		{
			j--;
			continue;
		}
		else
		{
			tempArr[j]=num;
			tempArr2[j]= indexOfSuffix;
			document.getElementById("word"+num).setAttribute('class'," spanclass1 spanclass2");
			document.getElementById("word"+num).innerHTML=FindWord.wordsData[FindWord.levelNo].data[indexOfSuffix].word;
			document.getElementById("word"+num).setAttribute('index',num);		
		}			
	}
	$(".spanclass1").css({pointerEvents:'none'});
	getDurationFlag=true;
	getDuration("sounds/"+FindWord.questionArr[FindWord.questionCnt].sound);
	quesId=parseInt(FindWord.questionArr[FindWord.questionCnt].questionId);
	label=FindWord.questionArr[FindWord.questionCnt].word;
}
function getDuration(src)
{
	var duration=0;
	if(getDurationFlag)
	{
		$('#playSound').on("loadedmetadata", function()
		{
			getDurationFlag=false;
			duration=$('#playSound').prop('duration');
			$('#playSound').unbind('loadedmetadata');
			FindWord.playInstruction(duration);
		});
	} 
	   $('#playSound').prop('src',src);
}

//on sound click
FindWord.playSound=function()
{
	document.getElementById('playSound').src="sounds/"+FindWord.questionArr[FindWord.questionCnt].sound;
	document.getElementById('playSound').play();
}

FindWord.playInstruction=function(duration)
{
	document.getElementById("playSound").play();
	FindWord.answerAudio=setTimeout(function()
	{
		$(".spanclass1").css({pointerEvents:'auto'});
		FindWord.startTimer();
	},duration*1000);
}

//check suffix right or wrong and move jerry
FindWord.checkSuffix=function(myID)
{
	var getClickedAttribute;
	FindWord.playedGameFlag=true;
	getClickedAttribute=document.getElementById(myID).getAttribute('index');
	clearInterval(FindWord.noResponseTimer);
	clearTimeout(FindWord.timeOut);
	$('#'+myID).css('pointer-events','none');
	//$('.spanclass1').css('pointer-events','none');
	//for correct suffix
	console.log(FindWord.indexArray);
	document.getElementById('playSound').src='sounds/Bell.mp3';
	document.getElementById('playSound').play();
	if(FindWord.indexArray.includes(Number(getClickedAttribute)))	
	{
		FindWord.correct++;
		document.getElementById(myID).style.color="#08e608";
		document.getElementById('suffixCnt').innerHTML=FindWord.indexArray.length-FindWord.correct;
		document.getElementById('suffixCnt').classList.add('bounceIn');
		setTimeout(function()
		{
			document.getElementById('suffixCnt').classList.remove('bounceIn');
		},500);
	}
	//for wrong suffix
	else 
	{
		FindWord.wrong++;
		$('#sound').css('pointer-events','none');
		scoredMarks=0;
		document.getElementById(myID).style.color="red";
		FindWord.answerwiseMessage('wrong.gif','wrong.mp3');
		FindWord.loadNextQue();
	}
	if(FindWord.correct==FindWord.suffixCount)
	{
		FindWord.correctCnt++;
		$('#sound').css('pointer-events','none');
		scoredMarks=10;
		FindWord.answerwiseMessage('rightAns.gif','CorrectSound.mp3');
		document.getElementById('suffixCnt').style.visibility='hidden';
		document.getElementById('suffixValue').style.visibility='hidden';
		FindWord.loadNextQue();
	}
}

FindWord.loadNextQue=function()
{
	if(FindWord.nextTimeout)
	{
		clearTimeout(FindWord.nextTimeout);
		FindWord.nextTimeout=null;
	}
	FindWord.nextTimeout=setTimeout(function()
	{
		FindWord.next();
	},3000);
}


FindWord.answerwiseMessage=function(imageName,soundName)
{
	$(".spanclass1").css({pointerEvents:'none'});
	console.log(resId,quesId,scoredMarks,totalMarks,parseInt(FindWord.levelNo)+1,startTime,label);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,quesId,scoredMarks,totalMarks,parseInt(FindWord.levelNo)+1,startTime,label);
	document.getElementById('ansImgDiv').style.visibility="visible";
	document.getElementById('ansImg').src=Utils.Path+"images/"+imageName;
	document.getElementById('playSound').src=Utils.Path+"sounds/"+soundName;
	document.getElementById('playSound').play();
};

FindWord.next=function()
{
	FindWord.attemptCnt++;
	FindWord.playedGameFlag=false;
	FindWord.questionCnt++;
	if(FindWord.questionCnt>=5)
	{
		FindWord.giveStars();
		clearInterval(FindWord.noResponseTimer);
		clearTimeout(FindWord.timeOut);
		clearTimeout(FindWord.nextTimeout);
		document.getElementById('nextDiv').classList.add('blink_me');
		document.getElementById("playSound").pause();
		if(FindWord.correctCnt>0)
		{
			document.getElementById('playSound').src="sounds/star"+FindWord.correctCnt+".mp3";
			document.getElementById('playSound').play();
		}
		document.getElementById('gamePage').style.display='none';
		document.getElementById('endpage').style.display='block';
		document.getElementById('gameOver').innerHTML=FindWord.hardCodedData.gameOver;
		if(Utils.mobileDeviceFlag){
			if(FindWord.levelNo=="1")
				Android.StudentCertification(FindWord.correctCnt,FindWord.attemptCnt,"9");
			else
				Android.StudentCertification(FindWord.correctCnt,FindWord.attemptCnt,"4");
		}
			
		FindWord.questionCnt=0;
		FindWord.correctCnt=0;
		FindWord.questionArr=[];
	}
	else
	{
		FindWord.reset();
		FindWord.setQuestionAndOption();
	}
}
FindWord.reset=function()
{
	FindWord.correct=0;
	FindWord.wrong=0;
	nextQueFlag=true;
	$("#starDiv").css("visibility","hidden");
	FindWord.indexArray=[],FindWord.suffixCount=0;
	$('#sound').css('pointer-events','auto');
	clearTimeout(FindWord.nextTimeout);
	clearInterval(FindWord.noResponseTimer);
	document.getElementById("playSound").pause();
	document.getElementById('suffixCnt').classList.remove('bounceIn');
	document.getElementById('ansImgDiv').style.visibility="hidden";
	document.getElementById('suffixCnt').style.visibility='visible';
	document.getElementById('suffixValue').style.visibility='visible';
	$(".spanclass2").css({'color':'white'});
	$('.spanclass1').css('pointer-events','auto');
}
FindWord.callHome=function()
{
	document.getElementById("playSound").pause();
	$("#starDiv").css("visibility","hidden");
	FindWord.questionCnt=0;
	clearInterval(FindWord.noResponseTimer);
	clearTimeout(FindWord.timeOut);
	document.body.style.backgroundImage = "url("+Utils.Path+'images/levelBg.png'+")";
	clearTimeout(FindWord.nextTimeout);
	if(document.getElementById("levelDiv").style.display=="block")
		location.reload();
	else
	{
		console.log(resId,quesId,scoredMarks,totalMarks,parseInt(FindWord.levelNo)+1,startTime,label);
		if(Utils.mobileDeviceFlag && FindWord.playedGameFlag)
			Android.addScore(resId,quesId,scoredMarks,totalMarks,parseInt(FindWord.levelNo)+1,startTime,label);
		document.getElementById("gamePage").style.display="none";
		document.getElementById("levelDiv").style.display="block";
		document.getElementById("endpage").style.display="none";
	}
}

FindWord.startTimer=function()
{
	if(FindWord.noResponseTimer)
	{
	clearInterval(FindWord.noResponseTimer);
	FindWord.noResponseTimer=null;
	FindWord.seconds=0;
	}	
	FindWord.noResponseTimer=setInterval(function() 
	{
		FindWord.seconds++;
		if(FindWord.seconds>=7)
		{
			document.getElementById("playSound").src=Utils.Path+"sounds/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(FindWord.noResponseTimer);
			FindWord.timeOut=setTimeout(function()
			{
				FindWord.seconds=0;
				FindWord.startTimer();
			},2000);
		}
	},1000);
} 
FindWord.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("visibility","hidden");
};

FindWord.giveStars=function()
{
	var fractionVar,i,numberOfStars=FindWord.correctCnt;
	for(i=1;i<=numberOfStars;i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/star1.png");
	$("#starDiv").css("visibility","visible");
};

FindWord.goNext=function()
{
	clearInterval(FindWord.noResponseTimer);
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}
