var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=100,resId;
Crumbling.level=0;
Crumbling.loadmetaDataFlag=false;

$(document).ready(function(){
	$(".se-pre-con").fadeOut("slow");
	if((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
		Utils.mobileDeviceFlag=true;
	
	// if(Utils.mobileDeviceFlag)
		// 	Utils.Path=Android.getMediaPath("ThikThak"); 
	
	setTimeout(function(){
		Crumbling.setAllImages();
		setTimeout(function(){
			Crumbling.init();
		},200);
	},200);
});

Crumbling.setAllImages=function(){
	$('#hathodi').prop('src',Utils.Path+'images/Theek-Thak_Break.png');
	$('#playGame').prop('src',Utils.Path+'images/Theek-Thak_Play.png');
	$('#home').prop('src',Utils.Path+'images/Theek-Thak_Home.png');
	$('#logo').prop('src',Utils.Path+'images/logo.png');
	$('#next').prop('src',Utils.Path+'images/Theek-Thak_Next.png');
	$('#playSentence').prop('src',Utils.Path+'images/Theek-Thak_Sound.png');
	$('#jokerImg').prop('src',Utils.Path+'images/joker.png');
};

Crumbling.init=function()
{
	Crumbling.sentenceList=[];
	$('#gamePage,#playGame,#jokerDiv').hide();
	$('#coverPage').show();
	$('#background').css({"background-image":'url('+Utils.Path+'images/CoverHindi.gif)'});
	$('#playGame').show();
	//Crumbling.loadDataLevelWise();
};


Crumbling.loadDataLevelWise=function()
{
	if(Crumbling.level>0)
	{
		for(var i=0;i<Crumbling.level;i++)
		{
			var j=0;
			while(j<Crumbling.sentencedata[i]['list'].length)
			{
				Crumbling.sentenceList.push(Crumbling.sentencedata[i]['list'][j]);
				j++;
			}	
		}
	}
	else
	{
		var j=0;
			while(j<Crumbling.sentencedata[Crumbling.level]['list'].length)
			{
				Crumbling.sentenceList.push(Crumbling.sentencedata[Crumbling.level]['list'][j]);
				j++;
			}
	}
}


Crumbling.initializeVariables=function()
{
	Crumbling.randomSentence=0,Crumbling.cut=false,startTime=0,Crumbling.sentence=0,Crumbling.arrlength=0,Crumbling.gameOpened=false;
	Crumbling.arrOfWords=[],Crumbling.specialCases=['Ms.','Mr.','Mrs.','mr.','etc.','mrs.','Etc'],Crumbling.arrOfEndingPositions=[],Crumbling.arrOfPunctuation=[],Crumbling.arrayOfTopPositions=[],Crumbling.arrayOfLeftPositions=[];
};

Crumbling.addSentenceToScreen=function()
{
	scoredMarks=0;
	Crumbling.durationOfAudio=0;
	Crumbling.initializeVariables();
	var d=new Date();
	$('#playGame,#coverPage').hide();
	$('#gamePage').show();
	$('#background').css({"background-image":'url('+Utils.Path+'images/BG.png)'});
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	Crumbling.randomSentence=Math.floor(Math.random()*Crumbling.jsondata.length);
	questionId=Crumbling.jsondata[Crumbling.randomSentence].StoryId;
	//console.log(Crumbling.jsondata[Crumbling.randomSentence].sentence);
	//$('#sentenceDiv').text(Crumbling.sentencedata[Crumbling.randomSentence].sentence);
	Crumbling.cutSentence();
	//Crumbling.playSentence();
};

Crumbling.playSentence=function()
{
	clearInterval(Crumbling.getDurationInterval);
	clearTimeout(Crumbling.TtsIntervalTimer);
	document.getElementById('playSound').src=Utils.Path+"sound/"+Crumbling.pathOfSentence['Audio'];
	document.getElementById('playSound').play();
}

Crumbling.cutSentence=function()
{
	Crumbling.pathOfSentence=Crumbling.jsondata[Crumbling.randomSentence]['page'][0]['sentence'][0];
	Crumbling.sentence=Crumbling.jsondata[Crumbling.randomSentence]['page'][0]['sentence'][0].Sentence;
	Crumbling.arrOfWords=Crumbling.sentence.split(' ').slice();
	Crumbling.arrlengthOfWords=Crumbling.arrOfWords.length;
	searchStringInArray('?','.','!',Crumbling.arrOfWords);
	Crumbling.removeFullStops();
	console.log(Crumbling.arrOfWords);
	$('#sentenceDiv').empty();
	Crumbling.addSpansToSentence();
};

Crumbling.addSpansToSentence=function()
{
	var div,spanElement,noOfWords=0,k=0;
	$('#next').removeClass('blink_me');
	for(var i=0;i<Crumbling.arrOfEndingPositions.length;i++)
	{
		if(i==0)
			noOfWords=Crumbling.arrOfEndingPositions[i];
		else
			noOfWords=Crumbling.arrOfEndingPositions[i]-Crumbling.arrOfEndingPositions[i-1];
		div=$('<div id="div'+i+'" style="display:inline" class="noPadding sentences text-center col-lg-12 col-md-12 col-xs-12 col-sm-12"></div>');
		for(var j=0;j<noOfWords;j++)
		{
			spanElement=$('<span id="space'+k+'" style="z-index:-1;display:inline-block" class="text-center blankSpaces spaces">'+Crumbling.arrOfWords[k]+'</span>');
			$(spanElement).droppable({
				drop : Crumbling.afterDrop,
				dragover:Crumbling.allowDrop
			});
			
			/* $(spanElement).on('click',function(){
				Crumbling.playsoundForWord(this);
			}); */
			$(div).append(spanElement);
			k++;
		}
		$(div).append('<span class="punctuation">'+Crumbling.arrOfPunctuation[i]+'</span>');
		$('#sentenceDiv').append(div);
	}
	
	sound = Utils.Path+"sound/"+Crumbling.pathOfSentence['audio'];
	Crumbling.loadmetaDataFlag = true;
	callback = Crumbling.breakWords;
	Crumbling.getAudioDuration(sound, callback);
	$('.spaces').css({'pointer-events':'none'});
	$('#hathodi').addClass('blink_me');

	//document.getElementById('playSound').src=Utils.Path+"sound/"+Crumbling.pathOfSentence['audio'];
	//document.getElementById('playSound').play();
	// if(Crumbling.mainTimeOut)
	// {
	// 	clearTimeout(Crumbling.mainTimeOut);
	// 	Crumbling.mainTimeOut=null;
	// }
	// Crumbling.mainTimeOut=setTimeout(function(){
	// 	Crumbling.durationOfAudio=document.getElementById('playSound').duration;
	// 	if(Crumbling.getDurationInterval)
	// 	{
	// 		clearInterval(Crumbling.getDurationInterval);
	// 		Crumbling.getDurationInterval=null;
	// 	}
	// 	Crumbling.getDurationInterval=setInterval(function()
	// 	{
	// 		if(Crumbling.durationOfAudio!=0)
	// 		{
	// 			clearInterval(Crumbling.getDurationInterval);
	// 			$('.spaces').css({'pointer-events':'none'});
	// 			$('#hathodi').addClass('blink_me');
	// 			if(Crumbling.TtsIntervalTimer)
	// 			{
	// 				clearTimeout(Crumbling.TtsIntervalTimer);
	// 				Crumbling.TtsIntervalTimer=null;
	// 			}
	// 			Crumbling.TtsIntervalTimer=setTimeout(function()
	// 			{
	// 				if(!Crumbling.cut)
	// 				{
	// 					Crumbling.stopPlayBack();
	// 					Crumbling.dropWords();
	// 				}
	// 			},Crumbling.durationOfAudio*1000);
	// 		}
	// 	},200);
	// },300);
};
Crumbling.breakWords=function(duration){
	document.getElementById('playSound').play();
	if(Crumbling.TtsIntervalTimer)
	{
		clearTimeout(Crumbling.TtsIntervalTimer);
		Crumbling.TtsIntervalTimer=null;
	}
	Crumbling.TtsIntervalTimer=setTimeout(function()
	{
		if(!Crumbling.cut)
		{
			Crumbling.stopPlayBack();
			Crumbling.dropWords();
		}
	},duration*1000);
}

Crumbling.callhathodi=function()
{
	clearInterval(Crumbling.getDurationInterval);
	clearTimeout(Crumbling.TtsIntervalTimer);
	Crumbling.cut=true;
	//Crumbling.flag=true;
	Crumbling.dropWords();
	
}

Crumbling.dropWords=function()
{
	clearInterval(Crumbling.getDurationInterval);
	clearTimeout(Crumbling.mainTimeOut);
	clearTimeout(Crumbling.TtsIntervalTimer);
	
	$('#hathodiDiv').css({'visibility':'hidden'});
	var noOfWords=0,randomPlace=0,arrOfRandomPlaces=[],arrayOfInfo=[];
	document.getElementById('playSound').src=Utils.Path+"sound/glassBreak.wav";
	document.getElementById('playSound').play();
	
	for(var i=0;i<Crumbling.arrOfEndingPositions.length;i++)
	{
		if(i!==0)
			noOfWords=Math.floor((Crumbling.arrOfEndingPositions[i]-Crumbling.arrOfEndingPositions[i-1])/2);
		else
			noOfWords=Math.floor(Crumbling.arrOfEndingPositions[i]/2);
		for(var j=0;j<noOfWords;j++)
		{
			if(i!==0)
				randomPlace=Math.floor((Math.random()*(Crumbling.arrOfEndingPositions[i]-Crumbling.arrOfEndingPositions[i-1]))+Crumbling.arrOfEndingPositions[i-1]);
			else
				randomPlace=Math.floor(Math.random()*Crumbling.arrOfEndingPositions[i]);

			while($.inArray(randomPlace,arrOfRandomPlaces)!=-1)
			{
				randomPlace=Math.floor(Math.random()*Crumbling.arrOfEndingPositions[i]);
			}
			arrOfRandomPlaces.push(randomPlace);
			arrayOfInfo.push(Crumbling.arrOfWords[randomPlace]);
		}
	}
	
	for(var k=0;k<Crumbling.arrlengthOfWords;k++)
	{
		if($.inArray(k,arrOfRandomPlaces)==-1)
			$('#space'+k).droppable('disable');
	}
	Crumbling.arrlengthOfWords=arrOfRandomPlaces.length;
	$('.spaces').css({'pointer-events':'auto'});
	for(var i=0;i<arrOfRandomPlaces.length;i++)
	{
		$('#space'+arrOfRandomPlaces[i]).addClass('blankSpaces').css({'color':'transparent'});
		spanElement=$('<span id="span'+i+'" style="z-index:5000;color:red" class="splitteredWord">'+arrayOfInfo[i]+'</span>');
		$(spanElement).draggable({
			cursor: 'move',
			snap:'#space'+i,
			containment: "#gamePage",
			start: function()
			{
				$(this).data("origPosition",$(this).position());
				$(this).css({'transform':'rotate(0deg)'});
				//Crumbling.playsoundForWord(this);
			}
		});
		/* $(spanElement).on('click',function(){
				Crumbling.playsoundForWord(this);
		}); */
		Crumbling.randomRotateEffect(spanElement);
		$('body').append(spanElement);
		xy=Crumbling.getPositions();
		$(spanElement).css({"position": "absolute","top": xy[1] + "%", "left": xy[0] + "%"});
	}
}

/* Crumbling.playsoundForWord=function(element)
{
	var word=$("#"+element.id).text().trim();
	var j=0;
	for(var i=0;i<Crumbling.pathOfSentence['Words'].length;i++)
	{
		if((Crumbling.pathOfSentence['Words'][i]['name'].trim()==word)||(Crumbling.pathOfSentence['Words'][i]['name'].trim()==(word+'.'))||(Crumbling.pathOfSentence['Words'][i]['name'].trim()==(word+'?')||(Crumbling.pathOfSentence['Words'][i]['name'].trim()==(word+'!'))))
		{
			j=i; 
			break;
		}
	}

    var time = 	Crumbling.pathOfSentence['Words'][j]['Duration'] * 1000;
        var currentTime=Crumbling.pathOfSentence['Words'][j]['From'];
        var seconds = currentTime * 1000;
        document.getElementById('playSound').src=Utils.Path+'sound/'+Crumbling.pathOfSentence['Audio'];
        document.getElementById('playSound').currentTime=Crumbling.pathOfSentence['Words'][j]['From'];
		document.getElementById('playSound').play();
		setTimeout(function(){
			Crumbling.stopPlayBack();
		}, time);
} */


Crumbling.afterDrop=function(event,ui)
{
	var draggedWord,droppedSpace;
	Crumbling.gameOpened=true;
	draggedWord=ui.draggable;
	droppedSpace= $(this);
	if($(draggedWord).text()==$(droppedSpace).text())
	{
		Crumbling.arrlengthOfWords--;
		$(draggedWord).css({'color':'rgb(24,56,132)'});
		$(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");
		Crumbling.stopPlayBack();
		document.getElementById('playSound').src=Utils.Path+"sound/wrong.mp3";
		document.getElementById('playSound').play();
	}
	if(Crumbling.arrlengthOfWords==0)
	{
		scoredMarks=100;
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
		Crumbling.gameOpened=false;
		setTimeout(function()
		{
			$('#jokerDiv,#jokerImg').show();
			$('#jokerImg').addClass('magictime vanishIn');
			$('#next').addClass('blink_me');
			$('.splitteredWord,.spaces').css({'pointer-events':'none'});
			Crumbling.stopPlayBack();
			document.getElementById('playSound').src=Utils.Path+"sound/correct.mp3";
			document.getElementById('playSound').play();
		},1000);
	}
}

Crumbling.stopPlayBack=function()
{
	clearInterval(Crumbling.getDurationInterval);
	clearTimeout(Crumbling.mainTimeOut);
	clearTimeout(Crumbling.TtsIntervalTimer);
	document.getElementById('playSound').pause();
}

Crumbling.showNext=function()
{
	Crumbling.stopPlayBack();
	if(Crumbling.gameOpened)
	{
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
		Crumbling.gameOpened=false;
	}
	clearInterval(Crumbling.getDurationInterval);
	clearTimeout(Crumbling.mainTimeOut);
	clearTimeout(Crumbling.TtsIntervalTimer);
	$('#hathodiDiv').css({'visibility':'visible'});
	$('#jokerImg').removeClass('magictime vanishIn');
	$('#jokerDiv,#jokerImg').hide();
	$('.splitteredWord').empty();
	$('.splitteredWord').remove();
	Crumbling.initializeVariables();
	Crumbling.addSentenceToScreen();
}


Crumbling.callHome=function()
{
	Crumbling.stopPlayBack();
	if(Crumbling.gameOpened)
	{
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}
	setTimeout(function(){
		location.reload(true);
	},200);
}

Crumbling.replaceBythischar=function()
{
	for(var i=0;i<Crumbling.pathOfSentence['Words'].length;i++)
	{
		var tempString=Crumbling.pathOfSentence['Words'][i]['name'];
		var p=".";
		Crumbling.pathOfSentence['Words'][i]['name']=Crumbling.pathOfSentence['Words'][i]['name'].replace(".", " ");
		Crumbling.pathOfSentence['Words'][i]['name']=Crumbling.pathOfSentence['Words'][i]['name'].replace("?", " ");
	}
	
};

function searchStringInArray (str, str2, str3,strArray) 
{
    for (var j=0; j<strArray.length; j++) 
    {
        if ( (strArray[j].indexOf(str)!==-1 ) || (strArray[j].indexOf(str2)!==-1) || (strArray[j].indexOf(str3)!==-1)) 
		{
			if($.inArray(strArray[j],Crumbling.specialCases)==-1)
			{
				Crumbling.arrOfEndingPositions.push(j+1);
			}
		}
    }
    return -1;
}

Crumbling.removeFullStops=function()
{
	var i=0,res;
	for(i;i<Crumbling.arrOfEndingPositions.length;i++)
	{
		var index=Crumbling.arrOfEndingPositions[i];
		var word=Crumbling.arrOfWords[index-1];
		res=word.substring(0,word.length-1);
		Crumbling.arrOfPunctuation.push(word.substring(word.length-1));
		Crumbling.arrOfWords[index-1]=res;
	}
};




Crumbling.shuffleWords=function(array)
{
  var i = 0, j = 0, temp = 0;
  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;
  }
};

Crumbling.randomRotateEffect=function(element)
{
	var randomDeg=Math.floor(Math.random()*180);
	$(element).css({"transform":'rotate(' + randomDeg + 'deg)'});
}


Crumbling.getPositions=function()
{
	var y=Math.floor((Math.random()*35)+40);
	
	var x=Math.floor(Math.random()*75);
	while($.inArray(((y)||(y+1)||(y+2)||(y-1)||(y-2)||(y-3)),Crumbling.arrayOfTopPositions)>=0)
	{
		y=Math.floor((Math.random()*35)+40);
		
	}
	while(($.inArray(((x)||(x+1)||(x+2)||(x-1)||(x-2)||(x-3)),Crumbling.arrayOfLeftPositions)>=0))
	{
		x=Math.floor(Math.random()*75);
	}

	Crumbling.arrayOfTopPositions.push(y);
	Crumbling.arrayOfLeftPositions.push(x);
	
	return [x,y];
}


Crumbling.getPositions=function()
{
	var y=Math.floor((Math.random()*35)+40);
	var x=Math.floor(Math.random()*75);
	while($.inArray(((y)||(y+1)||(y+2)||(y-1)||(y-2)||(y-3)),Crumbling.arrayOfTopPositions)>=0)
	{
		y=Math.floor((Math.random()*35)+40);
		
	}
	while(($.inArray(((x)||(x+1)||(x+2)||(x-1)||(x-2)||(x-3)),Crumbling.arrayOfLeftPositions)>=0))
	{
		x=Math.floor(Math.random()*75);
	}

	Crumbling.arrayOfTopPositions.push(y);
	Crumbling.arrayOfLeftPositions.push(x);
	
	return [x,y];
}


Crumbling.allowDrop=function(event)
{
	event.preventDefault();
}


//function getting audio duration
Crumbling.getAudioDuration = function (sound, callback) {
	var duration = 0;
	$('#playSound').prop('src', sound);
	if (Crumbling.loadmetaDataFlag) {
		$('#playSound').on("loadedmetadata", function () {
			duration = $('#playSound').prop('duration');
			Crumbling.loadmetaDataFlag = false;
			$('#playSound').unbind("loadedmetadata");
			callback(duration);
		});
	}
	else
		$('#playSound').unbind("loadedmetadata");
};	