var Kahaniyaan={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0;
Kahaniyaan.nextPage=0;
Kahaniyaan.pageReadCnt = 0;				//page read count
Kahaniyaan.pageTxtArr=[];					//text on singe page
Kahaniyaan.wordNo=0;
Kahaniyaan.playPauseFlag = false;
var muteAudioFlag = false;
Kahaniyaan.soundFlag = true;
Kahaniyaan.currentStoryNumber = 0;
$(document).ready(function () {
	$('title').text(Kahaniyaan.GameName)
	if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
		Utils.mobileDeviceFlag=true;
	Kahaniyaan.storyData = data;
	$('#storyBookDiv,#endpage,#storyPage').hide();
	Kahaniyaan.setImages();
	
	$("#playPause").click(function (e) {			//stops other events
		e.stopPropagation();
		// e.stopImmediatePropagation();
		Kahaniyaan.playPause(this);
	});
	$("#mute").click(function (e) {			//stops other events
		e.stopPropagation();
		// e.stopImmediatePropagation();
		Kahaniyaan.muteAudio();
	});
	Kahaniyaan.createStoryCover();
	changeProperty();
});
$(window).on('orientationchange', function (e) {
	changeProperty();
});
function changeProperty()
{
	if ($('#storyBookDiv').is(':visible')) {
		if (screen.width < 450) {
			$('#storyBookDiv').css({ 'height': $('body').height(), 'display': 'flex', 'align-items': 'center', 'margin-top': 'unset' });
			$('#bookDiv').css('height', '40vh');
			$('#bookImg').css('height', '21vh');
			$('#bookPara').css('bottom', '2vh');
		}
		else {
			$('#storyBookDiv').css({ 'height': 'unset', 'display': 'block', 'align-items': 'unset', 'margin-top': '5vh' });
			$('#bookDiv').css('height', '87vh');
			$('#bookImg').css('height', '52vh');
			$('#bookPara').css('bottom', '7vh');
		}
	}
}

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)";
	$('#logo').prop('src',Utils.Path + "images/skin/logo.png");
	$('#pradigiLogo').prop('src',Utils.Path + "images/skin/logo.png");
	document.getElementById("storyImg").src=Utils.Path+"images/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].pageImage;
}
Kahaniyaan.createStoryCover=function()		//Create story cover
{
	var newDiv, newImage, para;
	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.setAttribute('onclick','Kahaniyaan.openBook()')
	newDiv.style.backgroundImage="url("+Utils.Path+"images/skin/bookCover_1.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].storyImage);
	newDiv.appendChild(newImage);
	
	para= document.createElement("p");
	para.setAttribute("id","bookPara");
	para.setAttribute("class","menuNames widthCls text-center col-lg-12 col-md-12 col-xs-12 col-sm-12");
	para.innerHTML=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].storyTitle;
	newDiv.appendChild(para);

	if ($(para).text().length > 17)
		$(para).addClass('marqueCls');
	else
		$(para).removeClass('widthCls');
	/* getDuration(Utils.Path+"sounds/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].titleAudio);
	document.getElementById("playSound").play(); */
	Kahaniyaan.showStoryCover();
}

Kahaniyaan.showStoryCover=function()					//shows story cover
{
	$("#playPauseDiv").show();
	$('#textPart,#imgDiv').css('pointer-events', 'auto');
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	scoredMarks=10;
	Kahaniyaan.soundFlag=true;
	Kahaniyaan.pageReadCnt=0;
	Kahaniyaan.currentStoryNumber = 0;
	$("#hiddenImgDiv").text('');
	//create & hide all images used in the whole story
	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,				//load all 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();
			$("#storyBookDiv").show();
			
			//getDuration(Utils.Path+"sounds/"+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].titleAudio);
			document.getElementById("playSound").src='sounds/'+Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].titleAudio
			document.getElementById("playSound").play();
		}
	}
}

Kahaniyaan.openBook = function ()		//opens story 
{
	if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		GoInFullscreen($("#element").get(0));
	
	$("#storyBookDiv").hide();
	document.getElementById('storyPage').style.display="block";
	Kahaniyaan.nextStoryPage('')
}
/* Get into full screen */
function GoInFullscreen(element) {
    if (element.requestFullscreen)
	document.documentElement.requestFullscreen()
    else if (element.mozRequestFullScreen)
	document.documentElement.mozRequestFullScreen();
    else if (element.webkitRequestFullscreen)
	document.documentElement.webkitRequestFullscreen();
    else if (element.msRequestFullscreen)
	document.documentElement.msRequestFullscreen();
    screen.orientation.lock("landscape-primary")
        .then(function() {})
        .catch(function(error) {});
}

function getDuration(src)			//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";
				Kahaniyaan.nextStoryPage('');
			},duration*2000);
		});
		$('#playSound').prop('src',src);
	}
}
Kahaniyaan.nextStoryPage = function (element)		//display story pages , calls on onclick of pre & next pages
{
	Kahaniyaan.pageTxtArr=[];
	Kahaniyaan.wordNo=0;
	Kahaniyaan.playPauseFlag=false;
	$('#playPause').prop('class', 'fa fa-play-circle iconCls');
	$('.spans').removeClass('animated zoomIn');
	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 page clicked
	{
		$('#imgDiv').css('pointer-events', 'none');
		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)
	{
		$('#textPart').css('pointer-events', 'none');
		Kahaniyaan.nextPage++;							//if next page clicked
		Kahaniyaan.pageReadCnt++;
		if (Kahaniyaan.nextPage < Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length)
		{//shows story page
			var cloneCover2=$('.cover2').clone().addClass('remove');
			$('#textPart').append(cloneCover2);
			cloneCover2.css({'position':'absolute','top':0,'z-index':1});
			Kahaniyaan.displayOnPages(0,1000);               // textTimeout imgTimeout display after few sec
			Kahaniyaan.addPageTurnClass('nextturn');
		}
		else if(Kahaniyaan.nextPage==Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length)//story ends
		{
			document.getElementById("playSound").pause();
			clearTimeout(Kahaniyaan.playAudio);
			document.getElementById("storyPage").style.display="none";
			$('#endpage').show();
			
			$("#playPauseDiv").hide();
			Kahaniyaan.createHardcodeddivs();
			return false;
		}
	} 
	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 (className == 'nextturn')
		{
			$($('.remove ').children()[1]).css({ 'bottom': '0.5vh' });
			$($('.remove ').children()[1]).prop('class', 'noPadding col-lg-7 col-md-7 col-xs-7 col-sm-7 col-sm-offset-2 col-lg-offset-2 col-md-offset-2 col-xs-offset-2');
		}
		
		if(Kahaniyaan.removeClass)
		{
			clearTimeout(Kahaniyaan.removeClass);
			Kahaniyaan.removeClass=null;
		}
		Kahaniyaan.removeClass=setTimeout(() => {
			$('.remove').remove();	
			$('#textPart,#imgDiv').css('pointer-events', 'auto');
		}, 510);
	},500);
}
Kahaniyaan.displayOnPages=function(textTimeout,imgTimeout)
{
	var spanEle;
	/* if(Kahaniyaan.nextPage<Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList.length-1)//shows story page
	{ */
		if(Kahaniyaan.textTimer)
		{
			clearTimeout(Kahaniyaan.textTimer);
			Kahaniyaan.textTimer=null;
		}
		Kahaniyaan.textTimer=setTimeout(() => {
			document.getElementById("txtDiv").innerHTML="";
			Kahaniyaan.pageTxtArr=Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].pageText.split(" ");
			for(var i=0;i<Kahaniyaan.pageTxtArr.length;i++)
			{
				spanEle= document.createElement("span");
				spanEle.setAttribute("id","span"+i);
				spanEle.setAttribute("class", "spans");
				
				$(spanEle).on('click', function (e) {			//stops other events
					e.stopPropagation();						//ensures that event doesn't bubble to parent ele.
					// e.stopImmediatePropagation();
					Kahaniyaan.playSelectedWord(this);
				});
				spanEle.innerHTML=" "+Kahaniyaan.pageTxtArr[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.pageReadCnt==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;
	$('#playPause').prop('class', 'fa fa-pause-circle iconCls');
	$('.spans').css({ 'font-weight': 'unset' });
	$('.spans').removeClass('animated zoomIn');
	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': '#12B4F1' });
	document.getElementById('txtDiv').scrollTop = document.getElementById('span' + Kahaniyaan.wordNo).offsetTop;
	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':'black'});
			Kahaniyaan.highLight();
		}
		else										//stops highlighting
		{
			Kahaniyaan.playPauseFlag=true;
			$('#playPause').prop('class', 'fa fa-play-circle iconCls');
			Kahaniyaan.wordNo=0;
			$('.spans').css({'color':'black'});			
		}
	},getDuration*1000);
}

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

		clearTimeout(Kahaniyaan.stopHighlighting);
		$('#playPause').prop('class', 'fa fa-play-circle iconCls');
		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.stopPlayBack = function() {
    Kahaniyaan.resetAll();
    Kahaniyaan.currentTime = Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.wordNo].wordFrom;
};
Kahaniyaan.playSelectedWord = function(element) {
     Kahaniyaan.stopPlayBack();
    Kahaniyaan.selectedWord = Number(element.id.match(/(\d+)/)[0]);
	$('.spans').css({ 'font-weight': 'unset' });
	$('.spans').removeClass('animated zoomIn');
	$(element).css({  'font-weight': 'bold' });
	$(element).addClass('animated zoomIn');
    var playTime = Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.selectedWord].wordTo - Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.selectedWord].wordFrom;
    var currentTime = Kahaniyaan.storyData[Kahaniyaan.currentStoryNumber].pageList[Kahaniyaan.nextPage].readList[Kahaniyaan.selectedWord].wordFrom;
    document.getElementById("playSound").currentTime = currentTime;
    document.getElementById("playSound").play();
    if (Kahaniyaan.playWord) {
        clearTimeout(Kahaniyaan.playWord);
        Kahaniyaan.playWord = null;
    }
    Kahaniyaan.playWord = setTimeout(function() {
        document.getElementById("playSound").pause();

    }, playTime * 1000);
}
Kahaniyaan.muteAudio = function ()
{
	if (muteAudioFlag)
	{
		muteAudioFlag = false;
		$('#mute').prop('class', 'fa fa-volume-up iconCls');
		document.getElementById("playSound").muted = false;
	}
	else
	{
		muteAudioFlag = true;
		$('#mute').prop('class', 'fa fa-volume-off iconCls');
		document.getElementById("playSound").muted = true;
	}
}
Kahaniyaan.createHardcodeddivs=function()
{
	var ackDiv,extraInfo,div;
	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];
		}
	}
	extraInfo = document.createElement("div");
	$(extraInfo).prop('class', 'noPadding col-md-12 col-xs-12 col-lg-12 col-sm-12');
	$(extraInfo).css({ 'text-align': 'center', 'margin-top': '4vh' });

	for (var i = 0; i < 2; i++)
	{
		div=document.createElement("div");
		$(div).prop('class', 'noPadding col-md-12 col-xs-12 col-lg-12 col-sm-12');
		$(div).text(Kahaniyaan.extraInfo[i]);
		$(extraInfo).append(div)
	}
	$('#acknowledgementDiv').append(extraInfo);
}
Kahaniyaan.playAgain=function()
{
	$('#endpage').hide();
	$("#storyBookDiv").text('');
	$("#acknowledgementDiv").empty();
	Kahaniyaan.nextPage = 0;
	muteAudioFlag = true;
	Kahaniyaan.muteAudio()
	Kahaniyaan.createStoryCover();
};
Kahaniyaan.resetAll = function() {
    //$('#musicIcon').hide();
    document.getElementById("playSound").pause();
    clearTimeout(Kahaniyaan.stopHighlighting);
    clearTimeout(Kahaniyaan.playStoryPage);
    clearTimeout(Kahaniyaan.playWord);
    Kahaniyaan.playPauseFlag = true;
    $('#playPause').prop('class', 'fa fa-play-circle iconCls');
    $('.spans').css({ 'color': 'black' });
    Kahaniyaan.wordNo = 0;
}