var StoryGame = {};
var Utils = {};
Utils.Path = '';
StoryGame.cnt = 0;
Utils.mobileDeviceFlag = false;
//StoryGame.gameType="learning";// practice learning
StoryGame.splitSentence = [];
StoryGame.currentStory;
StoryGame.sentenceCnt;
StoryGame.shuffleMixSentences = [];
StoryGame.stories=[];
StoryGame.randomIndex = 0;
StoryGame.score = 0;
StoryGame.level = 1;StoryGame.correctCnt=0,skipFlag=false; StoryGame.sentenceFillCnt = 0;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=0,resId=0,level=0,wrongAttemptCnt=0,sentenceDroppedArr=[];
var currentWord,totalLength,questionType="paragraph";
//function for loader
$(document).ready(function () {
	$(".se-pre-con").fadeOut("fast");
	if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag = true;

	setTimeout(function () {
		$('#coverpage').show();
		$('#gamePage,#home,#endPage').hide();
		var temp=(Math.floor(Math.random() * 2 + 0));
		StoryGame.gameType=(temp==0)? "learning": "practice";
		console.log(StoryGame.gameType +" Mode");
		//StoryGame.gameType="learning";
		if(StoryGame.gameType=="learning")
			$("#checkDiv").css("visibility","hidden");
		$("#soundDiv").css("visibility", "hidden");
		StoryGame.setImages();
		StoryGame.setEventListeners();
		if(StoryGame.hardCodedData['languageFont']!=null)
				setFontFamilyForLang("fonts/"+StoryGame.hardCodedData['languageFont']);		
		StoryGame.copyJson = JSON.parse(JSON.stringify(StoryGame.Data));
		totalLength=	StoryGame.copyJson.length;
	}, 300);
});

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");            
}

//function to set images
StoryGame.setImages = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/back1.png)";
	document.getElementById('splitSentencesDiv').style.backgroundImage="url("+Utils.Path+"images/board.png)";
	document.getElementById('sentenceDiv').style.backgroundImage="url("+Utils.Path+"images/board.png)";
	$('#logo').prop('src', Utils.Path + 'images/logo.png');
	$('#play').prop('src', Utils.Path + 'images/Play.png');
	$('#home').prop('src', Utils.Path + 'images/Home.png');
	$('#check').prop('src', Utils.Path + 'images/correct.png');
	$('#skip').prop('src', Utils.Path + 'images/skip.png');
	$('#next').prop('src', Utils.Path + 'images/next.png');
	$('#sound').prop('src', Utils.Path + 'images/Speaker.png');
	//$('#character').prop('src', Utils.Path + 'images/Boy-&-girl-for-giving-ANS.png');
	document.getElementById('replayImg').src=Utils.Path+"images/replay.png";
	document.getElementById('creditImg').src=Utils.Path+"images/credits.png";
	$(".icon").css("height","13vh");
	$("#home").css("height","16vh");
}

StoryGame.setEventListeners = function () {
	$("#home").on("click", function () {
		StoryGame.home();
	});
	$("#play").on("click", function () {
		$("#playGame,#coverPage").hide();//,#checkDiv
		$("#home,#gamePage").show();
		$("#splitSentencesDiv,#sentenceDiv").show();
		//populate(StoryGame.copyJson,5);
		StoryGame.playGame();
	});
	$("#replayImg").click(function(){
		$("#home").css("visibility","visible");
		StoryGame.playGame();
	});
	$("#nextDiv").click(function () {
		if (StoryGame.highlightTimer) {
			clearTimeout(StoryGame.highlightTimer);
			StoryGame.highlightTimer = null;
		}
		skipFlag=true;
		StoryGame.nextQue();
	}); 
	$("#credits").click(function(){
		//$("#acknowledgementDiv").empty();
		$("#acknowledgementDiv").css("visibility","visible");
	});
	document.getElementById('checkDiv').setAttribute("onclick", "StoryGame.validate()");
};

function populate(array1,length)
{
	var randomIndex;
	while (StoryGame.stories.length !== length) 
	{
	randomIndex = Math.floor(Math.random()*array1.length);
	if($.inArray(array1[randomIndex],StoryGame.stories) === -1)
	StoryGame.stories.push(array1[randomIndex]);
	}
}


//this function will execute on click of play button
StoryGame.playGame = function () {
			StoryGame.randomIndex = 0;
			$("#acknowledgementDiv").empty();
			$("#endPage").hide();
			StoryGame.cnt=0;
			StoryGame.stories=[];
			$("#home,#gamePage").show();
			$("#sentenceDiv").empty();
			populate(StoryGame.copyJson,5);
			StoryGame.getData();
}

StoryGame.playSounds = function (audio) {
	setTimeout(function () {
		document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + audio;
		document.getElementById("playSound").play();
	}, 150);
};
function getDuration(src, callback) {
	var duration = 0;
	if (getDurationFlag) {
		$('#playSound').on("loadedmetadata", function () {
			getDurationFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind('loadedmetadata');
			callback(duration, false);
		});
	}
	$('#playSound').prop('src', src);
}

//to create top span for splited sentence
StoryGame.getData = function () {
	var d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	StoryGame.cnt++;
	$('.wordsClass').remove();
	//$('#character').prop('src', Utils.Path + 'images/Boy-&-girl-for-giving-ANS.png');
	$("#skipDiv").css("visibility", "visible");
	$("#skip").on("click", function () {
		//$("#skip").hide();
		StoryGame.audioFinished(1, true);
		document.getElementById("playSound").pause();
	});
	$("#checkDiv").css("visibility","hidden");

	StoryGame.currentStory=StoryGame.stories[StoryGame.randomIndex].sentence;
	currentWord=StoryGame.stories[StoryGame.randomIndex].storyName;
	questionId=StoryGame.stories[StoryGame.randomIndex].questionId;

	$("#sentenceDiv").show();
	StoryGame.splitSentence = StoryGame.splitSentenceFun(StoryGame.currentStory);

	if (StoryGame.splitSentence[StoryGame.splitSentence.length - 1] === " " || StoryGame.splitSentence[StoryGame.splitSentence.length - 1] === "")
		StoryGame.splitSentence.pop();
	console.log(StoryGame.splitSentence);
	StoryGame.sentenceCnt = StoryGame.splitSentence.length;
	if(StoryGame.gameType=="learning")
	{
		totalMarks=	StoryGame.sentenceCnt;
	}
	else
		totalMarks=10;
	
	StoryGame.createEmptySpan(StoryGame.sentenceCnt, "topSentence", StoryGame.splitSentence, "sentenceDiv");//create top sentence span
	StoryGame.createStorySpan(StoryGame.splitSentence);
	$("#splitSentencesDiv").prop("class", "noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12 ");
	StoryGame.highlightTimer=setTimeout(function(){
		StoryGame.playStanza();
	},1000);
	
};

StoryGame.playStanza = function () {
	var playTime = 0;
	document.getElementById("playSound").pause();
	StoryGame.noOfWords = StoryGame.stories[StoryGame.randomIndex].readList.length;
	StoryGame.counter = 0;
		document.getElementById('playSound').currentTime = StoryGame.stories[StoryGame.randomIndex].readList[0].wordFrom;
	document.getElementById('playSound').src = Utils.Path+"sounds/"+StoryGame.stories[StoryGame.randomIndex].audio;
	document.getElementById("playSound").play();
	StoryGame.playWordsOnebyOne();
};

StoryGame.playWordsOnebyOne = function () {
	$('.scaleClass').removeClass('scaleClass');

	StoryGame.playTime = StoryGame.stories[StoryGame.randomIndex].readList[StoryGame.counter].wordDuration;
	$("#span" +StoryGame.counter).addClass('scaleClass');
	if (StoryGame.highlightTimer) {
		clearTimeout(StoryGame.highlightTimer);
		StoryGame.highlightTimer = null;
	}
	StoryGame.highlightTimer = setTimeout(function () {
		if (StoryGame.counter < StoryGame.noOfWords - 1) {
			StoryGame.counter++;
			StoryGame.playWordsOnebyOne();
			return 0;
		}
		else {
			document.getElementById('playSound').pause();
			$('.scaleClass').removeClass('scaleClass');
			StoryGame.counter = 0;
			StoryGame.audioFinished(1,false);	
		}
	}, StoryGame.playTime * 1000);
};

StoryGame.audioFinished = function (duration, skipFlag) {
	clearTimeout(StoryGame.highlightTimer);
	StoryGame.highlightTimer = null;
	$("#skipDiv").css("visibility", "hidden");
	$('.scaleClass').removeClass('scaleClass');
	if (skipFlag) {
		clearTimeout(StoryGame.answerAudio);
		StoryGame.answerAudio = null;
		$("#skip").off('click');
	}
	StoryGame.answerAudio = setTimeout(function () {
		//$("#skip").off('click'); 
		StoryGame.shuffleSentence();
		$("#splitSentencesDiv").empty();
		StoryGame.createStorySpan(StoryGame.shuffleMixSentences);
		$(".bottomSentences").addClass('animated flash');
		setTimeout(function () {
			$(".bottomSentences").removeClass('animated flash');
		}, 1000);
		StoryGame.addEvent();
	}, duration * 1000);
};
//call from create topSentence fn.
StoryGame.createEmptySpan = function (length, spanId, dataArray, parentDiv) {
	var newSpan,span,cnt=1,div;
	for (i = 0; i < length; i++) {

		div=document.createElement("div");
		div.setAttribute("id", "sentDivs" + i);
		div.setAttribute("class","noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
		$("#" + parentDiv).append(div);
		span = document.createElement("span");
		span.setAttribute("id", "noSpan" + cnt);
		$(span).text(cnt+". ");
		$(span).addClass("numbers");
		$(span).addClass("noPadding col-lg-1 col-md-1 col-xs-1 col-sm-1");
		newSpan = document.createElement("p");
		newSpan.setAttribute("id", spanId + i);
		$(newSpan).addClass("topSentences wordsClass transperant noPadding col-lg-11 col-md-11 col-xs-11 col-sm-11");
		if (dataArray[i].indexOf("!") == -1) {
			$(newSpan).text(dataArray[i] + ".");
			$(newSpan).data("word", dataArray[i] + ".");
		}
		else {
			$(newSpan).text(dataArray[i]);
			$(newSpan).data("word", dataArray[i]);
		}
		$(newSpan).data("sentenceSetFlag", 0);
		$(div).append(span);
		$(div).append(newSpan);
		cnt++;
	}
};

//add drag drop event
StoryGame.addEvent = function () {
	$('.topSentences').droppable({
		drop: StoryGame.handleDrop
	});
	$('.bottomSentences').draggable({
		cursor: 'move',
		helper: 'clone',
		start: function (e, ui) {
			$(ui.helper).addClass("ui-draggable-helper");
			$("#splitSentencesDiv").css("position", "static");
		}
	});
	//$( ".bottomSentences" ).draggable({ containment: "#gamePage", scroll: false });
};
//to create bottom span for splited sentence
StoryGame.createStorySpan = function (array) {
	var  row, i, length, splitArray = [],counter=0;
	for (i = 0; i < array.length; i++) {
		row = document.createElement('div');
		row.id = "storySentence" + i;
		row.className = "bottomSentences wordsClass";
		if (array[i].indexOf("!") == -1) {
			//$(row).text(array[i]+".");
			$(row).data("storySentence", array[i] + ".");
		}
		else {
			//$(row).text(array[i]);
			$(row).data("storySentence", array[i]);
		}

		//$(row).data("separateSentence",splitArray[j]+".");
		$("#splitSentencesDiv").append(row);
		splitArray = array[i].split(' ');
		splitArray=splitArray.filter(Boolean);
		length = splitArray.length;
		for (var j = 0; j < length; j++) {
			var span = document.createElement('span');
			span.className = "nopadding text-center text-bold spanClass";
			span.id = "span" + counter;
			if (j == length - 1) {
				if (array[i].indexOf("!") == -1) {
					$(span).text(splitArray[j] + ".");
					$(span).data("storySentence", splitArray[j] + ".");
				}
				else {
					$(span).text(splitArray[j]);
					$(span).data("storySentence", splitArray[j]);
				}
			}
			else {
				$(span).text(splitArray[j]);
				$(span).data("storySentence", splitArray[j]);
			}
			//span.innerHTML=splitArray[j];
			span.className = "storyWords";
			row.appendChild(span);
			counter++;
		}
	}
};

StoryGame.handleDrop = function (event, ui)//drop Sentence
{
	var src, dstDiv, dropId;
	if(StoryGame.gameType=="learning"){
	//clearTimeout(StoryGame.zoomInTimer);
	clearTimeout(StoryGame.manageClasses);
	}
	dstDiv = $(this);
	StoryGame.playSounds(StoryGame.sounds.drop);
	dropId = dstDiv.attr("id");
		$("#" + dropId).removeClass('animated zoomIn');
	$("#" + dropId).data("sentenceSetFlag", 1);
	//if(StoryGame.gameType=="learning")
		dstDiv.removeClass("transperant rightClass");
	//else
		src = ui.draggable;
	var txt = $(src).data('storySentence');//text();
	$("#" + dropId).text(txt);
	$("#" + dropId).addClass('animated zoomIn');

	setTimeout(function () {
		$("#" + dropId).removeClass('animated zoomIn');
		dstDiv.css("border-bottom","2px dashed #fff");
		clearTimeout(StoryGame.manageClasses);
		StoryGame.manageClasses=null;
		if(StoryGame.gameType=="learning")
			StoryGame.validate(dropId);
	}, 1000);
	if(StoryGame.gameType=="practice")
		StoryGame.checkFillPosition();
};

//check the all sentences are filled or not
StoryGame.checkFillPosition = function () {
	 StoryGame.sentenceFillCnt = 0;
//	clearTimeout(StoryGame.zoomInTimer);
	for (i = 0; i < StoryGame.sentenceCnt; i++) {
		if ($("#topSentence" + i).data("sentenceSetFlag") == 1)
		StoryGame.sentenceFillCnt++;
	}
	if(StoryGame.sentenceFillCnt==StoryGame.sentenceCnt)
	{$("#checkDiv").css("visibility","visible");
		//$("#checkDivDiv").css("margin-top","-7%");	
	}
	else
	$("#checkDiv").css("visibility","hidden");
};

StoryGame.validate = function (id) {
		var cnt = 0;
		//clearTimeout(StoryGame.zoomInTimer);
		clearTimeout(StoryGame.manageClasses);
	if(StoryGame.gameType=="learning"){
		if (($("#"+id).text() != $("#" + id).data('word')) || $("#" +id).data('sentenceSetFlag') == 0) {
			$("#" + id).addClass("wrongClass");
			$("#" + id).data("sentenceSetFlag", 0);
			wrongAttemptCnt++;
		}
		else {
		if($.inArray( id,sentenceDroppedArr)==-1){
			sentenceDroppedArr.push(id);
					StoryGame.correctCnt++;
			}
			$("#" + id).addClass("rightClass");
		/* 	scoredMarks=StoryGame.correctCnt;
			if (Utils.mobileDeviceFlag)
				Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
		console.log(questionId, scoredMarks, totalMarks, level, startTime); */
		}
	}//Prctice
	else{
			for (i = 0; i < StoryGame.sentenceCnt; i++) {
				if (($("#topSentence" + i).text() != $("#topSentence" + i).data('word')) || $("#topSentence" + i).data('sentenceSetFlag') == 0) {
					$("#topSentence" + i).addClass("wrongClass");
					$("#topSentence" + i).data("sentenceSetFlag", 0);
				}
				else {
						id="topSentence" + i;
						if($.inArray( id,sentenceDroppedArr)==-1){
							sentenceDroppedArr.push(id);
									StoryGame.correctCnt++;
							}
					$("#topSentence" + i).addClass("rightClass");
				}
			}
		}
	//execute if all are correct
	if (StoryGame.correctCnt == StoryGame.sentenceCnt) {
		StoryGame.score += 10;
		/* 	if(StoryGame.gameType=="practice"){
				scoredMarks=10;  */
				if (Utils.mobileDeviceFlag)
						Android.addLearntData(currentWord,totalLength,questionType);
				console.log(currentWord,totalLength,questionType); 
			
			StoryGame.playSounds(StoryGame.sounds.correct);
		//	$('#character').prop('src', Utils.Path + 'images/Boy-&-girl-for-correct-ANS.png');
			$('.bottomSentences').draggable('disable');
			StoryGame.nextQue();
		}
	else {
		if(StoryGame.gameType=="practice"){
				scoredMarks=0;
				StoryGame.playSounds(StoryGame.sounds.wrong);
			/* 	if (Utils.mobileDeviceFlag)
					Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
				console.log(questionId, scoredMarks, totalMarks, level, startTime); */
				StoryGame.nextQue();
				$("#checkDiv").css("visibility","hidden");
				//$("#checkDivDiv").hide();
		}
			if(StoryGame.gameType=="learning"){
			 	skipFlag=false;
			}
	}
	if(StoryGame.manageClasses)
	{
		clearTimeout(StoryGame.manageClasses);
		StoryGame.manageClasses=null;
	}
	StoryGame.manageClasses=setTimeout(function () {
		$('.wrongClass').addClass("transperant");
		$('.wrongClass').removeClass("wrongClass");
		$('.rightClass').removeClass("rightClass");
		
		//console.log(StoryGame.splitSentence);
		 for (var i = 0; i < StoryGame.sentenceCnt; i++) {
			if (StoryGame.splitSentence[i].indexOf("!") == -1) {
				$("#topSentence" +i ).text(StoryGame.splitSentence[i] + ".");
				//$("#topSentence" + i).data("word", StoryGame.splitSentence[i] + ".");
			}
			else {
				$("#topSentence" + i).text(StoryGame.splitSentence[i]);
				//$("#topSentence" + i).data("word", StoryGame.splitSentence[i]);
			}
			$("#topSentence"+ i).className = "transperant"; 
			//$("#topSentence"+i).data('sentenceSetFlag',0);
		}
	}, 1300);
};
StoryGame.nextQue=function(){
	document.getElementById('playSound').src='';
	document.getElementById('playSound').pause();
	clearTimeout(StoryGame.highlightTimer);
	StoryGame.highlightTimer = null;
	clearTimeout(StoryGame.answerAudio);
	StoryGame.answerAudio = null;
	$('.scaleClass').removeClass('scaleClass');	
	if(StoryGame.gameType=="learning"){ 
		scoredMarks=StoryGame.correctCnt;
	if(skipFlag && wrongAttemptCnt==0 && StoryGame.correctCnt==0)
			scoredMarks=-1;
/* 	else if(wrongAttemptCnt>0)
			scoredMarks=0; */
	if (Utils.mobileDeviceFlag)
			Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
		console.log(questionId, scoredMarks, totalMarks, level, startTime);		
	}
	if(StoryGame.gameType=="practice"){
		if(skipFlag && !StoryGame.sentenceFillCnt)
			scoredMarks=-1;
		else if(StoryGame.correctCnt == StoryGame.sentenceCnt)
			scoredMarks=10;
		else
			scoredMarks=0;
		if (Utils.mobileDeviceFlag)
					Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
			console.log(questionId, scoredMarks, totalMarks, level, startTime);
	}
		StoryGame.correctCnt =0;
		wrongAttemptCnt=0;
		StoryGame.sentenceFillCnt=0;
		sentenceDroppedArr=[];
		
		StoryGame.highlightTimer=setTimeout(function () {
			if(StoryGame.cnt<5){
				skipFlag=false;
				$("#sentenceDiv").empty();
				StoryGame.randomIndex++;
				StoryGame.getData();
			}
			else
					StoryGame.showEndPage();
		}, 1000);
}

StoryGame.showEndPage=function(){
	document.getElementById("playSound").pause();
	document.getElementById("gamePage").style.display="none";
	document.getElementById("endPage").style.display="block";
	$("#home,#acknowledgementDiv").css("visibility","hidden");
	$("#acknowledgementDiv").empty();
	StoryGame.AcknowledgementPage();
	$("#gameOver").text(StoryGame.hardCodedData.gameOver);
}

StoryGame.AcknowledgementPage=function()
{
var i=0,div;
gameOver.innerHTML=StoryGame.hardCodedData.gameOver;
console.log(Object.keys(StoryGame.AcknowledgementPageData).length);
for(i=0;i<Object.keys(StoryGame.AcknowledgementPageData).length;i++)
{
	div=document.createElement('div');
	div.className="fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=Object.keys(StoryGame.AcknowledgementPageData)[i]+" : "+Object.values(StoryGame.AcknowledgementPageData)[i];
	acknowledgementDiv.appendChild(div);
}
div=document.createElement('div');
div.className="fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
div.innerHTML=StoryGame.hardCodedData['createdOn'];
acknowledgementDiv.appendChild(div);

}

//Mix-up the sentences
StoryGame.shuffleSentence = function () {
	StoryGame.shuffleMixSentences = shuffleArray(StoryGame.splitSentence.slice(0));
	//console.log(StoryGame.splitSentence);
};

// Split Sentence
StoryGame.splitSentenceFun = function (array) {
	return (array.split("."));
};

// Random No Generator
StoryGame.randomGenerator = function () {
	return (Math.floor(Math.random() * StoryGame.copyJson.length + 0));
};

function shuffleArray(array) {
	var i, j, temp;
	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;
	}
	return array;
}

StoryGame.home = function () {
	if(StoryGame.gameType=="practice"){
			scoredMarks=0;
	}
	if(StoryGame.gameType=="learning"){
		scoredMarks=StoryGame.correctCnt ;
	}
	if (Utils.mobileDeviceFlag)
		Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
	console.log(questionId, scoredMarks, totalMarks, level, startTime);		
	location.reload();
};

