var StoryGame = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
StoryGame.cnt = 1;
StoryGame.splitSentence = [];
StoryGame.currentStory;
StoryGame.sentenceCnt;
StoryGame.shuffleMixSentences = [];
StoryGame.score = 0;
StoryGame.level = 1;StoryGame.correctCnt=0;

//var questionId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0;
//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,#check').hide();
		$("#soundDiv").css("visibility", "hidden");
		StoryGame.setImages();
		StoryGame.setEventListeners();
		StoryGame.copyJson = JSON.parse(JSON.stringify(StoryGame.Data));
	}, 300);
});
//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/storybook.png)";
	//document.getElementById('sentenceDiv').style.backgroundImage="url("+Utils.Path+"images/storybook1.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');
	$('#sound').prop('src', Utils.Path + 'images/Speaker.png');
}
StoryGame.setEventListeners = function () {
	$("#home").on("click", function () {
		StoryGame.home();
	});
	$("#play").on("click", function () {
		$("#playGame,#next,#coverPage").hide();//,#checkDiv
		$("#home,#gamePage").show();
		$("#splitSentencesDiv,#sentenceDiv").show();
		StoryGame.playGame();
	});
	document.getElementById('checkDiv').setAttribute("onclick", "StoryGame.validate()");
	document.getElementById('soundDiv').setAttribute("onclick", "StoryGame.playCurrentSentence()");
	//document.addEventListener('touchmove', function() { e.preventDefault(); }, { passive:false });
};

//this function will execute on click of play button
StoryGame.playGame = function () {
	console.log(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").hide();
	//$("#soundDiv").css("visibility","visible");
	StoryGame.getData();
	//if(StoryGame.level!=0){
	StoryGame.cnt++;
	//}	
}

StoryGame.playSounds = function (audio) {
	setTimeout(function () {
		document.getElementById('playSound').src = Utils.Path + 'sounds/' + 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 () {
	StoryGame.randomIndex = 0;
	StoryGame.randomIndex = StoryGame.randomGenerator();
	StoryGame.currentStory = StoryGame.copyJson[StoryGame.randomIndex].sentence;
	console.log(StoryGame.currentStory);
	//StoryGame.playCurrentSentence();
	$("#sentenceDiv").show();
	StoryGame.splitSentence = StoryGame.splitSentenceFun(StoryGame.currentStory);
	if (StoryGame.splitSentence[StoryGame.splitSentence.length - 1] === "")
		StoryGame.splitSentence.pop();
	console.log(StoryGame.splitSentence);
	StoryGame.sentenceCnt = StoryGame.splitSentence.length;
	//console.log(StoryGame.sentenceCnt);
	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 ");
	setTimeout(function(){
		StoryGame.playStanza();
	},1000);
	
	//$('.bottomSentences').draggable('disable');
	 /* StoryGame.abc=setTimeout(function(){
		//StoryGame.playSounds(StoryGame.copyJson[StoryGame.randomIndex].audio);
		//getDurationFlag=true;
		//callback=StoryGame.audioFinished;
		//getDuration(Utils.Path+"sounds/"+StoryGame.copyJson[StoryGame.randomIndex].audio,callback);
		//document.getElementById("playSound").play();
		StoryGame.copyJson.splice(StoryGame.randomIndex,1);
	},500);  */
};

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

StoryGame.playWordsOnebyOne = function () {
	$('.scaleClass').removeClass('scaleClass');
	StoryGame.playTime = StoryGame.copyJson[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.abc = null;
	StoryGame.answerAudio = setTimeout(function () {
		//$("#skip").off('click'); 
		StoryGame.shuffleSentence();
		$("#splitSentencesDiv").empty();
		StoryGame.createStorySpan(StoryGame.shuffleMixSentences);
		$(".bottomSentences").addClass('animated lightSpeedIn');
		setTimeout(function () {
			$(".bottomSentences").removeClass('animated lightSpeedIn');
		}, 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 newSpan, 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++;
		}
	}

	/* 	for(i=0;i<array.length;	i++)
		{	
			newSpan= document.createElement("div");
			newSpan.setAttribute("id","storySentence"+i);
			if(array[i].indexOf("!") == -1)
			{
				$(newSpan).text(array[i]+".");
				$(newSpan).data("storySentence",array[i]+".");
			}
			else{
				$(newSpan).text(array[i]);
				$(newSpan).data("storySentence",array[i]);
			}
			newSpan.className="bottomSentences wordsClass";
			$("#splitSentencesDiv").append(newSpan);
		} */
};

StoryGame.handleDrop = function (event, ui)//drop Sentence
{
	var src, dstDiv, dropId;
	dstDiv = $(this);
	StoryGame.playSounds(StoryGame.sounds.drop);
	dropId = dstDiv.attr("id");
	$("#" + dropId).data("sentenceSetFlag", 1);
	dstDiv.removeClass("transperant");
	src = ui.draggable;
	var txt = $(src).data('storySentence');//text();
	$("#" + dropId).text(txt);
	$("#" + dropId).addClass('animated zoomIn');
	setTimeout(function () {
		$("#" + dropId).removeClass('animated zoomIn');
		StoryGame.validate(dropId);
	}, 1500);

};

StoryGame.validate = function (id) {
	//for (i = 0; i < StoryGame.sentenceCnt; i++) {
		if (($("#"+id).text() != $("#" + id).data('word')) || $("#" +id).data('sentenceSetFlag') == 0) {
			$("#" + id).addClass("wrongClass");
			$("#" + id).data("sentenceSetFlag", 0);
		}
		else {
			StoryGame.correctCnt++;
			$("#" + id).addClass("rightClass");
		}
	//}
	//execute if all are correct
	if (StoryGame.correctCnt == StoryGame.sentenceCnt) {
		StoryGame.score += 10;
		console.log(StoryGame.score);
		StoryGame.playSounds(StoryGame.sounds.correct);
		$('#character').prop('src', Utils.Path + 'images/Boy-&-girl-for-correct-ANS.png');
		$('.bottomSentences').draggable('disable');
		setTimeout(function () {
			$("#sentenceDiv").empty();
			StoryGame.playGame();
		}, 2000);
	}
	/* else {
		StoryGame.playSounds(StoryGame.sounds.wrong);
		//$("#checkDiv").hide();
	} */

	setTimeout(function () {
		$('.wrongClass').addClass("transperant");
		$('.wrongClass').removeClass("wrongClass");
		$('.rightClass').removeClass("rightClass");

		console.log(StoryGame.splitSentence);
	//	$("#"+id).text(StoryGame.splitSentence[i])
		//$("#"+id).className = "transperant"; 
		 for (var i = 0; i < StoryGame.sentenceCnt; i++) {
			if (StoryGame.splitSentence[i].indexOf("!") == -1) {
				$("#topSentence0" +i ).text(StoryGame.splitSentence[i] + ".");
				$("#topSentence0" + i).data("word", StoryGame.splitSentence[i] + ".");
			}
			else {
				$("#topSentence0" + i).text(StoryGame.splitSentence[i]);
				$("#topSentence0" + i).data("word", StoryGame.splitSentence[i]);
			}
			$("#topSentence"+ i).className = "transperant"; 
		}
		/* 	$("#" + i).text(StoryGame.splitSentence[i] + ".");
			$("#" + i).className = "transperant"; 
		} */
	}, 1200);
};

//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 (Utils.mobileDeviceFlag)
		Android.stopTts();
	location.reload();
};