//10 October 2018
var CrumbleTumble = {};
var Utils = {};
Utils.Path='';
Utils.mobileDeviceFlag=false;
CrumbleTumble.nextQueFlag=false;
CrumbleTumble.ttsFlag=false;
CrumbleTumble.arrayOfInfo=[];
CrumbleTumble.counter=0;
CrumbleTumble.selectTimer=null;
CrumbleTumble.checkWordTimer=null;
CrumbleTumble.questioncnt=0;
CrumbleTumble.highlightCnt=0;
CrumbleTumble.ansString="";
CrumbleTumble.ans="";
CrumbleTumble.arrayOfTopPositions=[];
CrumbleTumble.arrayOfLeftPositions=[];
var questionId=0,startTime=0,scoredMarks=0,totalMarks=0,resId=0,level=0;
//function for loader
$(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("CrumbleTumble");  */
	setTimeout(function()
	{
		CrumbleTumble.init();
	},300);	
},300);

CrumbleTumble.init=function()
{
	$('#soundDiv,#nextGame').css('visibility','hidden');
	$('#gamePage,#endPage').hide();
	$('#conceptDiv').text(CrumbleTumble.hardcorded.conceptbytext);
	$('#prathamContentDiv').text(CrumbleTumble.hardcorded.contentteamtext);
	$('#developedByDiv').text(CrumbleTumble.hardcorded.developedbytext);
	$('#developerNameDiv').text(CrumbleTumble.hardcorded.developerName);
	CrumbleTumble.setImages();
	CrumbleTumble.setEventListeners();
	CrumbleTumble.copyJson=JSON.parse(JSON.stringify(CrumbleTumble.MakeItRight.obj));
};
//function to set images
CrumbleTumble.setImages=function()
{
	document.getElementById('play').src=Utils.Path+"images/Theek-Thak_Play.png";
	document.getElementById('homeImage').src=Utils.Path+"images/Theek-Thak_Home.png";
	document.getElementById('logoImage').src=Utils.Path+"images/logo.png";
	document.getElementById('sound').src=Utils.Path+"images/Theek-Thak_Sound.png";
	document.getElementById('next').src=Utils.Path+"images/Theek-Thak_Play.png";
	document.body.style.backgroundImage="url("+Utils.Path+"images/BG.jpg)";
};
 CrumbleTumble.setEventListeners=function()
{
	$("#next").on("click",function(){
		CrumbleTumble.resetData();
	});
	 $("#sound").on("click",function(){
		CrumbleTumble.selectWords();	
	});
};

//this function will execute on click of play button
CrumbleTumble.startGame=function()
{	
	$('#coverPage').hide();
	$('#gamePage').show();
	$("#homeButton").css('visibility','visible');
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	CrumbleTumble.createTopWords();
	CrumbleTumble.highLightTextWithAudio();
};
CrumbleTumble.selectWords=function()
{
	if(Utils.mobileDeviceFlag)
		Android.playTts(""+CrumbleTumble.arrayOfInfo[CrumbleTumble.counter],'eng');
	else 
		saySomething(""+CrumbleTumble.arrayOfInfo[CrumbleTumble.counter]);
};
CrumbleTumble.resetData=function()
{
	if(CrumbleTumble.checkWordTimer)
	{
		clearTimeout(CrumbleTumble.checkWordTimer);
		CrumbleTumble.checkWordTimer=null;
	}	
	if(CrumbleTumble.selectTimer)
	{
		clearTimeout(CrumbleTumble.selectTimer);
		CrumbleTumble.selectTimer=null;
	}
		
	if(CrumbleTumble.TtsIntervalTimer)
	{
		clearInterval(CrumbleTumble.TtsIntervalTimer);
		CrumbleTumble.TtsIntervalTimer=null;
	}
	$("#sentenceDiv,#dropWords").empty();
	$('#soundDiv,#next').css('visibility','hidden');  
	CrumbleTumble.randomIndex=0;
	CrumbleTumble.splitWords=[];
	CrumbleTumble.currentSentence;
	CrumbleTumble.sentenceWordCnt;
	CrumbleTumble.Answer=[];
	CrumbleTumble.arrayOfInfo=[];
	CrumbleTumble.shuffleMixWords=[];
	CrumbleTumble.planeWordsArray=[];
	CrumbleTumble.charCnt=0;
	CrumbleTumble.symbolCnt=0;
	CrumbleTumble.counter=0;
	CrumbleTumble.highlightCnt=0;
	CrumbleTumble.createTopWords();
	CrumbleTumble.highLightTextWithAudio();
};
CrumbleTumble.playCurrentSentence=function()
{
	document.getElementById('playSound').src="sounds/"+CrumbleTumble.sound;
	document.getElementById('playSound').play();
};

CrumbleTumble.playSounds=function(audio)
{
	setTimeout(function(){  
		document.getElementById('playSound').src=Utils.Path+'sounds/'+audio;
		document.getElementById("playSound").play();	
		},150);
};

//to create top span for splited words
CrumbleTumble.createTopWords=function()
{
	CrumbleTumble.randomIndex=Math.floor(Math.random() * (CrumbleTumble.copyJson.length));
	questionId=CrumbleTumble.copyJson[CrumbleTumble.randomIndex].questionId;
	CrumbleTumble.currentSentence=CrumbleTumble.copyJson[CrumbleTumble.randomIndex].sentence;
	CrumbleTumble.Name=CrumbleTumble.copyJson[CrumbleTumble.randomIndex].name;
	CrumbleTumble.copyJson.splice(CrumbleTumble.randomIndex,1);
	CrumbleTumble.splitWords=CrumbleTumble.splitSentence(CrumbleTumble.currentSentence);
	CrumbleTumble.planeWordsArray=CrumbleTumble.splitWords.splice(0);
	//separate out symbols from string
	CrumbleTumble.planeWordsArray=CrumbleTumble.removeExpression(CrumbleTumble.planeWordsArray);
	console.log(CrumbleTumble.planeWordsArray);
	CrumbleTumble.Answer=CrumbleTumble.planeWordsArray.slice(0);
	console.log(CrumbleTumble.Answer);
	CrumbleTumble.sentenceWordCnt=CrumbleTumble.planeWordsArray.length;	
	CrumbleTumble.createSpan();//create top words span
	// split 2 sentences words
	CrumbleTumble.splitSentenceWords();
 };
CrumbleTumble.isSymbol=function(symbol)
{
	var expression = [".","?","!",","],index;
	index=expression.indexOf(symbol);		
	return index;
};

//call from createTopWords fn.
CrumbleTumble.createSpan=function()
{
	console.log(CrumbleTumble.planeWordsArray);
	var newSpan,span,isSymbol="";
	for(var i=0;i<CrumbleTumble.sentenceWordCnt;i++)
	{
		newSpan= document.createElement("span");
		newSpan.setAttribute("id","topWord"+i); 
		isSymbol=CrumbleTumble.isSymbol(CrumbleTumble.planeWordsArray[i]);
		if(isSymbol==-1)
		{	$(newSpan).text(CrumbleTumble.planeWordsArray[i]);
			newSpan.className="";
			$(newSpan).addClass("topWords wordsClass");
		}
		else
		{
			CrumbleTumble.symbolCnt++;
			$(newSpan).text(CrumbleTumble.planeWordsArray[i]);
			$(newSpan).addClass("wordsClass");
		}
		
		$(newSpan).data("word",CrumbleTumble.planeWordsArray[i]);
		$(newSpan).data("wordSetFlag",0);
		
		$(newSpan).droppable({
			drop : CrumbleTumble.afterDrop,
			dragover:CrumbleTumble.allowDrop,
		});
		
		$("#sentenceDiv").append(newSpan);
	}
};

CrumbleTumble.removeExpression=function(wordsarray)
{
	var expression = [".","?","!",","];
	var i,j,str,temp=[],flag=0;
	for(i = 0; i < wordsarray.length; i++)
	{
		flag=0;
		for(j=0;j<expression.length;j++)
		   {
			   	 if(wordsarray[i].indexOf(expression[j]) != -1)
			    {
			    	str = wordsarray[i].replace(expression[j],"");
			    	temp.push(str);
			    	temp.push(expression[j]);
			    	flag=1;
			    	break;	
			    }
			}
		if(flag!=1){
			temp.push(wordsarray[i]);
			flag=0
		}
	}
	return temp;
};

CrumbleTumble.dropWords=function()
{
	var noOfWords=0,randomPlace=0,arrOfRandomPlaces=[];
	
	document.getElementById('playSound').src=Utils.Path+"sounds/glassBreak.wav";
	document.getElementById('playSound').play(); 
	
	for(var i=0;i<CrumbleTumble.planeWordsArray.length;i++)
	{	
		if(CrumbleTumble.Name!=$("#topWord"+i).text().toLowerCase() && !($("#topWord"+i).text().length<2))
		{
			arrOfRandomPlaces.push(i);
			CrumbleTumble.arrayOfInfo.push(""+$("#topWord"+i).text());
		}	
	}
	//CrumbleTumble.arrayOfInfo.splice(-1);
	console.log(arrOfRandomPlaces);
	//arrOfRandomPlaces.splice(-1,1);
	console.log(arrOfRandomPlaces);
	 for(var k=0;k<CrumbleTumble.planeWordsArray.length;k++)
	{
		if($.inArray(k,arrOfRandomPlaces)!=-1)
		{	
			$('#topWord'+k).addClass('transperant');
		}
		else
			$('#topWord'+k).droppable('disable');	
	}
	CrumbleTumble.arrlengthOfWords=arrOfRandomPlaces.length;
	shuffleArray(CrumbleTumble.arrayOfInfo);
	console.log(CrumbleTumble.Answer)
	for(var i=0;i<arrOfRandomPlaces.length;i++)
	{
		var spanElement=$('<div id="word'+i+'" style="z-index:5000;" class="noPadding text-center col-xs-3 col-md-3 col-lg-3 col-sm-3 col-xs-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-offset-1 splitteredWord">'+CrumbleTumble.arrayOfInfo[i]+'</div>');
		$('#dropWords').append(spanElement);
	/* 	var xy=CrumbleTumble.getPositions();
		$(spanElement).css({"position": "absolute","top": xy[1] + "%", "left": xy[0] + "%"}); */
	} 
	$('.splitteredWord').on('click',function(){
			CrumbleTumble.checkWord(this.id);
	});
}
CrumbleTumble.afterDrop=function(event,ui)
{
	var draggedWord,droppedSpace;
	CrumbleTumble.gameOpened=true;s
	draggedWord=ui.draggable;
	droppedSpace= $(this);
	if($(draggedWord).text()==$(droppedSpace).text())
	{
			
		CrumbleTumble.arrlengthOfWords--;
		$(draggedWord).css({'color':'rgb(0,0,0)'});
		$(draggedWord).position({
		  my: "center center",
		  at: "center center",
		  of:this
		});
		//$(droppedSpace).removeClass('blankSpaces');
		$(draggedWord).draggable('disable');
		$(droppedSpace).droppable('disable');
		$(draggedWord).css({'z-index':-1});
	}
	else{
		scoredMarks=0;
		ui.draggable.animate(ui.draggable.data("origPosition"),"slow");
		//CrumbleTumble.stopPlayBack();
		document.getElementById('playSound').src=Utils.Path+"sounds/wrong.mp3";
		document.getElementById('playSound').play();
	}
	 if(CrumbleTumble.arrlengthOfWords==0)
	{
		setTimeout(function()
		{
	
			document.getElementById('playSound').src=Utils.Path+"sounds/correct.mp3";
			document.getElementById('playSound').play();
		},1000);
	} 
}

/* CrumbleTumble.randomRotateEffect=function(element)
{
	var randomDeg=Math.floor(Math.random()*180);
	$(element).css({"transform":'rotate(' + randomDeg + 'deg)'});
}
CrumbleTumble.getPositions=function()
{
	var y=Math.floor((Math.random()*35)+40);
	
	var x=Math.floor(Math.random()*80);
	while($.inArray(((y)||(y+1)||(y+2)||(y-1)||(y-2)||(y-3)),CrumbleTumble.arrayOfTopPositions)>=0)
	{
		y=Math.floor((Math.random()*35)+40);
		
	}
	while(($.inArray(((x)||(x+1)||(x+2)||(x-1)||(x-2)||(x-3)),CrumbleTumble.arrayOfLeftPositions)>=0))
	{
		x=Math.floor(Math.random()*100);
	}

	CrumbleTumble.arrayOfTopPositions.push(y);
	CrumbleTumble.arrayOfLeftPositions.push(x);
	
	return [x,y];
} */
CrumbleTumble.checkWord=function(obj)
{
	if($("#"+obj).text()==CrumbleTumble.arrayOfInfo[CrumbleTumble.counter])
	{
		var index=CrumbleTumble.Answer.indexOf(""+$("#"+obj).text());
		$('#topWord'+index).removeClass('transperant');
		document.getElementById('playSound').src=Utils.Path+"sounds/welldone.mp3";
		document.getElementById('playSound').play();
		CrumbleTumble.counter++;
		if(CrumbleTumble.counter!=CrumbleTumble.arrayOfInfo.length)
			CrumbleTumble.checkWordTimer=setTimeout(function(){CrumbleTumble.selectWords();},1000);
		else
		{
			if(CrumbleTumble.checkWordTimer)
			{
				clearTimeout(CrumbleTumble.checkWordTimer);
				CrumbleTumble.checkWordTimer=null;
			}
			/* document.getElementById('playSound').src=Utils.Path+"sounds/correct.mp3";
			document.getElementById('playSound').play(); */
			setTimeout(function(){CrumbleTumble.resetData();},1500);
		}	
	}
	else
	{
		document.getElementById('playSound').src=Utils.Path+"sounds/wrong.mp3";
		document.getElementById('playSound').play();
	}		
}

//Mix-up the sentence words
CrumbleTumble.splitSentenceWords=function()
{  
	var str=[];
	str=CrumbleTumble.planeWordsArray.slice(0);
	CrumbleTumble.shuffleMixWords=shuffleArray(CrumbleTumble.planeWordsArray);
	while(arraysEqual(str,CrumbleTumble.shuffleMixWords))
	{	
		CrumbleTumble.shuffleMixWords=shuffleArray(CrumbleTumble.shuffleMixWords);
	}
};
// Split Sentence
CrumbleTumble.splitSentence=function(array){
	return (array.split(" "));
}
CrumbleTumble.allowDrop=function(event)
{
	event.preventDefault();
}
CrumbleTumble.highLightTextWithAudio=function()
{
	if(Utils.mobileDeviceFlag)
	{	
		Android.playTts(CrumbleTumble.Answer[CrumbleTumble.highlightCnt],'eng');
	}	
	/* else
		saySomething(CrumbleTumble.Answer[CrumbleTumble.highlightCnt]);
	 */
	$('#topWord'+CrumbleTumble.highlightCnt).css({'background-color':'yellow'});
	if(CrumbleTumble.TtsIntervalTimer)
	{
		clearInterval(CrumbleTumble.TtsIntervalTimer);
		CrumbleTumble.TtsIntervalTimer=null;
	}
	CrumbleTumble.TtsIntervalTimer=setInterval(function()
	{
		 if(Utils.mobileDeviceFlag)
			CrumbleTumble.ttsFlag=Android.informCompletion(); 
		 
		if(CrumbleTumble.ttsFlag==true)
		{	CrumbleTumble.highlightCnt++;
			if(CrumbleTumble.highlightCnt < CrumbleTumble.Answer.length-1)
			{	
				$('.topWords').css({'background-color':'transparent'});
				CrumbleTumble.ttsFlag=false;
				CrumbleTumble.highLightTextWithAudio();
			}
			else
			{
				CrumbleTumble.highlightCnt=0;
				clearInterval(CrumbleTumble.TtsIntervalTimer);
				$('.topWords').css({'background-color':'transparent'});
				$('#soundDiv,#next').css('visibility','visible');  
				CrumbleTumble.dropWords();
				CrumbleTumble.selectTimer=setTimeout(function(){CrumbleTumble.selectWords();},1500)
			}	
		} 	
	},100);
};
// Random No Generator
function shuffleArray(array)
{
	var i,j,temp;
	for (i = array.length - 1; i > 0; i--) 
	{
	    j = Math.floor(Math.random() * (i + 1));
	    temp = array[i];
	    array[i] = array[j];
	    array[j] = temp;
	}
	return array;
}
function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }
    return true;
}
 CrumbleTumble.home=function(){
	location.reload();
 };
 function saySomething(whatToSay)
{
	if('speechSynthesis' in window)
	{
		var speech = new SpeechSynthesisUtterance(whatToSay);
		speech.lang = 'hi-IN'; //en-US
		//speech.rate=0.5;
		window.speechSynthesis.speak(speech);
	}
}