//9 oct

var FindWord={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
FindWord.playedGameFlag=false;
var resId=0,quesId=0,startTime=0,scoredMarks=0,totalMarks=10,attempt='',label=[];
FindWord.totalscore=0;
FindWord.indexArray=[];
FindWord.nextTimeout=0;
FindWord.questionArr=[];
FindWord.questionCnt=0;
//FindWord.levelIndexFlag=false;
getDurationFlag=false;

$(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()
{
	document.body.style.backgroundImage = "url("+Utils.Path+FindWord.hardCodedData.cover_page_L1+")";
	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('playAgain').src=Utils.Path+"images/playAgain.png";
	document.getElementById('credit').src=Utils.Path+"images/credits.png";
	document.getElementById('nextQueBtn').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'+")";
	getUniqueValArr(FindWord.wordsData,FindWord.questionArr,5);
	FindWord.createDiv();
	FindWord.setQuestionAndOption();
	
}

//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("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();
	document.getElementById('suffixCnt').classList.add('bounceIn');
	setTimeout(function()
	{
		document.getElementById('suffixCnt').classList.remove('bounceIn');
	},500);
	
	document.getElementById("suffixPart").style.display='block';
	document.getElementById("suffixValue").innerHTML=FindWord.questionArr[FindWord.questionCnt].prnounciation;
	FindWord.suffixCount=Math.floor(Math.random() * 4) + 2;
	document.getElementById('suffixCnt').innerHTML=FindWord.suffixCount;
	
	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.length-1)) + 0);
		if(FindWord.indexArray.includes(num) || tempArr2.includes(indexOfSuffix) || tempArr.includes(num) || FindWord.wordsData[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[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);
	attempt+=FindWord.questionArr[FindWord.questionCnt].word+"#";;
}

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

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);
}

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

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

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'});
	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();
};
//results
FindWord.calculateResult=function()
{
	attempt=attempt.slice(0,attempt.length-1);
	console.log(attempt);
	if(FindWord.correct==FindWord.suffixCount && FindWord.wrong==0)
		FindWord.totalscore+=10;
	
	else if(FindWord.correct==FindWord.suffixCount && FindWord.wrong!=0)
	{
		FindWord.totalscore+=5;
	}
}

FindWord.next=function()
{
	FindWord.calculateScore();
	clearTimeout(FindWord.nextTimeout);
	FindWord.playedGameFlag=false;
	FindWord.questionCnt++;
	if(FindWord.questionCnt>=5)
	{
		FindWord.AcknowledgementPage();
		document.getElementById("playSound").pause();
		gameOver.innerHTML=FindWord.hardCodedData.gameOver;
		document.getElementById('endpage').style.display='block';
		document.getElementById('gamePage').style.display='none';
		FindWord.questionCnt=0;
		FindWord.questionArr=[];
	}
	else
	{
		FindWord.reset();
		FindWord.setQuestionAndOption();
	}
}
FindWord.calculateScore=function()
{
	console.log(attempt);
	if(Utils.mobileDeviceFlag && FindWord.playedGameFlag)
	{
		scoredMarks=FindWord.correct;
		attempt=attempt.slice(0,attempt.length-1);
		Android.addScore(resId,quesId,scoredMarks,FindWord.suffixCount,1,startTime,attempt);
		console.log(resId,quesId,scoredMarks,FindWord.suffixCount,1,startTime,attempt);
	}
	else if(Utils.mobileDeviceFlag && FindWord.playedGameFlag==false)  
	{
		scoredMarks=-1;
		attempt='';
		Android.addScore(resId,quesId,scoredMarks,FindWord.suffixCount,1,startTime,attempt);
		console.log(resId,quesId,scoredMarks,FindWord.suffixCount,1,startTime,attempt);
	}
	
}
FindWord.reset=function()
{
	FindWord.correct=0;
	FindWord.wrong=0;
	attempt='';
	nextQueFlag=true;
	document.getElementById('suffixCnt').classList.remove('bounceIn');
	$('#sound').css('pointer-events','auto');
	FindWord.indexArray=[],FindWord.suffixCount=0;
	clearTimeout(FindWord.nextTimeout);
	document.getElementById("playSound").pause();
	document.getElementById('ansImgDiv').style.visibility="hidden";
	document.getElementById('suffixCnt').style.visibility='visible';
	document.getElementById('suffixValue').style.visibility='visible';
	$('.spanclass1').css('pointer-events','auto');
	$('.spanclass1').css('color','white');
}

FindWord.callHome=function()
{
	document.getElementById("playSound").pause();
	
	clearTimeout(FindWord.nextTimeout);
	//document.body.style.backgroundImage = "url("+Utils.Path+'images/levelBg.png'+")";
	//if(document.getElementById("levelDiv").style.display=="block")
		location.reload();
	//else
	//{
		//document.getElementById("gamePage").style.display="none";
		//FindWord.questionCnt=0;
		//document.getElementById("levelDiv").style.display="block";
		//document.getElementById("endpage").style.display="none";
		//console.log(resId,quesId,FindWord.correct,FindWord.suffixCount,parseInt(FindWord.levelNo)+1,startTime,attempt);
		if(Utils.mobileDeviceFlag && FindWord.playedGameFlag)
		{
			attempt=attempt.slice(0,attempt.length-1);	
			Android.addScore(resId,quesId,FindWord.correct,FindWord.suffixCount,1,startTime,attempt);
		}
		else if(Utils.mobileDeviceFlag && FindWord.playedGameFlag)
		{
			attempt=0;
			Android.addScore(resId,quesId,FindWord.correct,FindWord.suffixCount,1,startTime,attempt);
		}
		
	//}
}
FindWord.AcknowledgementPage=function()
{
	var i=0,div;
	document.getElementById("endpage").style.display="block";
	console.log(Object.keys(FindWord.AcknowledgementPageData).length)
	for(i=0;i<Object.keys(FindWord.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(FindWord.AcknowledgementPageData)[i]+" : "+Object.values(FindWord.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=FindWord.hardCodedData['createdOn'];
	acknowledgementDiv.appendChild(div);

}
FindWord.playAgain=function()
{
	getUniqueValArr(FindWord.wordsData,FindWord.questionArr,5);
	document.getElementById('acknowledgementDiv').style.visibility="hidden";
	$('#acknowledgementDiv').empty();
	FindWord.reset();
	FindWord.setQuestionAndOption();
	document.getElementById("gamePage").style.display="block";
	document.getElementById("endpage").style.display="none";
}
FindWord.credits=function()
{
	document.getElementById("acknowledgementDiv").style.visibility="visible";
}
