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

$(document).ready(function(){
	$(".se-pre-con").fadeOut("slow");
	setFontFamilyForLang("fonts/Lohit-Oriya.ttf");
	if(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag=true;
	
	if(Utils.mobileDeviceFlag)
		$('#recordDiv,#playRecordDiv').show();
	else
		$('#recordDiv,#playRecordDiv').hide();
	setTimeout(function(){
		VideoStory.setAllImages();
		VideoStory.init();
	},200);
});

setFontFamilyForLang=function(fontFilePath){
  var newStyle = "<style>"+
            "@font-face {  "+
              "font-family: 'CustomFontFamily';"  +
                "src: url('"+fontFilePath+"') format('truetype');"+
                "}  </style>";
    $("head").append(newStyle);
    $("body").css("font-family","CustomFontFamily");            
}
VideoStory.setAllImages=function()
{
	$('#playGame').prop('src',Utils.Path+'images/playGame.png');
	$('#home').prop('src',Utils.Path+'images/Home.png');
	$('#prev').prop('src',Utils.Path+'images/previous.png');
	$('#next').prop('src',Utils.Path+'images/Next.png');
	$('#play').prop('src',Utils.Path+'images/Play.png');
	$('#logo').prop('src',Utils.Path+'images/logo.png');
	$('#stop').prop('src',Utils.Path+'images/Stop.png');
	$('#speaker').prop('src',Utils.Path+'images/Sound.png');
	$('#record').prop('src',Utils.Path+'images/Record.png');
	$('#playRecord').prop('src',Utils.Path+'images/My-Recording.png');
};

VideoStory.init=function()
{
	$('#gamePage').hide();
	$('#coverPage').show();
	$('#background').css({'backgroundImage':'url('+Utils.Path+'images/'+VideoStory.hardcodedData['coverPage']+')'});
};

VideoStory.addMenu=function()
{
	$('#menu').empty();
	$('#background').css({'backgroundImage':'url('+Utils.Path+'images/'+VideoStory.hardcodedData['BG']+')'});
	$('#menu,#gamePage').show();
	$('#cover,#game,#coverPage').hide();
	VideoStory.initializeVariables();
	var i=0,j=0,tempArray=[],div,img,para;
	tempArray=VideoStory.jsondata.slice();
	while(i<tempArray.length)
	{
		div=$('<div class="col-lg-3 col-md-3 col-xs-4 col-sm-3 storyDivs" id="div'+i+'" style="margin-bottom:3%;"><img id="img'+i+'" style="border:2px solid black;padding:0px;!important" src="images/BG.jpg" class="img-responsive col-lg-10 col-md-10 col-xs-10 col-sm-10 col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1"/><p id="para'+i+'" style="font-weight:bold" class="text-center storyNames col-lg-10 col-md-10 col-xs-10 col-sm-10 col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1" >'+tempArray[i]['StoryName']+'</p></div>');
		$('#menu').append(div);
		$('#div'+i).data('StoryId',tempArray[i].StoryId);
		i++;
	}
	$('.storyDivs').on('click',function(){
		VideoStory.showNameAndImageOfStory(this);
	});
};

VideoStory.initializeVariables=function()
{
	VideoStory.gameOpened=false;
	scoredMarks=0,VideoStory.counter=0,
	VideoStory.arrayOfSplitedSentence=[],VideoStory.indexOfPages=[];
	VideoStory.Flags={};
	VideoStory.sameStoryPlayed=false;
	VideoStory.Flags.volumeLow=false;
	VideoStory.Flags.recordAudio=false;
	VideoStory.Flags.playRecordedAudio=false;
	VideoStory.Flags.playDefaultAudio=false;
	VideoStory.Flags.recorded=false;
	VideoStory.Flags.navigationFlag=false;
	document.getElementById('playAudio').muted=false;
	$('#speaker').prop('src',Utils.Path+'images/Sound.png');
};

VideoStory.showNameAndImageOfStory=function(element)
{
	$('#menu').fadeOut();
	$('#cover').fadeIn();
	for(var i=0;i<VideoStory.jsondata.length;i++)
	{
		if(VideoStory.jsondata[i]['StoryId']===$(element).data('StoryId'))
		{
			VideoStory.selectedStory=i;
			break;
		}
	}
	$('#title').text(VideoStory.jsondata[VideoStory.selectedStory]['StoryName']);
	questionId=VideoStory.jsondata[VideoStory.selectedStory]['StoryId'];
	document.getElementById('coverImg').src="images/sampleImageKahaniyan.jpg";
};
/*on click of image*/
VideoStory.showStory=function()
{
	$('#cover').hide(500);
	$('#game').show(500);
	$('#storyName').text(VideoStory.jsondata[VideoStory.selectedStory]['StoryName']);
	VideoStory.basicPath=VideoStory.jsondata[VideoStory.selectedStory]['page'][0]['sentence'][0];
	searchStringInArray('NNN', VideoStory.basicPath['Words']);
	console.log(VideoStory.indexOfPages);
	VideoStory.addSentences();
};

function searchStringInArray (str, strArray) 
{
	var j=0;VideoStory.indexOfPages=[];
	VideoStory.indexOfPages.push(j);
    for (j; j<strArray.length; j++) 
    {
        if (strArray[j]['name'].indexOf(str)!==-1) 
        	VideoStory.indexOfPages.push(j);
    }
	VideoStory.indexOfPages.push(j-1);
    return -1;
}

function findAndRemove(str,strArr)
{
	var j=0;
    for (j; j<strArr.length; j++) 
    {
        if (strArr[j].indexOf(str)!==-1) 
        	VideoStory.arrayOfSplitedSentence[j]=VideoStory.arrayOfSplitedSentence[j].replace('NNN'," ");
    }
    return -1;
}	


VideoStory.addSentences=function()
{
	VideoStory.playTime=0;
	var element;
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	VideoStory.arrayOfSplitedSentence=[];
	$('#sentenceDiv').empty();
	for(var i=VideoStory.indexOfPages[VideoStory.counter];i<=VideoStory.indexOfPages[VideoStory.counter+1];i++)
	{
		VideoStory.arrayOfSplitedSentence.push(VideoStory.basicPath['Words'][i]['name']);
	}
	findAndRemove('NNN',VideoStory.arrayOfSplitedSentence);
	console.log(VideoStory.arrayOfSplitedSentence);
	
	for(var i=0;i<VideoStory.arrayOfSplitedSentence.length;i++)
	{
		element=$('<span id="span'+i+'" class="sentence" >'+' '+VideoStory.arrayOfSplitedSentence[i]+'</span>');
		$('#sentenceDiv').append(element);
	}
	
	VideoStory.playTime=(VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter+1]]['To']-VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter]]['From'])*1000;
	VideoStory.audioStartTime=VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter]]['From'];
	document.getElementById('playAudio').src="sounds/"+VideoStory.basicPath['Audio'];
	console.log(VideoStory.playTime);
};

VideoStory.defaultSoundClicked=function()
{	

	if(VideoStory.Flags.playDefaultAudio==false)
	{
		if(VideoStory.sameStoryPlayed==false)
		{
			VideoStory.sameStoryPlayed=true;
			VideoStory.gameOpened=true;
			scoredMarks=100;
			console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
			if(Utils.mobileDeviceFlag)
				Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
			VideoStory.gameOpened=false;
		}
		VideoStory.playDefaultAudio();
		
	}
	else
		VideoStory.pauseDefaultAudio();
};


VideoStory.pauseDefaultAudio=function()
{
	if(VideoStory.Flags.playDefaultAudio)
	{
		clearTimeout(VideoStory.timeOut);
		document.getElementById('playAudio').pause();
		$('#play').prop('src','images/Play.png');
		VideoStory.Flags.playDefaultAudio=false;
		VideoStory.audioStartTime=document.getElementById('playAudio').currentTime;
		VideoStory.enableClicks('record','playRecord');
		var temp=document.getElementById('playAudio').currentTime-VideoStory.prevCurrentTime;
		VideoStory.playTime=((VideoStory.playTime/1000)-temp)*1000;
		//console.log(VideoStory.playTime);
	}
};

VideoStory.playDefaultAudio=function()
{
	VideoStory.Flags.playDefaultAudio=true;
	document.getElementById('playAudio').currentTime=0;
	VideoStory.disableClick('record','playRecord');
	VideoStory.enableClicks('prev','next');
	VideoStory.enableClicks('stop','speaker');
	$('#play').prop('src','images/Pause.png');
	document.getElementById('playAudio').currentTime=VideoStory.audioStartTime;
	console.log(document.getElementById('playAudio').currentTime);
	document.getElementById('playAudio').play();
	VideoStory.prevCurrentTime=document.getElementById('playAudio').currentTime;
	if(VideoStory.timeOut)
	{
		clearTimeout(VideoStory.timeOut);
		VideoStory.timeOut = null;
	}
	
    VideoStory.timeOut=setTimeout(function()
	{
		VideoStory.stopDefaultAudio();
	}, VideoStory.playTime);
};

VideoStory.resetAudioFunc=function()
{
	VideoStory.audioStartTime=VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter]]['From'];
	VideoStory.playTime=(VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter+1]]['To']-VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter]]['From'])*1000;
}

VideoStory.stopDefaultAudio=function()
{
	clearTimeout(VideoStory.timeOut);
	document.getElementById('playAudio').pause();
	$('#play').prop('src','images/Play.png');
	VideoStory.Flags.playDefaultAudio=false;
	VideoStory.audioStartTime=VideoStory.basicPath['Words'][VideoStory.indexOfPages[VideoStory.counter]]['From'];
	VideoStory.enableClicks('record','playRecord');
};

VideoStory.volumeOnOff=function()
{
	if(VideoStory.Flags.playDefaultAudio)
	{
		if(VideoStory.Flags.volumeLow==false)
		{
			document.getElementById('playAudio').muted=true;
			VideoStory.Flags.volumeLow=true;
			document.getElementById('speaker').src="images/Sound-off.png";
		}
		else if(VideoStory.Flags.volumeLow==true)
		{
			document.getElementById('playAudio').muted=false;
			VideoStory.Flags.volumeLow=false;
			document.getElementById('speaker').src="images/Sound.png";
		}
	}	
};


VideoStory.disableClick=function(x1,x2)
{
	$('#'+x1+',#'+x2).css({'pointer-events':'none'});
};

VideoStory.enableClicks=function(x1,x2)
{
	$('#'+x1+',#'+x2).css({'pointer-events':'auto'});
};

VideoStory.recordYourAudio=function()
{
	if(VideoStory.Flags.playDefaultAudio)
		VideoStory.stopDefaultAudio();

	if(!VideoStory.Flags.recordAudio)
	{
		VideoStory.Flags.recordAudio=true;
		$('#record').prop('src','images/Stopthh.png');
		$('#record').addClass('blink_me');
		VideoStory.disableClick('play','playRecord');
		VideoStory.disableClick('stop','speaker');
		VideoStory.enableClicks('prev','next');
		if(Utils.mobileDeviceFlag)
			Android.startRecording('kahaniya.3gp');
	}
	else
	{
		VideoStory.Flags.recordAudio=false;
		$('#record').removeClass('blink_me');
		$('#record').prop('src','images/Record.png');
		if(Utils.mobileDeviceFlag)
			Android.stopRecording();
		VideoStory.enableClicks('playRecord','play');
		VideoStory.enableClicks('speaker','stop');
		VideoStory.Flags.recorded= true;
	}
};

VideoStory.playRecordedAudio=function()
{
	if((VideoStory.Flags.recorded==true)&&(VideoStory.Flags.playDefaultAudio==false))
	{
    	if (!VideoStory.Flags.playRecordedAudio)
    	{
			$('#playRecord').prop('src','images/Stopthh.png');
			VideoStory.disableClick('play','record');
			VideoStory.disableClick('stop','speaker');
	        VideoStory.Flags.playRecordedAudio=true;
			if(Utils.mobileDeviceFlag)
				Android.audioPlayerForStory("/kahaniya.3gp",null);
   	 	}
    	else if(VideoStory.Flags.playRecordedAudio)
    	{
			$('#playRecord').prop('src','images/My-Recording.png');
	        VideoStory.Flags.playRecordedAudio=false;
			if(Utils.mobileDeviceFlag)
				Android.stopAudioPlayer();
			VideoStory.enableClicks('record','play');
			VideoStory.enableClicks('speaker','stop');
	    }
	}
};

VideoStory.reSetFlags=function()
{
	if(VideoStory.Flags.playDefaultAudio)
		VideoStory.stopDefaultAudio();
	if(VideoStory.Flags.recordAudio){
		if(Utils.mobileDeviceFlag)
			Android.stopRecording();
	}
	if(VideoStory.Flags.playRecordedAudio){
		if(Utils.mobileDeviceFlag)
			Android.stopAudioPlayer();
	}
	$('#play').prop('src',Utils.Path+'images/Play.png');
	$('#stop').prop('src',Utils.Path+'images/Stop.png');
	$('#speaker').prop('src',Utils.Path+'images/Sound.png');
	$('#record').prop('src',Utils.Path+'images/Record.png');
	$('#playRecord').prop('src',Utils.Path+'images/My-Recording.png');
	VideoStory.Flags.volumeLow=false;
	VideoStory.Flags.recordAudio=false;
	VideoStory.Flags.playRecordedAudio=false;
	VideoStory.Flags.playDefaultAudio=false;
	VideoStory.Flags.recorded=true;
	$('#record').removeClass('blink_me');
	$('.widgets').css({'pointer-events':'auto'});
	document.getElementById('playAudio').muted=false;
};

VideoStory.navigateSentences=function(evt)
{
	VideoStory.reSetFlags();
	var length=VideoStory.indexOfPages.length-1;
	if(evt=='prev')
	{
		if(VideoStory.counter!==0)
			VideoStory.counter--;
		else
			VideoStory.counter=length-1;
	}
	else if(evt=='next')
	{
		if(VideoStory.counter!==length-1)
			VideoStory.counter++;
		else
			VideoStory.counter=0;
	}
	$('#sentenceDiv').empty();
	if(VideoStory.counter>=length)
	{
		VideoStory.counter=0;
	}
	VideoStory.addSentences();
};


VideoStory.callHome=function()
{
	if(Utils.mobileDeviceFlag){
		Android.stopAudioPlayer();
		Android.stopRecording(); 
	}
	VideoStory.stopDefaultAudio();
	VideoStory.addMenu();
};

	


