/* JavaScript Document  
/  @author Ch-Nityanand Ojha
*/

var GRADE = 1;

var font_size = [40, 35, 30];
var rubricfntSize = font_size[GRADE - 1];
var optionFntSize = rubricfntSize - 5;
var quesfntSize = rubricfntSize - 5;
var VERT_MARG = 15;

var SAVE_ANS = true;
var CASE_SENS = true;

var drawNextQuestionDelay = 3000;
var drawIncorrectQuestionDelay = 4000;
var makeAnimationSpaceDelay = 3500;
var playAnimationDelay = 60;
var introDelay = 1000;
var visibility = ["hidden", "visible"];

var colors = { right: "#007d00", wrong: "#FF0000", input: "#000000" };


var fontFace = "Rubric, sans-serif";
var fontFace1 = "Ans, sans-serif";
var Max;
var currentQ = 0;
var currentLen = 0;

var colorObj = { initial: "#ffff99", select: "#99ffff", defaultText: "#000000", correctText: "#007d00", wrongText: "#FF0000" };
//var rArr = ["exlent","funtastic","good","goodjob"];
//var wArr = ["thatsincorrect","thatsnotright"];
var audio;

var optDiv;
var clickCount = 0;
var clickedArr = [];
var rCount = 0;
var wCount = [];
var interval;
var qText = [];
var sNo;
var preNxt;
var _main;
var fVideo;
var optStatus = [];
var storedData = [];
var inputCount = 0;

var _rubricTxt;
var checkSol;
var _submit, _solution;
var filled = [];
var AnsArr = [];
var filledCount = 0;
var optionBox;
var allInput = "";
var MaxInput = 0;
var allDone = 0;
var cData = {};
var qAttempts;
var SCO;
var Status;
var scoreDisp;
var finalScore = 0;

//window.onload = startIntro();
//createLayout();

var introVid;

//////// G for grammer, V for vocabulary..........
//var introType = "g";
startIntro();

function playVideoIntro() {
	introVid.removeEventListener("click", playVideoIntro);
	introVid.play();
	introVid.setAttribute("autofocus", "");
}

function startIntro() {

	introVid = createTag("video");
	titleText = createTag("div");
	document.body.appendChild(introVid);

	introVid.setAttribute("playsinline", "");
	introVid.addEventListener("click", playVideoIntro);
	var posterPath = "../__images/coverImg_" + data.intro.toLowerCase() + ".jpg";
	introVid.setAttribute("poster", posterPath);


	var sourceWebm = document.createElement("source");
	var sourceMp4 = document.createElement("source");
	introVid.appendChild(sourceWebm);
	introVid.appendChild(sourceMp4)

	introVid.style.position = "absolute";
	introVid.style.top = "0px";

	introVid.addEventListener("ended", onEnd);

	//SAVE_ANS && fillArray();
	//titleText.style.width = "1280px";
	titleText.style.position = "absolute";
	titleText.style.fontFamily = "Title";
	titleText.style.opacity = 0;
	titleText.style.textAlign = "center";
	titleText.style.fontSize = "50px";
	document.body.appendChild(titleText);
	console.log("START........");

	if (data.intro.length == 0)
		introVid.style.visibility = 'hidden';


	switch (data.intro.toLowerCase()) {
		case "g":
			titleText.innerHTML = data.title || data._title;
			titleText.style.width = "630px";
			titleText.style.top = "400px";
			titleText.style.left = "590px";
			titleText.style.color = "#000";
			sourceWebm.src = "../__intro/Title_Grammar.webm"
			sourceMp4.src = "../__intro/Title_Grammar.mp4"
			introVid.load();
			introVid.play();
			setTimeout(showTitle, 3000);
			break;
		case "v":
			titleText.innerHTML = data.title || data._title;
			titleText.style.width = "712px";
			titleText.style.top = "400px";
			titleText.style.left = "275px";
			titleText.style.color = "#000";
			sourceWebm.src = "../__intro/Title_Vocab.webm"
			sourceMp4.src = "../__intro/Title_Vocab.mp4"
			introVid.load();
			introVid.play();
			setTimeout(showTitle, 3000);
			break;
		case "r":
			titleText.innerHTML = data.title || data._title;
			titleText.style.width = "712px";
			titleText.style.top = "400px";
			titleText.style.left = "205px";
			titleText.style.color = "#000";
			introVid.src = "../__intro/Title_Thinking.ogv"
			introVid.load();
			introVid.play();
			setTimeout(showTitle, 5000);
			break;
		default:
			feedbackAnim();
			introVid.removeEventListener("ended", onEnd);
			$(titleText).animate({ opacity: 0 }, 1);
			$(introVid).animate({ opacity: 0 }, 1, createLayout);
			document.getElementById("main").style.backgroundImage = "url('../__images/image/" + spriteOBJ.background + "')";
			break;

	}

}

function showTitle() {
	$(titleText).animate({ opacity: 1 }, 1000);

}


function onEnd() {
	feedbackAnim();
	document.getElementById("main").style.backgroundImage = "url('../__images/image/" + spriteOBJ.background + "')";
	introVid.removeEventListener("ended", onEnd);
	$(titleText).animate({ opacity: 0 }, introDelay);
	$(introVid).animate({ opacity: 0 }, introDelay, createLayout);
}

function resetActivity() {
	console.log("rajji");
	finalScore = 0;
	allDone=0;
	scoreDisp.innerHTML = finalScore + "/" + quesArr.length;
	// e.target.removeEventListener("click", resetActivity);
	// e.target.removeEventListener("click", resetActivity);
	cData = {}
	storedData = []
	arrangeOptions(currentQ);
	for (var i = 0; i < inputCount; i++) {
		//console.log("Resetting CHECK:  ",getElement("#in"+i).value);
		if (!getElement("#in" + i).isDone) {
			//console.log("Resetting:  ",getElement("#in"+i).value);
			getElement("#in" + i).value = "";
			getElement("#in" + i).className = "inClass";
			getElement("#in" + i).style.color = colors.input;
			getElement("#in" + i).disabled = false;
		}

	}
	// checkNextPrev();
	// enableSolution(currentQ);
	ResetBtn.style.pointerEvents = "none";
	ResetBtn.style.opacity = 0.5;
	// e.target.removeEventListener("click", resetActivity);
	// e.target.classList.add("inactive");
}

function addScorm(){
	SCO = pipwerks.SCORM;
	SCO.connection.initialize();
	console.log("INIT:  ", SCO.connection.isActive);

	if (!SCO.connection.isActive) {
		return;
	}
	let status = SCO.get("cmi.core.lesson_status");
	let minScore = SCO.get("cmi.core.score.min");
	if (!minScore) {
		SCO.set("cmi.core.score.min", 0)
		SCO.set("cmi.core.score.max", storedData.length)
	}

	if (status !== "completed") {

		finalScore = SCO.get("cmi.core.score.raw") || 0;
		finalScore = parseInt(finalScore);
		scoreDisp.innerHTML = finalScore + "/" + quesArr.length;
		console.log("FIANL : ", finalScore);
		if (storedData.length == finalScore) {
			SCO.set("cmi.core.lesson_status ", "passed");
		}
	}
	else {

		setScore = SCO.get("cmi.core.score.raw") || 0;
		finalScore = parseInt(setScore);
		scoreDisp.innerHTML = finalScore + "/" + quesArr.length;
		ResetBtn.style.visibility = "visible";
		ResetBtn.addEventListener("click", () => { resetActivity() });

	}

	let lmsData = SCO.get("cmi.suspend_data");

	console.log("LMS DATA: ", lmsData);
	if (lmsData.length) {
		receiveFullData = lmsData.split("*")
		storedData = JSON.parse(receiveFullData[0]);
		qAttempts=receiveFullData[1]
		allDone=JSON.parse(receiveFullData[2])
	}
	saveData();
	console.log("DATA: ", lmsData);
}

function feedbackAnim() {
	_main = getElement("#main");
	var canvasAnim = document.createElement("canvas");
	_main.appendChild(canvasAnim);
	canvasAnim.width = spriteOBJ.feedbackAnim.frames.width;
	canvasAnim.height = spriteOBJ.feedbackAnim.frames.height;
	canvasAnim.style.position = "absolute";
	canvasAnim.style.top = spriteOBJ.animTop + "px";
	canvasAnim.style.left = spriteOBJ.animLeft + "px";
	canvasAnim.setAttribute("id", "canvasAnim");

	var stage = new spritejs.Stage("canvasAnim");

	var compSprite = new spritejs.SpriteSheet(spriteOBJ.feedbackAnim);
	compSprite.on("error", function (event) {
		console.log("Error ", event);
	});

	feedbackAnim = new spritejs.Sprite(compSprite, "ideal");
	stage.addChild(feedbackAnim);


	spritejs.Ticker.addEventListener("tick", stage);
}


function createLayout() {
	//console.log("TTT:  ",TEMP);
	document.body.removeChild(introVid);
	introVid = null;
	document.body.removeChild(titleText);
	titleText = null;
	_main = getElement("#main");

	
	for (var i = 0; i < data._quesArr.length; i++) {
		storedData.push(cData);
	}

	_rubricTxt = createTag("div");
	_rubricTxt.setAttribute("id", "rubricDiv");
	_main.appendChild(_rubricTxt);

	rubricAud = document.createElement("span");
	_rubricTxt.append(rubricAud)
	rubricAud.setAttribute("id", "rubricAud")
	rubricAud.classList.add("customButton")
	rubricAud.style.backgroundImage = "url('../__images/audOFF.png')";
	rubricAud.addEventListener("click", onRubricAudClicked)

	rubText = document.createElement("span")
	_rubricTxt.append(rubText)
	rubText.innerHTML = data.rubric || data._rubric;


	_rubricTxt.style.fontSize = rubricfntSize + "px";
	_rubricTxt.style.fontFamily = fontFace;
	_rubricTxt.style.color = "#3d8eb9";
	//_rubricTxt.innerHTML = rubric;
	//console.log("MAXXXXXXXXXXXXXXXXXXXXXX: ", _rubricTxt.offsetWidth);
	_rubricTxt.style.width = Math.min(1200, _rubricTxt.offsetWidth) + "px";

	optionBox = createTag("div");
	optionBox.setAttribute("id", "textBox");
	_main.appendChild(optionBox);
	optionBox.style.position = "absolute";
	//optionBox.style.top = upperSpace + "px";
	optionBox.style.left = outerSpace + "px";
	optionBox.style.width = MAX_WIDTH + "px";

	//optionBox.style.top = upperSpace + "px";



	optionBox.style.visibility = "hidden";

	sNo = createTag("div");
	sNo.setAttribute("id", "SnoDiv");

	_main.appendChild(sNo);
	sNo.style.height = 50 + "px";
	sNo.style.width = 60 + "px";
	sNo.style.left = outerSpace - (LINE_HEIGHT * 1.5) + "px";
	sNo.style.fontSize = quesfntSize + "px";
	sNo.style.visibility = "hidden";



	optDiv = createTag("div");
	optDiv.setAttribute("id", "optDv");

	_main.appendChild(optDiv);
	optDiv.style.visibility = "hidden";
	//console.log(optDiv.id);
	optDiv.style.left = outerSpace + 20 + "px";
	optDiv.style.width = MAX_WIDTH + "px";




	Max = quesArr.length;

	checkSol = createTag("div");
	checkSol.setAttribute("id", "checkSolution");
	_main.appendChild(checkSol);

	
	ResetBtn = document.createElement("div");
	//ResetBtn.className = "answer";
	ResetBtn.innerHTML = "RESET";
	ResetBtn.setAttribute("id", "Reset");
	checkSol.appendChild(ResetBtn);

	
	_solution = createTag("div");
	_solution.setAttribute("id", "answerBtn");
	_solution.innerHTML = "SOLUTION";
	checkSol.appendChild(_solution);

	_submit = createTag("div");
	_submit.setAttribute("id", "submitBtn");
	_submit.innerHTML = "CHECK";
	checkSol.appendChild(_submit);


	getElement("#submitBtn").addEventListener("click", onSubmit);
	getElement("#answerBtn").addEventListener("click", onSolution);
	disableSubmitBTN();
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	preNxt = createTag("div");
	preNxt.setAttribute("id", "preNext");
	_main.appendChild(preNxt);

	preNxt.style.top = "535px";
	preNxt.style.left = "335px";
	preNxt.style.visibility = "hidden";

	preBtn = createTag("div");
	preBtn.className = "prenxt";
	// preBtn.style.backgroundImage = "url('Assets/images/arrow.png')";
	preBtn.setAttribute("id", "prev");
	//preBtn.style.transform = "rotate(180deg)";
	preBtn.style.cssFloat = "left";
	preNxt.appendChild(preBtn);
	disableObj(preBtn);

	nxtBtn = createTag("div");
	nxtBtn.className = "prenxt";
	nxtBtn.setAttribute("id", "next");
	nxtBtn.style.cssFloat = "right";
	preNxt.appendChild(nxtBtn);

	preNxt.addEventListener("click", onNextPrev);

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	_main = document.getElementById("main")
	audio = document.createElement("audio");
	_main.appendChild(audio);
	sourceMP3 = document.createElement("source");
	audio.appendChild(sourceMP3)
	sourceOGG = document.createElement("source");
	audio.appendChild(sourceOGG)


	//soundComplete();

	//disableSolution();
	if (quesArr.length <= 1) {
		sNo.style.display = "none";
		getElement("#preNext").style.display = "none";
	}
	soundComplete()

	if (quesArr.length <= 1) {
		sNo.style.display = "none";
		getElement("#preNext").style.display = "none";
	}
	try {
		addScorm();
	} catch (err) {
	}
	arrangeOptions(currentQ);
}

function onRubricAudClicked(e) {
	rubricAud.style.backgroundImage = "url('../__images/audON.png')";

	sourceOGG.src = "Assets/rubric/rubric.ogg";
	sourceMP3.src = "Assets/rubric/rubric.mp3";
	audio.load();


	audio.play();
	audio.addEventListener("ended", rubComplete);
}

function rubComplete() {
	audio.removeEventListener("ended", rubComplete);
	rubricAud.style.backgroundImage = "url('../__images/audOFF.png')";
	// addQuestion(0);
}


function onNextPrev(e) {
	//console.log("NPNPNPNPNPNNP:  ", currentQ);	
	if (e.target.id == "prev") {
		//console.log("PREV...........",currentQ);
		arrangeOptions(--currentQ);

	} else if (e.target.id == "next") {
		//console.log("NEXT...........",currentQ);
		arrangeOptions(++currentQ);
	}
}


function soundComplete() {
	optDiv.style.visibility = "visible";
	sNo.style.visibility = "visible";
	getElement("#checkSolution").style.visibility = "visible";
	getElement("#answerBtn").style.visibility = "visible";
	getElement("#submitBtn").style.visibility = "visible";
	preNxt.style.visibility = "visible";

	//audio.removeEventListener("ended", soundComplete);
	arrangeOptions();

	var scorePanel = document.createElement("div");
	_main.appendChild(scorePanel);
	scorePanel.setAttribute("id", "scorePanel");

	var scoreMeter = document.createElement("span");
	scoreMeter.innerHTML = "Score : ";
	scorePanel.appendChild(scoreMeter);
	scoreMeter.setAttribute("id", "scoreMeter");
	scoreDisp = document.createElement("span");
	// scoreDisp.innerHTML = setScore + "/" + quesArr.length;
	scorePanel.appendChild(scoreDisp);
	scoreDisp.setAttribute("id", "scoreDisp")
}


function arrangeOptions() {
	feedbackAnim.gotoAndStop("ideal");
	var opt;
	var count = 0;
	var prevW = 0;
	var offset;
	var ln = 0;
	var wd = 0;
	var cName = "";
	var temp = [];
	var count = 0;
	var quesData;

	clickCount = 0;
	inputCount = 0;
	cleanup();
	enableSolution(currentQ);
	disableSubmitBTN();
	checkNextPrev();
	sNo.innerHTML = (currentQ + 1);

	clickedArr = [];
	filled = [];
	qText = quesArr[currentQ];

	try {

		cData = storedData[currentQ];
		rCount = getFilledCount(cData.ans);
		(cData.allDone) ? disableSolution() : enableSolution();
		console.log("DATA FETCHED:   ", cData);
	} catch (err) {
		cData = { 'attempt': [], 'ans': [], 'allDone': false };
		//temp = [];
		qAttempts = 0;
		rCount = 0;
		for (var ii = 0; ii < quesArr[currentQ].length; ii++) {
			//console.log("TEST: ",quesArr[currentQ][ii].ans[jj]);
			for (var jj = 0; jj < quesArr[currentQ][ii].ans.length; jj++) {
				//console.log(quesArr[currentQ][ii].ans[jj]);
				cData.attempt.push(0);
				cData.ans.push("");
			}
		}


	}

	fillOptionBox();
	//console.log("STORE: ",currentQ, storedData[currentQ]);

	for (var i = 0; i < qText.length; i++) {
		//console.log("AAAAAAAAA: ", i);
		var innerText = createTag("div");
		innerText.className = "innerQ";
		innerText.style.display = "block";
		innerText.style.fontSize = quesfntSize + "px";
		quesData = getQuestionData(qText[i].ques);
		innerText.innerHTML = quesData;
		optDiv.appendChild(innerText);
	}

	setupInputFields(cData);
	//(rCount == inputCount)?disableSolution():enableSolution(currentQ);	
	resetBoxes();

}

function resetBoxes() {
	/*var topPos = upperSpace + optionBox.offsetHeight+30;
	
	sNo.style.top = topPos+ "px";	
	optDiv.style.top = topPos + "px";*/


	var tt = _rubricTxt.offsetTop + (_rubricTxt.offsetHeight) + (VERT_MARG * GRADE);
	optionBox.style.top = tt+50 + "px";
	tt += optionBox.offsetHeight + (VERT_MARG * GRADE);

	sNo.style.top = 275 + "px";
	optDiv.style.top = 275 + "px";
}

function fillOptionBox() {
	var tag;
	emptyOptionBox();
	//console.log("filling....", optionArr[currentQ]);
	for (var i = 0; i < optionArr[currentQ].length; i++) {

		tag = createTag("span");
		tag.className = "optTxt";
		tag.style.fontSize = quesfntSize + "px";
		tag.style.display = "inline-block";
		//tag.style.margin = "10px 20px 10px 20px";
		tag.style.marginLeft = tag.style.marginRight = optMargin + "px";
		tag.style.marginBottom = tag.style.marginTop = Math.max(optMargin / 2, 10) + "px";

		tag.innerHTML = optionArr[currentQ][i];

		optionBox.appendChild(tag);
	}

	//console.log("VIVIVI:  ",optionArr[currentQ].length, Boolean(optionArr[currentQ].length), Number(Boolean(optionArr[currentQ].length))); 
	optionBox.style.visibility = visibility[Number(Boolean(optionArr[currentQ].length))];//
}


function emptyOptionBox() {
	while (optionBox.firstChild) {
		optionBox.removeChild(optionBox.firstChild);
	}

}


function getQuestionData(str) {
	var data = "";
	var arr = str.split(" ");
	var output = "";

	for (var i = 0; i < arr.length; i++) {
		data = (arr[i].length) && allMark(arr[i]) && replaceMark(arr[i]);
		arr[i] = !data ? arr[i] : data;
	}


	output = arr.join(" ");
	return output;
}

function allMark(str) {
	//console.log("CHECKING:  ", str);		
	currentLen = 0;
	while (str[currentLen++] == MARK);
	currentLen--;

	if (currentLen == str.length - 1 && str[currentLen] == ".") {
		//console.log("BBBBBBOOOO:  ", currentLen, Boolean(currentLen-1));
		return Boolean(currentLen);
	}
	return (currentLen == str.length);

}


function replaceMark(str) {
	var lastChar = (str[str.length - 1] == ".") ? "." : "";
	//console.log("==============", lastChar, str, str[str.length-1]);
	var input = "<input class='inClass' autocomplete='off' spellcheck=false id=in" + inputCount++ + " >";
	input = input.concat(lastChar);
	//console.log("-----LAST : ", input);
	filled.push(undefined);
	return input;
}

function setupInputFields(_cData) {
	var counter = 0;
	var maxlen;
	var offset = quesfntSize;
	var obj;
	var MAX = 0;
	var dataType = " ";
	//for(var i=0;i<quesArr.length;i++)

	for (var j = 0; j < quesArr[currentQ].length; j++) {
		for (var k = 0; k < quesArr[currentQ][j].ans.length; k++) {
			maxlen = getMaxLen(quesArr[currentQ][j].ans[k]);
			MAX = Math.max(MAX, maxlen);
			obj = getElement("#in" + counter);
			//console.log("CCCCCCCCC:  ",maxlen, maxlen*offset, offset);

			obj.setAttribute("type", " ");
			obj.setAttribute("data-type", dataType);
			obj.setAttribute("maxlength", (maxlen + 1).toString());
			//obj.attempts = 0;
			obj.style.fontSize = quesfntSize + "px";
			//console.log("WIDTH:  ", obj.clientWidth);	
			obj.attempts = _cData.attempt[counter];
			obj.style.width = (maxlen * offset / 2) + "px";
			obj.rightAns = quesArr[currentQ][j].ans[k][0];
			//if(storedData[currentQ] && storedData[currentQ].ans[counter])
			//console.log("cDATA:  ",  _cData.ans, counter);

			if (_cData.ans[counter] && _cData.ans[counter].length) {
				obj.attempts = _cData.attempt[counter];
				obj.value = _cData.ans[counter];
				obj.style.color = colors.right;
				obj.isDone = true;
				obj.disabled = true;
				filled[counter] = obj.value;
				filledCount++;
			} else {
				//console.log("fffffffffffffffffffffff");			
				obj.addEventListener("input", onInput);

				filled[counter] = undefined;
			}
			//console.log("**********:  ",quesArr[i][j].ans[k][0]);
			counter++;
		}

	}

	resetInputWidth(counter, MAX);
	MaxInput = counter;
	//console.log("TOTAL: ", MaxInput);
}

function onKeyPress(e) {


	if (e.keyCode == 13 && e.target.value.length) {
		console.log("JEY.........", e.target.value.length);
		onSubmit();
	}
}


function resetInputWidth(counter, _max) {
	var str = "";
	var id;
	for (var ii = 0; ii < _max; ii++) {
		//str.concat("A");
		str += "W";

	}
	str += "W";
	for (var i = 0; i < counter; i++) {
		id = "#in" + i;
		getElement(id).setAttribute("maxlength", (_max + 1).toString());
		getElement(id).style.width = 150 + "px"; //changes
		//console.log(getElement(id));
	}
}

function getMaxLen(arr) {
	var maxx = arr[0].length;

	for (var i = 0; i < arr.length; i++) {
		maxx = Math.max(maxx, arr[i].length);
	}
	//console.log("RETURN MAX:  ", maxx);
	return maxx;

}

function onInput(e) {
	var obj = e.currentTarget;
	var maxChar = parseInt(obj.getAttribute("maxlength"))

	if (obj.getAttribute("data-type") == "text") {
		var lastchar = obj.value.charAt(obj.value.length - 1);
		if (!isNaN(lastchar)) {
			obj.value = obj.value.substring(0, obj.value.length - 1);
		}
	}

	if (obj.value.length >= maxChar) {
		obj.value = obj.value.substring(0, maxChar);
	}

	refreshSubmit(obj.id.replace("in", ""));

}




function refreshSubmit(idd) {
	/*
	var count=0;
	var idx;
	var val = getElement("#in"+idd).value;
	idd = parseInt(idd);
	console.log(getElement("#in"+idd));
	(val.length)?(filled[idd] = idd):filled[idd] = undefined;	
	idx = filled.indexOf(undefined);	
	(!++idx)?enableSubmitBTN(idd) :disableSubmitBTN(idd);
	*/
	for (var i = 0; i < MaxInput; i++) {
		if (!getElement("#in" + i).isDone && getElement("#in" + i).value.trim().length > 0) {
			enableSubmitBTN();
			getElement("#in" + i).addEventListener("keydown", onKeyPress);
			break;
		} else {
			disableSubmitBTN();
			getElement("#in" + i).removeEventListener("keydown", onKeyPress);
		}
	}
	//console.log("---------", JSON.stringify(cData),cData);
	//console.log("*********: ",filled);
	//count = filled.getFilledCount();	
	//(count >= inputCount)?enableSubmitBTN() :disableSubmitBTN();

}

function onSubmit() {
	var userIn;
	var tempR = 0;
	var tempArr = [];
	var idd = "";
	//var cData={};
	var myArr = [];
	var myAtt = 0;
	var count = 0;
	var cAttempt = [];
	var cr = 0;
	qAttempts = 1;
	wCount = [];

	disableSolution();
	disableSubmitBTN();
	disableObj(getElement("#prev"));
	disableObj(getElement("#next"));
	//disableAll();
	/*try{
		tempArr = storedData[currentQ].ans;
		cData = storedData[currentQ];
	}catch(err){
		tempArr=[];
	}*/

	for (var j = 0; j < quesArr[currentQ].length; j++) {
		for (var k = 0; k < quesArr[currentQ][j].ans.length; k++) {
			var atp = 0;
			AnsArr = quesArr[currentQ][j].ans[k];
			userIn = getElement("#in" + count).value;
			userIn = userIn.trim();
			getElement("#in" + count).value = userIn;
			//userIn = removeAllSpaces(userIn);
			//console.log("check:  ",quesArr[currentQ][j].ans[k],"========",j,k);			
			getElement("#in" + count).disabled = true;
			if (getElement("#in" + count).isDone) {
				cr++;
			}
			//getElement("#in"+count).style.backgroundColor = "#FFFFFF";			
			if (getElement("#in" + count).value.length && !getElement("#in" + count).isDone) {
				//console.log(getElement("#in"+count).attempts);
				atp = parseInt(getElement("#in" + count).attempts) + 1;
				getElement("#in" + count).attempts = atp;
				qAttempts = Math.max(atp, qAttempts);
				cAttempt[count] = qAttempts;
				if (textInArray(userIn, AnsArr, CASE_SENS)) {
					getElement("#in" + count).style.color = colors.right;
					getElement("#in" + count).isDone = true;
					getElement("#in" + count).attempts = ATTEMPTS_ALLOWED;
					tempR++;
					finalScore += tempR;
					console.log(tempR);
					scoreDisp.innerHTML = finalScore + "/" + quesArr.length;
					let status = SCO.get("cmi.core.lesson_status");
					if (status !== "completed") {
						SCO.set("cmi.core.score.raw", finalScore);
						SCO.save()
					}
					myArr[count] = userIn;
					cData.ans[count] = userIn;
					cData.attempt[count] = ATTEMPTS_ALLOWED;
					cr++;
					//console.log("TTTTTTTTT:  ",cData);
				} else {
					getElement("#in" + count).style.color = colors.wrong;
					myArr[count] = null;
					wCount.push(count);
					filled[count] = undefined;
					cData.attempt[count] = atp;
					//console.log("*********:  ", getElement("#in"+count).attempts, qAttempts);
				}
				//console.log("FOR:  ", userIn, attempts, cAttempt);
			}

			//console.log(getElement("#in"+count).getAttribute("attempts"),"*********", getElement("#in"+count));
			count++;
		}
	}

	rCount = tempR;
	console.log("HERE RIGHT:  ", cr);

	if (cr >= inputCount) {
		cData.allDone = true;
	}
	if (wCount.length) {
		cData.allDone = false;
		if (qAttempts < ATTEMPTS_ALLOWED && tempR) {
			//console.log("111111111");
			if (tempR <= (inputCount - wCount.length)) {
				//console.log("2222222222");		
				playWrongFeedback(tempR, postWrong);
			} else {
				//console.log("333333333333");
				playRemainingWrongFeedback(myArr.length - tempR, postWrong);
			}
		} else {
			//console.log("4444444444444");
			playFeedback("wrong", postWrong);
		}
		//console.log("55555555555555");
		feedbackAnim.gotoAndPlay("wrong");
		//setTimeout(postSubmit, drawIncorrectQuestionDelay);
		//cData.attempt = attempts;		
	} else {
		//console.log("6666666666666");
		feedbackAnim.gotoAndPlay("right");
		//setTimeout(postSubmit, drawNextQuestionDelay);
		//cData.allDone = true;
		playFeedback("right", postRight);
	}
	//console.log("FILED:  " , Count(myArr),rCount);


	if (getFilledCount(myArr) == myArr.length) {
		//console.log("ALL DONE===========: ", rCount,myArr);
		cData.allDone = true;
	}
	//cData.ans = tempArr;
	//xconsole.log("STORING: ",JSON.stringify(cData), cData);
	//cData.ans = myArr;
	//cData.attempt = cAttempt;
	console.log("AFTER SUBMIT SAVE:  ", cData["attempt"]);
	SAVE_ANS && saveAnswers(cData);

	//console.log("SAVED:  ", storedData);
}


function textInArray(txt, arr, _case) {
	txt = txt.trim();
	if (!_case) {
		for (var i = 0; i < arr.length; i++) {

			!_case && (arr[i] = arr[i].toLowerCase());

		}
		txt = txt.toLowerCase();
	}
	console.log("COMP: ", txt, arr);
	return ((arr.indexOf(txt) + 1));
}


function postRight()
{
	console.log("POST RIGHT=======", cData);
	if(getTotalCorrect() < inputCount)
	{
		//console.log("STAY...........");
		resetQuestion();
		return;
	}
	
	if(allDone < quesArr.length)
	{		
		//console.log("222222222222222case2 ",currentQ, "-------:,", quesArr.length );
		gotoNextQ();
			
	}else
	{
		//console.log("-----------ELSE.....");
		console.log("varun postright");
		disableSolution();			
		finishActivity();
	}
	
}

function postWrong() {
	console.log("-=-=-=-=-");
	feedbackAnim.gotoAndStop("ideal");
	console.log("POST WRONG ========", cData['attempt'], qAttempts);

	var play = false;

	if (qAttempts >= ATTEMPTS_ALLOWED) {

		showCorrectAns();

	} else {
		resetQuestion();
	}
	//console.log("Post wrong:  ",attempts, JSON.stringify(cData), cData);
}

function checkNextPrev() {
	(currentQ) ? enableObj(getElement("#prev")) : disableObj(getElement("#prev"));
	(currentQ < quesArr.length - 1) ? enableObj(getElement("#next")) : disableObj(getElement("#next"));
}


function getTotalCorrect() {
	var obj;
	var count = 0;
	var val;
	var ans;
	for (var i = 0; i < inputCount; i++) {
		obj = getElement("#in" + i);
		if (obj.isDone)
			count++;
	}
	return count;
}


function resetQuestion() {
	console.log("-----------")
	feedbackAnim.gotoAndStop("ideal");

	for (var i = 0; i < inputCount; i++) {
		//console.log("Resetting CHECK:  ",getElement("#in"+i).value);
		if (!getElement("#in" + i).isDone) {
			//console.log("Resetting:  ",getElement("#in"+i).value);
			getElement("#in" + i).value = "";
			getElement("#in" + i).className = "inClass";
			getElement("#in" + i).style.color = colors.input;
			getElement("#in" + i).disabled = false;
		}

	}
	checkNextPrev();
	enableSolution(currentQ);
	//disableObj(getElement("#submitBtn"));
}


function disableAll() {
	for (var i = 0; i < inputCount; i++) {
		getElement("#in" + i).style.pointerEvents = "none";
	}

}

function enableAll() {
	for (var i = 0; i < inputCount; i++) {
		if (getElement("#in" + i).isDone) {
			continue;
		}
		getElement("#in" + i).style.pointerEvents = "auto";
	}
}




function onSolution(e) {
	//disableSolution();
	//disableSubmitBTN();
	var obj;
	for (var i = 0; i < inputCount; i++) {
		obj = getElement("#in" + i);
		obj.attempts = ATTEMPTS_ALLOWED;
	}
	disableAll();
	showCorrectAns();
}

function showCorrectAns() {
	var id;
	var obj;
	var tArr = [];
	var tObj = {};
	var rCount = 0;
	var wCount = 0;
	var count = 0;
	disableSolution();
	disableSubmitBTN();
	disableObj(getElement("#prev"));
	disableObj(getElement("#next"));
	//tArr = cData.ans;
	//console.log("TTT:  ",cData.ans, qAttempts);

	//if(qAttempts >= ATTEMPTS_ALLOWED)
	{
		for (var i = 0; i < inputCount; i++) {
			obj = getElement("#in" + i);
			if (obj.attempts == ATTEMPTS_ALLOWED) {
				obj.style.color = colors.right;
				obj.disabled = true;
				obj.isDone = true;
				obj.value = obj.rightAns;
				cData.attempt[i] = ATTEMPTS_ALLOWED;
				cData.ans[i] = obj.rightAns;
				count++;
				rCount++;
			} else {
				//cData.attempt[i] = null;
				cData.ans[i] = null;
				wCount++;
				obj.disabled = false;
				obj.value = "";
			}
			//tArr.push(ATTEMPTS_ALLOWED);

		}

		if (count == inputCount) {
			cData.allDone = true;
			//console.log("FINAL: ", cData);
			SAVE_ANS && saveAnswers(cData);
			playFeedback("correct", gotoNextQ);

		} else {
			playFeedback("correct", resetQuestion);
		}
	}


	/*
	if(wCount.length){
		for(var ii=0;ii<wCount.length;ii++){
			//console.log("RRRRR:  ",ii,wCount[ii]); 
			obj = getElement("#in"+wCount[ii]);
			rCount++;
			obj.style.color = colors.right;			
			cData.ans[wCount[ii]] = obj.rightAns;
			//console.log(cData.ans);
		}
		
		if(storedData[currentQ])
		{	
			
			if(!obj.isDone){
				obj.value = obj.rightAns;
				obj.disabled = true;							
			}
		}else
		{
			//console.log("else...........",obj.rightAns,obj);
			obj.value = obj.rightAns;
			obj.isDone = true;			
		}			
	}else{
			
		//playFeedback("correct",postShowRight,rCount);
		}
	*/
	console.log("SHOW CORRECT AND SAVE:  ", cData['attempt']);
	SAVE_ANS && saveAnswers(cData);
}

function postShowRight() {
	checkNextPrev();
	enableSolution();
}

function saveAnswers(obj) {
	console.log("SAVING: ", cData["attempt"]);
	storedData[currentQ] = obj;
	//console.log("STORAGE:  ",storedData[currentQ]);

	let status = SCO.get("cmi.core.lesson_status");
	if (status !== "completed") {
		SCO.set("cmi.suspend_data", JSON.stringify(storedData) + "*" +qAttempts+"*"+allDone);
		SCO.save();
	}

	if (status !== "completed") {
	let tempInc=0
	for (var i = 0; i < storedData.length; i++) {
        if(storedData[i].allDone== true){
           tempInc++; 
        }

		
        console.log(tempInc);

        if(tempInc === quesArr.length){
			console.log("varunnnnnnnnn30");
            SCO.set("cmi.core.lesson_status", "completed");
			SCO.save(); 
			disableSolution();	
			console.log("varun saveanswer");		
			//finishActivity();          
        }
	}

}
}


function saveData() {
	let status = SCO.get("cmi.core.lesson_status");
	if (status !== "completed") {
		let dataToSave = JSON.stringify(storedData);
		SCO.set("cmi.suspend_data", JSON.stringify(storedData) + "*" +qAttempts+"*"+allDone);
		SCO.save();
	}
}



function gotoNextQ()
{
	//console.log("goint next:  ", currentQ, quesArr.length);
	allDone++;
	if(allDone == quesArr.length)
	{
		console.log("varun gotonext");
		disableSolution();			
		finishActivity();
	}
	
	if(currentQ>=quesArr.length-1){
		//console.log("TTTTTTTTTT");
		setTimeout(enableObj,drawNextQuestionDelay,getElement("#prev"));		
	}else{
		currentQ++;
		setTimeout(arrangeOptions,drawNextQuestionDelay);
	}

	saveData()
}


function cleanup() {
	while (optDiv.hasChildNodes()) {
		//console.log("=================removing:  ",  optDiv.lastChild);
		optDiv.removeChild(optDiv.lastChild);
	}

}





