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.goBackFlag=null;
Kahaniyaan.playPauseFlag=false;
Kahaniyaan.soundFlag=true;
var nextTurnFlag=prevTurnFlag=false;
$(document).ready(function () {
	$('title').text(Kahaniyaan.GameName)
	$(".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("KhelbadiKahaniyan"); */
	
	setTimeout(function(){
	document.getElementById('coverpage').style.display="block";
	document.getElementById('showMenu').style.display="none";
	document.getElementById('storyPage').style.display="none";
	document.getElementById('endpage').style.display="none";
	document.getElementById("home").style.display = "none";
	//Page.init();
	Kahaniyaan.setImages();
	},300);
});
Kahaniyaan.setImages=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+"images/skin/"+Kahaniyaan.coverImage+")";
	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('home').src=Utils.Path+"images/skin/Home.png";
	document.getElementById('logo').src=Utils.Path+"images/skin/logo.png";
	document.getElementById('play').src=Utils.Path+"images/skin/Play.png";
	document.getElementById('prev').src=Utils.Path+"images/skin/Pre.png";
	document.getElementById('next').src=Utils.Path+"images/skin/Next.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
{
	var scrollBar;
	document.body.style.backgroundImage="url("+Utils.Path+"images/skin/BG3.png)";
	document.getElementById("acknowledgementDiv").innerHTML="";
	Kahaniyaan.goBackFlag="storyMenu";
	document.getElementById('Stories').style.visibility="visible";
	$("#playPauseDiv").hide();
	$("#storyBookDiv").hide();
	$("#storyBookDiv").text('');
	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.populateMenu(scrollBar);
}
Kahaniyaan.populateMenu=function(parentDiv)					//creates story menu
{
	var mainDiv,newDiv,newImage,para,imgCnt=0;
	for(var i=0;i<Math.ceil(Kahaniyaan.storyData.length/3);i++)
	{
		mainDiv= document.createElement("div");
		mainDiv.setAttribute("id","mainDiv"+i); 
		mainDiv.setAttribute("class","mainDivClass col-lg-12 col-md-12 col-xs-12 col-sm-12 noPadding"); 
		parentDiv.appendChild(mainDiv);
		
		for(var j=0;j<3;j++)
		{
			if(imgCnt<Kahaniyaan.storyData.length)
			{
				newDiv= document.createElement("div");
				newDiv.setAttribute("id","div"+imgCnt); 
				newDiv.setAttribute("class","bgClass divClass col-lg-3 col-md-3 col-xs-3 col-sm-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1 noPadding"); 
				newDiv.setAttribute("onclick","Kahaniyaan.openStory(this)");
				var randomBookImage=Math.floor(Math.random()*4);
				newDiv.style.backgroundImage="url("+Utils.Path+"images/skin/bookCover_"+randomBookImage+".png)";
				mainDiv.appendChild(newDiv);
				
				newImage= document.createElement("img");
				newImage.setAttribute("id","img"+imgCnt);
				newImage.setAttribute("class","img-responsive borderClass col-lg-12 col-md-12 col-xs-12 col-sm-12");
				newImage.setAttribute("src",Utils.Path+"images/"+Kahaniyaan.storyData[imgCnt].storyCover);
				newDiv.appendChild(newImage);
				
				para= document.createElement("p");
				para.setAttribute("id","para"+imgCnt);
				para.setAttribute("class","menuNames text-center col-lg-12 col-md-12 col-xs-12 col-sm-12");
				para.innerHTML=Kahaniyaan.storyData[imgCnt].storyName;
				newDiv.appendChild(para);
				$("#div"+imgCnt).data("value",imgCnt);
				$("#div"+imgCnt).data("image",randomBookImage);
					imgCnt++;
			}
		}
	}
}

Kahaniyaan.openStory=function(element)					//opens perticular story
{
	$('#acknowledgementDiv').hide();
	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;
	$(".marginClass").css("pointer-events","none");
	$("#storyBookDiv").show();
	document.getElementById('Stories').style.visibility="hidden";
	Kahaniyaan.goBackFlag="storyOpened";
	document.getElementById('showMenu').style.display="none";
	Kahaniyaan.currentStoryNumber=$(element).data("value");			//gets story number
	questionId=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].questionId;
	getDuration(Utils.Path+"sounds/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].titleAudio,element);
	document.getElementById("playSound").play();
	Kahaniyaan.showStoryBook($(element).data("image"));
	// document.getElementById("storyImg").src=Utils.Path+"images/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages[Kahaniyaan.nextPage].img;
}
Kahaniyaan.showStoryBook=function(randomBookImage)		//shows  book cover which is click
{
	newDiv= document.createElement("div");
	newDiv.setAttribute("id","bookDiv"); 
	newDiv.setAttribute("class","bgClass  col-lg-10 col-md-10 col-xs-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1 noPadding"); 
	newDiv.style.backgroundImage="url("+Utils.Path+"images/skin/bookCover_"+randomBookImage+".png)";
	document.getElementById("storyBookDiv").appendChild(newDiv);
	
	newImage= document.createElement("img");
	newImage.setAttribute("id","bookImg");
	newImage.setAttribute("class","img-responsive col-lg-10 col-md-10 col-xs-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
	newImage.setAttribute("src",Utils.Path+"images/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].storyCover);
	newDiv.appendChild(newImage);
	
	para= document.createElement("p");
	para.setAttribute("id","bookPara");
	para.setAttribute("class","menuNames text-center col-lg-12 col-md-12 col-xs-12 col-sm-12");
	para.innerHTML=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].storyName;
	newDiv.appendChild(para);
}
function getDuration(src,element)			//get duration of  title audio
{
	var duration=0;
	if(Kahaniyaan.soundFlag)
	{
		$('#playSound').on("loadedmetadata", function()
		{
			Kahaniyaan.soundFlag=false;
			duration=$('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			if(Kahaniyaan.storyStartTimer)
			{
				clearTimeout(Kahaniyaan.storyStartTimer);
				Kahaniyaan.storyStartTimer=null;
			}
			Kahaniyaan.storyStartTimer=setTimeout(function(){
				$("#storyBookDiv").hide();
				document.getElementById('storyPage').style.display="block";
				document.getElementById("textPart").style.display="block";	
				$(".marginClass").css("pointer-events","auto");
				Kahaniyaan.nextStoryPage(element);
			},duration*1000);
		});
		$('#playSound').prop('src',src);
	}
}
Kahaniyaan.nextStoryPage=function(element)		//display story pages , calls on onclick of pre & next button
{
	Kahaniyaan.txtArr=[];
	Kahaniyaan.wordNo=0;
	Kahaniyaan.playPauseFlag=false;
	clearTimeout(Kahaniyaan.stopHighlighting ,Kahaniyaan.playStoryPage,Kahaniyaan.turnClass,Kahaniyaan.removeClass,Kahaniyaan.storyStartTimer);
	document.getElementById('playSound').pause()
	$("#playPauseDiv").show();
	if(element.id=="prev" && Kahaniyaan.nextPage>0)			//if prev button clicked
	{
		$('.cover1').css('right', '83vw');
		var cloneCover2=$('.cover1').clone().addClass('remove');
		$('#textPart').append(cloneCover2);
		cloneCover2.css({'position':'absolute','z-index':1});
		Kahaniyaan.nextPage--;
		Kahaniyaan.displayOnPages(1000,0);
		Kahaniyaan.addPageTurnClass('prevturn');
	}
	else if(element.id=="next" && Kahaniyaan.nextPage<Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages.length)
	{
		nextTurnFlag = true;
		$('.cover2').css('right', 'initial');
		var cloneCover2=$('.cover2').clone().addClass('remove');
		$('#textPart').append(cloneCover2);
		cloneCover2.css({'position':'absolute','z-index':1});
	//	$('.cover2').addClass('nextturn page');
		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].pages.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].pages[Kahaniyaan.nextPage].text.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].pages[Kahaniyaan.nextPage].img;
		}, imgTimeout);
		if(Kahaniyaan.playAudio)
		{
			clearTimeout(Kahaniyaan.playAudio);
			Kahaniyaan.playAudio=null;
		}
		Kahaniyaan.playAudio=setTimeout(() => {
			document.getElementById("playSound").src=Utils.Path+"sounds/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].soundFile;
			$('#playSound').on("loadedmetadata", function(){
			Kahaniyaan.playStory();
				$(this).off("loadedmetadata");	
			});	
		}, 1000);
		
	}
	if(Kahaniyaan.nextPage==Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages.length)//story ends
	{
		document.getElementById("playSound").pause();
		document.getElementById("storyPage").style.display="none";
		$('#endpage').show();
		document.getElementById('Stories').style.visibility="visible";
		$("#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;
	$('.cover2').css('right', 'initial');
	document.getElementById("playPause").src=Utils.Path+"images/skin/pause.png";
	totalPages=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages[Kahaniyaan.nextPage].read.length-1;
	Kahaniyaan.currentTime=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages[Kahaniyaan.nextPage].read[Kahaniyaan.wordNo].From;
	
	Kahaniyaan.playTime=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages[Kahaniyaan.nextPage].read[totalPages].To-Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages[Kahaniyaan.nextPage].read[Kahaniyaan.wordNo].From;
	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].pages[Kahaniyaan.nextPage].read[Kahaniyaan.wordNo].Duration;									//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].pages[Kahaniyaan.nextPage].read.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";
			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";
		document.getElementById("playSound").pause();
		Kahaniyaan.currentTime=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pages[Kahaniyaan.nextPage].read[Kahaniyaan.wordNo].Duration;
	}
	else
	{
		Kahaniyaan.playPauseFlag=false;
		clearTimeout(Kahaniyaan.stopHighlighting);
		//$(this).off("loadedmetadata");
		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.values(Kahaniyaan.hardcoded[Kahaniyaan.currentStoryNumber])[i];
			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();
	$("#storyBookDiv").text('');
	$("#acknowledgementDiv").empty();
	Kahaniyaan.nextPage=0;
	Kahaniyaan.openStory(Kahaniyaan.currentElement);
};
Kahaniyaan.callHome=function()
{
	document.getElementById('playSound').pause();	//clear all timeouts
    var id = window.setTimeout(function() {}, 0);
    while (id--) {
        window.clearTimeout(id); // will do nothing if no timeout with id is present
    }
	if(Kahaniyaan.goBackFlag=="storyOpened")
		Kahaniyaan.showStoryMenu();
	else if(Kahaniyaan.goBackFlag=="storyMenu")
		location.reload();
}