var Kahaniyaan={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0;
Kahaniyaan.nextPage=0;
Kahaniyaan.storyReadCnt = 0;
Kahaniyaan.txtArr=[];
Kahaniyaan.wordNo=0;
Kahaniyaan.goBackFlag=null;
Kahaniyaan.playPauseFlag=true;
Kahaniyaan.soundFlag=true;
var nextTurnFlag=prevTurnFlag=false;
$(document).ready(function () {
	$('title').text(Kahaniyaan.GameName)
	if(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag=true;
	document.getElementById('endpage').style.display = "none";
	Kahaniyaan.storyData = data;
	Kahaniyaan.setImages();
	$("#playPause").click(function (e) {
		e.stopImmediatePropagation();
		Kahaniyaan.playPause(this);
	});
	Kahaniyaan.openStory('');
});
Kahaniyaan.setImages=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+"images/skin/BG3.png)";
	document.getElementById("imgDiv").style.backgroundImage="url("+Utils.Path+"images/skin/pageCover1.png)";
	document.getElementById("textPart").style.backgroundImage="url("+Utils.Path+"images/skin/pageCover2.png)";
	document.getElementsByClassName("cover1")[0].style.backgroundImage="url("+Utils.Path+"images/skin/page1.png)";
	document.getElementsByClassName("cover2")[0].style.backgroundImage="url("+Utils.Path+"images/skin/page2.png)";
	document.getElementById("acknowledgementDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/creditsBG.png)";
	// document.getElementById("playPause").src=Utils.Path+"images/skin/playStory.png";
	document.getElementById('logo').src=Utils.Path+"images/skin/logo.png";
	document.getElementById('credits').src=Utils.Path+"images/skin/credits.png";
	document.getElementById('playAgain').src=Utils.Path+"images/skin/playAgain.png";
}
Kahaniyaan.showStoryMenu=function()							//shows story menu
{
	document.getElementById("acknowledgementDiv").innerHTML="";
	Kahaniyaan.goBackFlag="storyMenu";
	document.getElementById('Stories').style.visibility="visible";
	$("#playPauseDiv").hide();
	document.getElementById('Stories').innerHTML=Kahaniyaan.GameName;
	document.getElementById("playSound").pause();
	Kahaniyaan.nextPage=0;
	document.getElementById('storyPage').style.display="none";
	document.getElementById('endpage').style.display="none";
	document.getElementById('scrollBar').innerHTML="";
	document.getElementById('showMenu').style.display="block";
	document.getElementById('coverpage').style.display="none";
	document.getElementById("home").style.display = "block";
	scrollBar=document.getElementById("scrollBar");
	Kahaniyaan.openStory('')
}

Kahaniyaan.openStory=function(element)					//opens perticular story
{
	$('#acknowledgementDiv').hide();
	$("#storyPage,#playPauseDiv").show();
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	Kahaniyaan.currentElement=element;
	scoredMarks=10;
	Kahaniyaan.soundFlag=true;
	Kahaniyaan.storyReadCnt=0;
	Kahaniyaan.goBackFlag="storyOpened";
	Kahaniyaan.currentStoryNumber = 0;
	for (var i = 0; i < Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length; i++)
	{
		var hiddenImg;
		hiddenImg= document.createElement("img");
		hiddenImg.setAttribute("id","hiddenImg"+i);
		hiddenImg.setAttribute("class","img-responsive col-lg-1 col-md-1 col-xs-1 col-sm-1");
		hiddenImg.setAttribute("src",Utils.Path+"images/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[i].pageImage);
		$("#hiddenImgDiv").append(hiddenImg);
	}
	var imgs = document.images,
		len = imgs.length,
		counter = 0;
	
	[].forEach.call( imgs, function( img ) {
		if(img.complete)
		  incrementCounter();
		else
		  img.addEventListener( 'load', incrementCounter, false );
	} );
	
	function incrementCounter() {
		counter++;
		if ( counter === len ) {
			console.log('All images loaded!');
			$(".loader").hide();
		}
	}
	Kahaniyaan.displayOnPages(0,0);
	document.getElementById("storyImg").src=Utils.Path+"images/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].pageImage;
}

Kahaniyaan.nextStoryPage = function (element)		//display story pages , calls on onclick of pre & next button
{
	Kahaniyaan.txtArr=[];
	Kahaniyaan.wordNo=0;
	Kahaniyaan.playPauseFlag=true;
	// document.getElementById("playPause").src=Utils.Path+"images/skin/playStory.png";
	$('#playPause').prop('class', 'fa fa-play');
	clearTimeout(Kahaniyaan.stopHighlighting ,Kahaniyaan.playStoryPage,Kahaniyaan.turnClass,Kahaniyaan.removeClass,Kahaniyaan.storyStartTimer);
	document.getElementById('playSound').pause()
	$("#playPauseDiv").show();
	
	if(element.id=="imgDiv" && Kahaniyaan.nextPage>0)			//if prev button clicked
	{
		var cloneCover1=$('.cover1').clone().addClass('remove');
		$('#imgDiv').append(cloneCover1);
		cloneCover1.css({'position':'absolute','top':0,'z-index':1});
		Kahaniyaan.nextPage--;
		Kahaniyaan.displayOnPages(1000,0);
		Kahaniyaan.addPageTurnClass('prevturn');
	}
	else if(element.id=="textPart" && Kahaniyaan.nextPage<Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length)
	{
		nextTurnFlag=true;
		var cloneCover2=$('.cover2').clone().addClass('remove');
		$('#textPart').append(cloneCover2);
		// cloneCover2.css({ 'position': 'absolute', 'z-index': 1 });
		cloneCover2.css({'position':'absolute','top':0,'z-index':1});
		Kahaniyaan.nextPage++;							//if next button clicked
		Kahaniyaan.storyReadCnt++;
		Kahaniyaan.displayOnPages(0,1000);               // textTimeout imgTimeout display after few sec
		Kahaniyaan.addPageTurnClass('nextturn');
	} 
	else
		Kahaniyaan.displayOnPages(0,0);
	
}
Kahaniyaan.addPageTurnClass=function(className)
{
	if(Kahaniyaan.turnClass)
	{
		clearTimeout(Kahaniyaan.turnClass);
		Kahaniyaan.turnClass=null;
	}
	Kahaniyaan.turnClass=setTimeout(()=>{
		$('.remove').addClass(className+' page');
		if(Kahaniyaan.removeClass)
		{
			clearTimeout(Kahaniyaan.removeClass);
			Kahaniyaan.removeClass=null;
		}
		Kahaniyaan.removeClass=setTimeout(() => {
			$('.remove').remove();	
		}, 510);
	},500);
}
Kahaniyaan.displayOnPages=function(textTimeout,imgTimeout)
{
	var spanEle;
	if(Kahaniyaan.nextPage<Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length)//shows story page
	{
		if(Kahaniyaan.textTimer)
		{
			clearTimeout(Kahaniyaan.textTimer);
			Kahaniyaan.textTimer=null;
		}
		Kahaniyaan.textTimer=setTimeout(() => {
			document.getElementById("txtDiv").innerHTML="";
			Kahaniyaan.txtArr=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].pageText.split(" ");
			for(var i=0;i<Kahaniyaan.txtArr.length;i++)
			{
				spanEle= document.createElement("span");
				spanEle.setAttribute("id","span"+i);
				spanEle.setAttribute("class","spans");
				spanEle.innerHTML=" "+Kahaniyaan.txtArr[i];
				document.getElementById("txtDiv").appendChild(spanEle);
			}	
		}, textTimeout);
		if(Kahaniyaan.imgTimer)
		{
			clearTimeout(Kahaniyaan.imgTimer);
			Kahaniyaan.imgTimer=null;
		}
		Kahaniyaan.imgTimer=setTimeout(() => {
		    document.getElementById("storyImg").src=Utils.Path+"images/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].pageImage;
		}, imgTimeout);
		if(Kahaniyaan.playAudio)
		{
			clearTimeout(Kahaniyaan.playAudio);
			Kahaniyaan.playAudio=null;
		}
		Kahaniyaan.playAudio=setTimeout(() => {
			document.getElementById("playSound").src=Utils.Path+"sounds/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readPageAudio;
			$('#playSound').on("loadedmetadata", function(){
			//Kahaniyaan.playStory();
				$(this).off("loadedmetadata");	
			});	
		}, 1000);
		
	}
	if(Kahaniyaan.nextPage==Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length)//story ends
	{
		document.getElementById("playSound").pause();
		document.getElementById("storyPage").style.display="none";
		$('#endpage').show();
		$("#Stories").text(Kahaniyaan.endMsg);
		$("#playPauseDiv").hide();
		Kahaniyaan.createHardcodeddivs();
	}
	if(Kahaniyaan.storyReadCnt==1)
	{
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}
 }
Kahaniyaan.playStory=function()			//calculates total pages ,first page play time & highlights them
{
	var totalPages;
	// document.getElementById("playPause").src=Utils.Path+"images/skin/pause.png";
	$('#playPause').prop('class', 'fa fa-pause');
	totalPages=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList.length-1;
	Kahaniyaan.currentTime=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.wordNo].wordFrom;
	
	Kahaniyaan.playTime=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[totalPages].wordTo-Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.wordNo].wordFrom;
	document.getElementById("playSound").currentTime=Kahaniyaan.currentTime;
	document.getElementById("playSound").play();
	Kahaniyaan.highLight();
	if(Kahaniyaan.playStoryPage)
	{
		clearTimeout(Kahaniyaan.playStoryPage);
		Kahaniyaan.playStoryPage=null;
	}
	Kahaniyaan.playStoryPage=setTimeout(function()
	{
		document.getElementById("playSound").pause();
		
	},Kahaniyaan.playTime*1000);
}
Kahaniyaan.highLight=function()
{
	var getDuration=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.wordNo].wordDuration;									//duration of word
	$("#span"+Kahaniyaan.wordNo).css({'color':'yellow'});
	if(Kahaniyaan.stopHighlighting)
	{
		clearTimeout(Kahaniyaan.stopHighlighting);
		Kahaniyaan.stopHighlighting=null;
	}
	Kahaniyaan.stopHighlighting=setTimeout(function()
	{
		if(Kahaniyaan.wordNo<Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList.length-1)								//plays one by one word
		{
			Kahaniyaan.wordNo++;
			$('.spans').css({'color':'rgba(0, 0, 0, 0.6)'});
			Kahaniyaan.highLight();
		}
		else										//stops highlighting
		{
			Kahaniyaan.playPauseFlag=true;
			// document.getElementById("playPause").src = Utils.Path + "images/skin/playStory.png";
			$('#playPause').prop('class', 'fa fa-play');
			Kahaniyaan.wordNo=0;
			$('.spans').css({'color':'rgba(0, 0, 0, 0.6)'});			
		}
	},getDuration*1000);
}

Kahaniyaan.playPause=function()				//change play pause image,stops highlighting accordingly
{
	if(Kahaniyaan.playPauseFlag==false)
	{
		Kahaniyaan.playPauseFlag=true;

		clearTimeout(Kahaniyaan.stopHighlighting);
		// document.getElementById("playPause").src=Utils.Path+"images/skin/playStory.png";
		$('#playPause').prop('class', 'fa fa-play');
		document.getElementById("playSound").pause();
		Kahaniyaan.currentTime=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.wordNo].wordDuration;
	}
	else
	{
		Kahaniyaan.playPauseFlag=false;
		clearTimeout(Kahaniyaan.stopHighlighting);
		Kahaniyaan.playStory();
	}
}
Kahaniyaan.createHardcodeddivs=function()
{
	var ackDiv;
	for(var i=0;i<Object.keys(Kahaniyaan.hardcoded[Kahaniyaan.currentStoryNumber]).length;i++)
	{
		if(Object.values(Kahaniyaan.hardcoded[Kahaniyaan.currentStoryNumber])[i]!="")
		{
			ackDiv= document.createElement("div");
			ackDiv.setAttribute("id","ack"+i); 
			ackDiv.setAttribute("class","noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12"); 
			document.getElementById("acknowledgementDiv").appendChild(ackDiv);
			ackDiv.innerHTML=Object.keys(Kahaniyaan.hardcoded[Kahaniyaan.currentStoryNumber])[i]+" : "+Object.values(Kahaniyaan.hardcoded[Kahaniyaan.currentStoryNumber])[i];
		}
	}
}
Kahaniyaan.showCredits=function(){
	$('#acknowledgementDiv').show();
};
Kahaniyaan.playAgain=function()
{
	$('#endpage').hide();
	$("#acknowledgementDiv").empty();
	Kahaniyaan.nextPage=0;
	Kahaniyaan.openStory(Kahaniyaan.currentElement);
};