WordSearch={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0,levelNo;
var correctCnt=0,skipCnt=0,countDown=60;
WordSearch.queArr=[];
WordSearch.idArr=[];
WordSearch.homeFlag="goback";
$(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)
		Utils.Path=Android.getMediaPath(""); */
	setTimeout(function()
	{
		$("#coverpage").show();
		$("#gamepage,#modalPage,#widgetDiv,#middlepage,#homeImg").hide();
		WordSearch.setImages();
		WordSearch.createMiddlePageDivs();
	},300);
});
WordSearch.setImages=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+"images/Cover.png)";
	$("#homeImg").prop("src","images/Home.png");
	$("#logoImg").prop("src","images/logo.png");
	$("#playImg").prop("src","images/Play.png");
	$("#reloadImg").prop("src","images/reload.png");
	$("#checkImg").prop("src","images/Done.png");
	$("#characterImg").prop("src","images/standingBoy.png");
}
WordSearch.createMiddlePageDivs=function()						//creating level Divs
{
	var levelDiv,levelImg;
	for(var i=0;i<3;i++)
	{
		levelDiv=document.createElement("div");
		levelDiv.setAttribute("id","levelDiv"+i);
		levelDiv.setAttribute("class","noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
		document.getElementById("middlepage").append(levelDiv);

		levelImg=document.createElement("img");
		levelImg.setAttribute("id","levelImg"+i);
		levelImg.setAttribute("class","img-responsive noPadding col-lg-10 col-md-10 col-xs-10 col-sm-10");
		levelImg.setAttribute("src",Utils.Path+"images/"+WordSearch.levelImages.imgName+i+WordSearch.levelImages.imgType);
		levelImg.setAttribute("onclick","WordSearch.selectLevel(this)");
		levelDiv.appendChild(levelImg);
		$(levelImg).data("levelNum",i);
	}
}
WordSearch.playGame=function()
{
	WordSearch.homeFlag="goback";
	document.getElementById("playSound").pause();	
	$("#modalDiv").removeClass("animated zoomIn");
	clearInterval(WordSearch.Timer);
	WordSearch.queArr=[];
	countDown=60;
	$("#modalPage,#coverpage,#gamepage,#questionSet").hide();
	$("#widgetDiv,#middlepage,#homeImg").show();
	document.body.style.backgroundImage="url("+Utils.Path+"images/BG.png)";
}
WordSearch.selectLevel=function(element)							//select level
{
	clearTimeout(WordSearch.autoCheck);
	levelNo=$(element).data("levelNum");
	$("#middlepage").hide();
	$("#gamepage,#questionSet").show();
	$("#characterImg").prop("src","images/standingBoy.png");
	WordSearch.createLetterDivs(WordSearch.levels[levelNo].rows,WordSearch.levels[levelNo].cols,WordSearch.levels[levelNo].className);
	$("#counterDiv").text(countDown);
	WordSearch.createQuestionSetDivs();
	WordSearch.showWordsInGrid();
}
WordSearch.createLetterDivs=function(rows,cols,className)			//creating letter Divs
{
	var mainDiv,letterDiv,letterNum=1;
	$("#gridDiv").text("");
	for(var i=0;i<rows;i++)
	{
		mainDiv=document.createElement("div");
		mainDiv.setAttribute("id","mainDiv"+i);
		mainDiv.setAttribute("class","noPadding displayClass col-lg-12 col-md-12 col-xs-12 col-sm-12");
		document.getElementById("gridDiv").append(mainDiv);
		for(j=0;j<cols;j++)
		{
			letterDiv=document.createElement("div");
			letterDiv.setAttribute("id","letterDiv"+letterNum);
			letterDiv.setAttribute("class","noPadding balloonClass "+className);
			var randomBalloon=Math.floor((Math.random()*(5-1))+1);
			letterDiv.style.backgroundImage="url("+Utils.Path+"images/"+WordSearch.balloonImage.imgName+randomBalloon+WordSearch.balloonImage.imgType+")";
			letterDiv.setAttribute("onclick","WordSearch.selectLetter(this)");
			mainDiv.append(letterDiv);
			letterNum++;
		}
	}
}
WordSearch.createQuestionSetDivs=function()						//create word Divs
{
	var quesDiv,questions;
	$("#questionSet").text("");
	WordSearch.queArr=populate(WordSearch.Data,WordSearch.queArr,WordSearch.levels[levelNo].words);
	questions=document.createElement("div");
	questions.setAttribute("id","questions");
	questions.setAttribute("class","noPadding "+WordSearch.levels[levelNo].questionClass);
	document.getElementById("questionSet").appendChild(questions);
	for(var i=0;i<WordSearch.levels[levelNo].words;i++)
	{
		quesDiv=document.createElement("div");
		quesDiv.setAttribute("id","quesDiv"+i);
		quesDiv.setAttribute("class","noPadding col-xs-1 col-sm-1 col-md-1 col-lg-1 wordsClass");
		questions.appendChild(quesDiv);
	}
	for(var i=0;i<WordSearch.levels[levelNo].words;i++)						//display question Set
		$("#quesDiv"+i).text(WordSearch.queArr[i]);
}
WordSearch.showWordsInGrid=function()									//place Words into Grid
{
	var randomIndex=0,splitQueArr=[],indexArray=[],letterNum=1,randomLetter,wholeSplitArr=[],jodAksharFlag=false;
	correctCnt=0,jodAksharArr=[];
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	WordSearch.homeFlag="selectLevel";
	$(".wordsClass").css("text-decoration","none");
	$("#checkDiv").css("pointer-events","none");
	if(WordSearch.Timer)
	{
		clearInterval(WordSearch.Timer);
		WordSearch.Timer=null;
	}
	WordSearch.Timer=setInterval(function()
	{
		countDown-=1;
		$("#counterDiv").text(countDown);
		if(countDown==0)
		{
			clearInterval(WordSearch.Timer);
			WordSearch.showModal();
		}
	},1000);
	if(levelNo==0)
	{
		$(".balloonClass").css("font-size","3.5vw");
		$(".balloonClass").css("margin","1vw");
	}
	else if(levelNo==1)
	{
		$(".balloonClass").css("margin-left","2vw");
		$(".balloonClass").css("margin-top","1vh");
		$(".balloonClass").css("width","7vw");
	}
	else if(levelNo==2)
	{
		$(".balloonClass").css("margin-left","2vw");
		$(".balloonClass").css("margin-top","1vh");
		$(".balloonClass").css("width","12vw");
	}
	//console.log(WordSearch.queArr);
	for(var i=0;i<WordSearch.queArr.length;i++)
	{
		jodAksharFlag=false;
		jodAksharArr=[];
		index=0;
		idx=0;
		splitQueArr=WordSearch.queArr[i].split("");
		if(splitQueArr.includes("्"))
			jodAksharFlag=true;
		for(var j=0;j<WordSearch.queArr[i].length;j++)						//get joined kanhamatra array
		{
			while(WordSearch.KanhaMatraArr.includes(splitQueArr[j]))
			{
				if(splitQueArr[j]=="्")
					jodAksharArr.push(j);
				splitQueArr[j-1]=splitQueArr[j-1]+splitQueArr[j];
				splitQueArr.splice(j,1);
			}
			
		}
		if(jodAksharFlag)													//get jodakshar array
		{
			/* var diff=0,str="";
			if(jodAksharArr.length>1)
			{
				for(var j=0;j<jodAksharArr.length;j++)		
				{
					diff=splitQueArr.indexOf(jodAksharArr[j])-diff;
					if(jodAksharArr[j]==jodAksharArr[j+1])
						diff=1;
				}					
			}
			for(var j=0;j<jodAksharArr.length;j++)								
			{
				index=splitQueArr.indexOf(jodAksharArr[j]);
				diffIndex=index;
				if(diff==1)
				{
					for(var k=0;k<jodAksharArr.length+1;k++)
					{	str=str+splitQueArr[diffIndex];
						diffIndex++;
					}
					splitQueArr.splice(index,jodAksharArr.length+1,str);
					break;
				}
				else
				{
					splitQueArr[index]=splitQueArr[index]+splitQueArr[index+1];
					splitQueArr.splice(index+1,1);
				}
				
			} */
			for(var k=0;k<jodAksharArr.length;k++)
			{
				idx=jodAksharArr[k];
				idx=idx-k;
				splitQueArr[idx-1]=(splitQueArr[idx-1].concat(splitQueArr[idx]));
				splitQueArr.splice(idx,1);
			}
		}
		console.log(splitQueArr);
		for(j=0;j<splitQueArr.length;j++)									//gets random indices
		{
			randomIndex=Math.floor((Math.random()*(WordSearch.levels[levelNo].rows*WordSearch.levels[levelNo].cols)+1));
			while($.inArray(randomIndex,indexArray)!==-1)
				randomIndex=Math.floor((Math.random()*(WordSearch.levels[levelNo].rows*WordSearch.levels[levelNo].cols)+1));
			indexArray.push(randomIndex);
			wholeSplitArr.push(splitQueArr[j]);
		}
	}
	shuffleArray(wholeSplitArr);
	
	for(var i=0;i<wholeSplitArr.length;i++)									//display Letters in different positions
		$("#letterDiv"+indexArray[i]).text(wholeSplitArr[i]);
		
	for(j=0;j<WordSearch.levels[levelNo].rows*WordSearch.levels[levelNo].cols;j++)	//display remainining Letters			
	{
		if($("#letterDiv"+letterNum).text()=="")
		{
			randomLetter=Math.floor(Math.random()*WordSearch.mulakshareArr.length);
			while($.inArray(WordSearch.mulakshareArr[randomLetter],wholeSplitArr)!==-1)
				randomLetter=Math.floor(Math.random()*WordSearch.mulakshareArr.length);
			$("#letterDiv"+letterNum).text(WordSearch.mulakshareArr[randomLetter]);
		}
		letterNum++;
	}
}
WordSearch.selectLetter=function(str)								//select letters from grid
{
	WordSearch.idArr.push(str.id);
	$("#checkDiv").css("pointer-events","auto");
	$("#characterImg").prop("src","images/boy.gif");
	document.getElementById("playSound").pause();
	document.getElementById("playSound").src=Utils.Path+"sounds/ting.mp3";
	document.getElementById("playSound").play();
	$(str).css("background-color","yellow");
	if(WordSearch.autoCheck)
	{
		clearTimeout(WordSearch.autoCheck);
		WordSearch.autoCheck=null;
	}
	WordSearch.autoCheck=setTimeout(function(){WordSearch.checkAnswer();},3000);
}
WordSearch.checkAnswer=function()									//check answer
{
	var answer="";
	clearTimeout(WordSearch.autoCheck);
	$("#gridDiv").css("pointer-events","none");
	for(var i=0;i<WordSearch.idArr.length;i++)
		answer+=$("#"+WordSearch.idArr[i]).text();
	document.getElementById("playSound").pause();
	$("#checkDiv").css("pointer-events","none");
	console.log(answer);
	if(WordSearch.queArr.includes(answer))
	{
		scoredMarks=10;
		for(var i=0;i<WordSearch.idArr.length;i++)
		{
			$("#"+WordSearch.idArr[i]).css("background-color","green");
			/* $("#"+WordSearch.idArr[i]).css("opacity","0.6"); */
			$("#"+WordSearch.idArr[i]).addClass("animated fadeOutUp");
			$("#"+WordSearch.idArr[i]).css("pointer-events","none");
		}
		document.getElementById("playSound").src=Utils.Path+WordSearch.Sound[0];
		document.getElementById("playSound").play();
		$("#characterImg").prop("src",Utils.Path+WordSearch.Image[0]);
		correctCnt++;
		for(var i=0;i<$("#questions").children().length;i++)
		{
			if($("#quesDiv"+i).text()==answer)
			{
				$("#quesDiv"+i).css("text-decoration","line-through");
				break;
			}
		}
		if(WordSearch.nextQueTimer)
		{
			clearTimeout(WordSearch.nextQueTimer);
			WordSearch.nextQueTimer=null;
		}
		if(correctCnt==WordSearch.levels[levelNo].words)
			WordSearch.showModal();
	}
	else
	{
		scoredMarks=0;
		for(var i=0;i<WordSearch.idArr.length;i++)
		{
			$("#"+WordSearch.idArr[i]).css("background-color","red");
			$("#"+WordSearch.idArr[i]).addClass("animated tada");
		}
		document.getElementById("playSound").src=Utils.Path+WordSearch.Sound[1];
		document.getElementById("playSound").play();
		$("#characterImg").prop("src",Utils.Path+WordSearch.Image[1]);
		setTimeout(function(){
			for(var i=0;i<WordSearch.idArr.length;i++)
			{
				$("#"+WordSearch.idArr[i]).css("background-color","transparent");
				$("#"+WordSearch.idArr[i]).removeClass("animated tada");
			}
		},1000);
	}
	setTimeout(function(){
			$("#characterImg").prop("src",Utils.Path+"images/standingBoy.png");
			$("#gridDiv").css("pointer-events","auto");
			WordSearch.idArr=[];
		},1000);
	console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
}
WordSearch.nextQuestion=function()											//display next Question
{
	clearTimeout(WordSearch.nextQueTimer);
	skipCnt++;
	WordSearch.resetAll();
	$("#checkDiv").css("pointer-events","auto");
	$(".balloonClass").css("pointer-events","auto");
	document.getElementById("playSound").pause();
	WordSearch.createLetterDivs(WordSearch.levels[levelNo].rows,WordSearch.levels[levelNo].cols,WordSearch.levels[levelNo].className);
	WordSearch.createQuestionSetDivs();
	WordSearch.showWordsInGrid();
}
WordSearch.playAgain=function()		
{
	skipCnt=0;
	correctCnt=0;
	$("#modalDiv").removeClass("animated zoomIn");
	$("#modalPage,#middlepage").hide();
	$("#gamepage,#questionSet,#widgetDiv,#homeImg").show();
	document.getElementById("message").style.visibility="hidden";
	WordSearch.createLetterDivs(WordSearch.levels[levelNo].rows,WordSearch.levels[levelNo].cols,WordSearch.levels[levelNo].className);
	WordSearch.resetAll();
	WordSearch.createQuestionSetDivs();
	WordSearch.showWordsInGrid();
}
WordSearch.resetAll=function()
{
	countDown=60;
	clearInterval(WordSearch.Timer);
	clearTimeout(WordSearch.autoCheck);
	WordSearch.queArr=[];
	WordSearch.idArr=[];
	$("#counterDiv").text(countDown);
	WordSearch.queArr=populate(WordSearch.Data,WordSearch.queArr,WordSearch.levels[levelNo].words);
}
WordSearch.callHome=function()
{
	if(WordSearch.homeFlag=="selectLevel")
		WordSearch.playGame();
	else
		location.reload(true);
}
WordSearch.showModal=function()
{
	clearInterval(WordSearch.Timer);
	$("#modalPage").show();
	$("#modalDiv").addClass("animated zoomIn");
	$("#playAgainButton").text(WordSearch.hardcoded.playAgainButton);
	$("#chooseLevelButton").text(WordSearch.hardcoded.chooseLevelButton);
	$("#gameOverDiv").text(WordSearch.hardcoded.gameOver);
	$("#timeDiv").text("Time Taken : "+(60-countDown)+" Sec");
	$("#totalWordsDiv").text("Total Words : "+WordSearch.levels[levelNo].words);
	$("#correctwordsDiv").text("Correct Words : "+correctCnt);
}