/* 
/  @author Nityanand Ojha
*/

var grade = 3;
var activityReset = 0
var fntSize = [40, 35, 30];
var rubricfntSize = fntSize[grade - 1];
var quesfntSize = (fntSize[grade - 1]) - 5;
var optionFntSize = (fntSize[grade - 1]) - 5;
var fontFace = "Rubric, sans-serif";
var fontFace1 = "Ans, sans-serif";

var rArr = ["Amazing", "Brilliant", "Excellent", "Good", "GoodJob", "Superb", "Welldone", "Wonderful"];
var cArr = ["Oops"];
var wArr = [];
var nArr = ["ThinkAgain", "LetsTryAgain", "LetsGiveAnotherShot", "TryOnceAgain"];

var colorObj = { initial: "#000", select: "rgb(89, 231, 231)" };
var storageArr = [];
var tempAttempt = 0;
var _main;
var _rubricTxt;
var _quesTxt;
var srialNo;
var option;
var audio;
var animDiv;
var submitBtn;
var answerBtn;
var qNo = 0;
var optionBackground;
var allDone = [];
var numDropzone = 0;
var cOption = null;
var scoreDisp;
var finalScore = 0;
var SCO;
var optionArrLength

var introDelay = 1000;
var introVid;
//////// G for grammer, V for vocabulary..........
//var introType = "v";

startIntro();

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

function startIntro() {
	_main = document.getElementById(MAINTAG);
	addingCheckSolBtns();

	introVid = document.createElement("video");
	titleText = document.createElement("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);

	//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);

	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 = "300px";
			titleText.style.color = "#000";
			sourceWebm.src = "../__intro/Title_Vocab.webm"
			sourceMp4.src = "../__intro/Title_Vocab.mp4"
			introVid.load();
			introVid.play();
			setTimeout(showTitle, 3000);
			break;
		default:
			//feedbackVid.init();
			feedbackAnim();
			document.getElementById("main").style.backgroundImage = "url('../__images/image/"+spriteOBJ.background+"')";	
			introVid.removeEventListener("ended", onEnd);
			$(titleText).animate({ opacity: 0 }, 1);
			$(introVid).animate({ opacity: 0 }, 1, dragAndDrop);
			break;
	}

}

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

function onEnd() {
	//feedbackVid.init();
	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, dragAndDrop);
}

function feedbackAnim() {
	optionArrLength = data.optionArr[0].length;
	console.log(optionArrLength, "99999999999999");

	_main = document.getElementById("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 dragAndDrop() {
	document.body.removeChild(titleText);
	titleText = null;
	document.body.removeChild(introVid);
	introVid = null;

	for (var i = 0; i < data.optionArr.length; i++) {
		var tmpAttempt = [];
		for (var j = 0; j < data.optionArr[i].length; j++) {
			tmpAttempt.push(0);
		}
		storageArr.push({ attempt: tmpAttempt, drpZoneAttempt: [], quesDone: "false", ans: [], drp: [] });
	}


	console.log(storageArr, " ******");

	submitBtn.style.pointerEvents = "none";
	submitBtn.style.opacity = 0.5;
	submitBtn.addEventListener("click", onSubmitClick);

	// answerBtn.addEventListener("click", onSolutionClick);


	_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)
	_main = document.getElementById("main");

	optDiv = document.createElement("div");
	optDiv.setAttribute("id", "optDv");
	_main.appendChild(optDiv);
	optDiv.style.visibility = "hidden";
	optDiv.style.left = outerSpace + "px";
	optDiv.style.width = MAX_WIDTH + "px";

	_rubricTxt = document.createElement("div");
	document.body.appendChild(_rubricTxt);
	_rubricTxt.style.position = "absolute";

	_rubricTxt.setAttribute("id", "rubricTxt")
	_rubricTxt.style.maxWidth = "calc(100% - 60px)";
	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.innerHTML = data.rubric;
	_rubricTxt.style.background = "#fff";
	_rubricTxt.style.padding = 10 + "px";
	_rubricTxt.style.borderTopRightRadius = 10 + "px";
	_rubricTxt.style.borderBottomRightRadius = 10 + "px";
	_rubricTxt.style.left = 0 + "px";
	_rubricTxt.style.top = 15 + "px";
	_rubricTxt.style.color = "#3d8eb9";
	_rubricTxt.style.fontSize = rubricfntSize + "px";
	_rubricTxt.style.fontFamily = fontFace;

	_rubricTxt.style.width = Math.min(_rubricTxt.offsetWidth + 30, 1100) + "px";

	/*addingNextPre();
	addQuestion(0);*/
	//soundComplete();

	soundComplete();
}

var restbtnAct = document.getElementById("Reset");


function resetActivity(e) {
	activityReset = 1
	finalScore = 0;
	scoreDisp.innerHTML = finalScore + "/" + optionArrLength;
	e.target.classList.add("inactive");
	resetDragables()
	// addQuestion(0);
	removePreviousOnpre();
	addQuestion(qNo);
	// resetWrongDragables()
	let noQuestion = data.quesArr[0].length;
	allDone = [];

	for(var qi=0; qi<noQuestion; qi++){
        allDone[qi] = "n"
    }

	storageArr = [];
	for (var i = 0; i < data.optionArr.length; i++) {
		var tmpAttempt = [];
		for (var j = 0; j < data.optionArr[i].length; j++) {
			tmpAttempt.push(0);
		}
		storageArr.push({ attempt: tmpAttempt, drpZoneAttempt: [], quesDone: "false", ans: [], drp: [] });
	}
	addingNextPre();
	//addQuestion(0);
	restbtnAct.style.pointerEvents = "none";
	restbtnAct.style.opacity = 0.5;
}

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", storageArr.length)
	}
	console.log(status);
	if (status !== "completed") {

		console.log(status, "raj1");
		finalScore = SCO.get("cmi.core.score.raw") || 0;
		finalScore = parseInt(finalScore);
		scoreDisp.innerHTML = finalScore + "/" + optionArrLength;
		console.log("FINAL : ", finalScore);
		// if (storageArr.length == finalScore) {
		// 	SCO.set("cmi.core.lesson_status ", "passed");
		// }
	}
	else {
		console.log(status, "raj2");

		console.log("check");
		finalScore = SCO.get("cmi.core.score.raw") || 0;
		finalScore = parseInt(finalScore);
		scoreDisp.innerHTML = finalScore + "/" + optionArrLength;
		console.log(restbtnAct);
		restbtnAct.style.visibility = "visible";
		restbtnAct.addEventListener("click", resetActivity);

	}

	console.log(SCO.get("cmi.suspend_data"));

	let lmsData = SCO.get("cmi.suspend_data");
	console.log("LMS DATA: ", lmsData);
	console.log(lmsData.length);

	if (lmsData.length) {
		storageArr = JSON.parse(lmsData) || storageArr;
		console.log(storageArr);
		// handlingDoneQues()

	}
	saveData();

	console.log("DATA: ", lmsData);
	console.log("storageArrrr ------=======", data.optionArr.length);
	// console.log("Status: ", Status);


}


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 soundComplete() {
	//audio.removeEventListener("ended", soundComplete);
	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 = "0/4";
	scoreDisp.innerHTML = finalScore + "/" + optionArrLength;
	scorePanel.appendChild(scoreDisp);
	scoreDisp.setAttribute("id", "scoreDisp");
	try {
		addScorm();
	} catch (err) {
	}

	addingNextPre();
	addQuestion(0);
	handlingDoneQues();
}

function addingNextPre() {
	nextpreNav = document.createElement("div");
	nextpreNav.className = "nextpreNav";
	nextpreNav.setAttribute("id", "nextpreNav");
	nextpreNav.style.top = 645 + "px";
	nextpreNav.style.left = 165 + "px";
	_main.appendChild(nextpreNav);

	nextBtn = document.createElement("div");
	nextBtn.setAttribute("id", "nextBtn");

	preBtn = document.createElement("div");
	preBtn.setAttribute("id", "preBtn");
	disableObj(preBtn);
	nextpreNav.appendChild(nextBtn);
	nextpreNav.appendChild(preBtn);

	if (data.optionArr.length > 1) {
		nextpreNav.addEventListener("click", onNavigationClick);
	} else {
		nextBtn.style.visibility = "hidden";
		preBtn.style.visibility = "hidden";
		nextpreNav.addEventListener("click", onNavigationClick);
	}
}

function onNavigationClick(e) {

	if (e.target.id == "preBtn") {
		submitBtn.style.pointerEvents = "none";
		submitBtn.style.opacity = 0.5;
		removePreviousOnpre();
		addQuestion(--qNo);
		enableObj(getElement("nextBtn"));
		handlingDoneQues();

		if (!qNo) {
			disableObj(e.target);
			return;
		}


	} else if (e.target.id == "nextBtn") {
		submitBtn.style.pointerEvents = "none";
		submitBtn.style.opacity = 0.5;
		qNo++
		removePrevious();
		addQuestion(qNo);
		enableObj(getElement("preBtn"));
		handlingDoneQues();

		if (qNo == data.optionArr.length - 1) {
			disableObj(e.target);
			return;
		}

	}

}

function disableObj(obj) {
	obj.style.pointerEvents = "none";
	obj.style.opacity = 0.5;
}

function enableObj(obj) {
	obj.style.pointerEvents = "auto";
	obj.style.opacity = 1;
}

function getElement(str) {
	return (document.getElementById(str));
}

function addQuestion(indx) {
	//feedbackVid.doReset();
	//feedbackAnim.gotoAndStop("ideal");
	var opW = 0;
	submitBtn.style.visibility = "visible";
	answerBtn.style.visibility = "visible";

	optDiv.style.visibility = "visible";
	arrangeSentence();

	for (var i = 0; i < data.optionArr[indx].length; i++) {
		option = document.createElement("div");
		option.style.position = "absolute";
		_main.appendChild(option);
		option.innerHTML = data.optionArr[indx][i];
		option.style.zIndex = "1";
		option.style.fontFamily = fontFace1;
		option.style.fontSize = optionFntSize + "px";
		option.classList.add("options");
		option.id = "op" + i;
		option.owner = null;
		option.isDone = false;
		option.wCount = 0;
		option.style.cursor = "pointer";
		option.style.borderRadius = "5px";
		//option.style.border = '1px solid red'

		option.addEventListener("click", onOptionsClicked);

		opW += option.offsetWidth + spacingBetweenOption;
	}

	if (optionHorizontalArrange) {
		hArrangingOptions(indx);
	} else {
		vArrangingOptions(indx);
	}

	if (optionBackground) {
		_main.removeChild(optionBackground);
	}

	optionBackground = document.createElement("div");
	optionBackground.style.position = "absolute";
	_main.appendChild(optionBackground);
	optionBackground.style.zIndex = "0";
	optionBackground.style.border = "3px solid #F29B34";
	optionBackground.style.height = option.offsetHeight + 25 + "px";
	optionBackground.style.width = (opW - spacingBetweenOption) + 40 + "px";
	optionBackground.style.top = parseInt(option.style.top) - 16 + "px";
	optionBackground.style.left = parseInt(document.getElementById("op" + 0).style.left) - 20 + "px";
	optionBackground.style.borderRadius = 5 + "px";
	optionBackground.style.backgroundColor = "#ffffff";
}
function addQuestionReset(indx) {
	//feedbackVid.doReset();
	//feedbackAnim.gotoAndStop("ideal");
	var opW = 0;
	submitBtn.style.visibility = "visible";
	answerBtn.style.visibility = "visible";

	optDiv.style.visibility = "visible";
	arrangeSentence();

	// for (var i = 0; i < data.optionArr[indx].length; i++) {
	// 	option = document.createElement("div");
	// 	option.style.position = "absolute";
	// 	_main.appendChild(option);
	// 	option.innerHTML = data.optionArr[indx][i];
	// 	option.style.zIndex = "1";
	// 	option.style.fontFamily = fontFace1;
	// 	option.style.fontSize = optionFntSize + "px";
	// 	option.classList.add("options");
	// 	option.id = "op" + i;
	// 	option.owner = null;
	// 	option.isDone = false;
	// 	option.wCount = 0;
	// 	option.style.cursor = "pointer";
	// 	option.style.borderRadius = "5px";
	// 	//option.style.border = '1px solid red'

	// 	option.addEventListener("click", onOptionsClicked);

	// 	opW += option.offsetWidth + spacingBetweenOption;
	// }

	if (optionHorizontalArrange) {
		hArrangingOptions(indx);
	} else {
		vArrangingOptions(indx);
	}

	/* if (optionBackground) {
		_main.removeChild(optionBackground);
	}

	optionBackground = document.createElement("div");
	optionBackground.style.position = "absolute";
	_main.appendChild(optionBackground);
	optionBackground.style.zIndex = "0";
	optionBackground.style.border = "3px solid #F29B34";
	optionBackground.style.height = option.offsetHeight + 25 + "px";
	optionBackground.style.width = (opW - spacingBetweenOption) + 40 + "px";
	optionBackground.style.top = parseInt(option.style.top) - 16 + "px";
	optionBackground.style.left = parseInt(document.getElementById("op" + 0).style.left) - 20 + "px";
	optionBackground.style.borderRadius = 5 + "px";
	optionBackground.style.backgroundColor = "#ffffff"; */
}


function onOptionsClicked(e) {
	cOption = e.target;
	for (var k = 0; k < data.optionArr[qNo].length; k++) {
		var getOp = document.getElementById("op" + k);
		if (getOp.owner) {
			getOp.style.pointerEvents = "none";
		}
		getOp.style.backgroundColor = 'transparent';
	}

	cOption.style.backgroundColor = colorObj.select;

	/* var drpZone = document.getElementsByClassName("dropzone");
	for(var i=0; i<drpZone.length; i++){
		drpZone[i].classList.add("drop-active");
	} */

	enableDropZones();
}

function arrangeSentence() {
	var drpZoneCnt = -1;
	var opt;
	var prevW = 0;
	var offset;
	var ln = 0;
	allDone = [];

	cleanup();

	for (var n = 0; n < data.quesArr[qNo].length; n++) {
		str = getBroken(data.quesArr[qNo][n].ques);
		prevW = 0;
		ln++;
		drpnum = 0;
		for (var i = 0; i < str.length; i++) {
			opt = document.createElement("div");
			opt.className = "cell";
			opt.style.fontSize = quesfntSize + "px";
			optDiv.appendChild(opt);
			opt.innerHTML = str[i];
			opt.style.fontFamily = fontFace1;
			if (str[i].charAt(0) == "_") {
				drpZoneCnt++;
				numDropzone = drpZoneCnt;
				var tempW = opt.offsetWidth;
				var tempH = opt.offsetHeight;

				opt.style.width = tempW + "px";
				opt.style.height = 40 + "px";
				opt.setAttribute("id", ("dropZone" + drpZoneCnt));
				opt.classList.add("dropzone");
				opt.addEventListener("click", dropzoneClicked);
				opt.guest = null;
				opt.isDone = false;
				opt.value = n + "_" + drpnum++;
				opt.wCount = 0;
				allDone.push("n");
				opt.style.borderBottom = '2px solid #000';
				opt.innerHTML = "";
			}

			offset = prevW + opt.offsetWidth;
			ln = ln + Math.floor(offset / MAX_WIDTH);

			opt.style.top = ((ln - 1) * LINE_HEIGHT) + optPadd + (n * (indentation / 2)) + "px";

			prevW = (offset > MAX_WIDTH) ? indentation : prevW;
			opt.style.left = (prevW) + "px";

			prevW = parseInt(opt.style.left) + opt.offsetWidth + 5;

			/*prevW = (offset>MAX_WIDTH)?indentation:prevW;
			if(str[i].charAt(0) == "."){
				opt.style.left = (prevW)-5+"px";
			}else{
				opt.style.left = (prevW)+"px";
			}*/
		}

	}

	optDiv.style.height = (((ln + 1) * LINE_HEIGHT))+60 + "px";

	disableDropZones();
	//arrangeTargets(qNo)
}

/* 
function arrangeTargets(idx) {
	var str;
	if (optPos[idx] != undefined) {
		var quesImg = document.createElement("img");
		//quesImg.src = "Assets/images/Image_"+(idx+1)+".jpg";	
		//quesImg.style.width = "670px"		
		//quesImg.style.height = "390px"	
		//optDiv.appendChild(quesImg);		
		optDiv.style.height = quesImg.offsetHeight + "px";
		optDiv.style.width = quesImg.offsetWidth + "px";
		for (var i = 0; i < optPos[idx].length; i++) {
			//console.log("TARRRRRRRRR:  ", getElement("tar"+i));
			getElement("dropZone" + i).style.left = optPos[idx][i].x + "px";
			getElement("dropZone" + i).style.top = optPos[idx][i].y + "px";
		}
	}
} */

function getBroken(str) {
	return str.split(" ");
}

function cleanup() {
	while (optDiv.hasChildNodes()) {
		optDiv.removeChild(optDiv.lastChild);
	}

}

function dropzoneClicked(e) {
	if (cOption) {
		console.log(e.target.id, " _______________dropzoneClicked");

		//e.target.style.cursor = "auto";
		cOption.style.backgroundColor = 'transparent';

		setPositionOfDragable(e.currentTarget, cOption);
		disableDropZones();
		enableDragables();
		cOption = null;
	}

}

function addNumbering(indx) {
	srialNo = document.createElement("div");
	srialNo.style.position = "absolute";
	srialNo.setAttribute("id", "SnoDiv");
	srialNo.innerHTML = (indx + 1);
	srialNo.style.fontSize = optionFntSize + "px";
	srialNo.style.fontFamily = fontFace1;
	srialNo.style.borderRadius = "50%";
	srialNo.style.width = (optionFntSize + 5) + "px";
	srialNo.style.border = "3px solid #F29B34";

	_main.appendChild(srialNo);
	srialNo.style.top = optDv.offsetTop + "px";
	srialNo.style.left = (optDv.offsetLeft) - (srialNo.offsetWidth + 10) + "px";
}

function hArrangingOptions(indx) {
	for (var i = 0; i < data.optionArr[indx].length; i++) {
		var cc = document.getElementById("op" + i)

		if (i == 0) {
			cc.style.left = optionLeft + "px";
		} else {
			var prevOp = document.getElementById("op" + (i - 1))
			cc.style.left = parseInt(prevOp.style.left, 10) + (prevOp.offsetWidth + spacingBetweenOption) + "px";
		}
		cc.style.top = optionBelow + "px";//parseInt(_quesTxt.style.top,10)+(_quesTxt.offsetHeight+optionBelow)+"px";

		cc.xx = cc.style.left;
		cc.yy = cc.style.top;
	}
}

function vArrangingOptions(indx) {
	for (var i = 0; i < data.optionArr[indx].length; i++) {
		var cc = document.getElementById("op" + i)

		if (i == 0) {
			cc.style.top = optionBelow + "px";//parseInt(_quesTxt.style.top,10)+(_quesTxt.offsetHeight+optionBelow)+"px";
		} else {
			var prevOp = document.getElementById("op" + (i - 1))
			cc.style.top = parseInt(prevOp.style.top, 10) + (prevOp.offsetHeight + spacingBetweenOption) + "px";
		}

		cc.style.left = optionLeft + "px";

		cc.xx = cc.style.left;
		cc.yy = cc.style.top;
	}
}

function onSubmitClick(e) {
	disableObj(nextBtn);
	disableObj(preBtn);
	disableBTN();
	disableDragables();

	if (cOption) {
		cOption.style.backgroundColor = 'transparent';
	}

	var chkAns = new checkAnswer(qNo);

	if (chkAns.done()) {
		storageArr[qNo].quesDone = "true";
		setTimeout(addNextQuestion, 4000);
	} else {
		// storageArr[qNo].quesDone = "true";
		setTimeout(function () {
			answerBtn.style.pointerEvents = "auto";
			answerBtn.style.opacity = 1;

			if (qNo < data.optionArr.length - 1) {
				enableObj(nextBtn);
			}

			if (qNo) {
				enableObj(preBtn);
			}

			solutionForWrongOne(qNo, chkAns.getDrpzone());
		}, 3000);
	}

	var wCount = chkAns.getWCount();
	var tempR = chkAns.getRCount();

	//var maxAttempt = getMaxOfArray(storageArr[qNo].attempt);
	var maxAttempt = getMaxOfArray(storageArr[qNo].drpZoneAttempt);
	//console.log(storageArr[qNo].attempt, " donennnnnnnnnnnnnnnnnn wCount: ", wCount);
	if (wCount) {
		if (maxAttempt == 0 && tempR) {
			if (tempR <= wCount) {
				playWrongFeedback(tempR);
			} else {
				playRemainingWrongFeedback((numDropzone + 1) - tempR);
			}
		} else {
			playFeedback("wrong");
		}
		//feedbackVid.playWrongFeedback(postSubmit);
		//feedbackAnim.gotoAndPlay("wrong");
	} else {
		playFeedback("right");
		//feedbackVid.playCorrectFeedback(postSubmit);
		//	feedbackAnim.gotoAndPlay("right");
	}

	saveData();

}

function getMaxOfArray(numArray) {
	return Math.max.apply(null, numArray);
}

function postSubmit() {

}

function checkAnswer(indx) {
	var _b = false;
	var cnt = 0;
	var wCnt = 0;
	var tempR = 0;
	var drpZone = [];
	// finalScore=0

	for (var n = 0; n < data.quesArr[indx].length; n++) {

		for (var i = 0; i < data.quesArr[indx][n].ans.length; i++) {
			var drpGuest = document.getElementById("dropZone" + cnt).guest;
			if (drpGuest) {
				if (drpGuest.isDone == false) {
					drpZone.push(drpGuest.owner);
					if (drpGuest.id == data.quesArr[indx][n].ans[i]) {
						allDone[cnt] = "c";
						drpGuest.isDone = true;
						drpGuest.owner.isDone = true;
						setColor(drpGuest, "#009900");

						startStoring(drpGuest.id, drpGuest.owner.id);
						tempR++;
						finalScore++;
						console.log(tempR);
						scoreDisp.innerHTML = finalScore + "/" + optionArrLength;
					} else {
						drpGuest.wCount++;
						drpGuest.owner.wCount++;
						var c1 = drpGuest.id.substr(2);
						storageArr[indx].attempt[c1] = drpGuest.wCount;
						var c2 = drpGuest.owner.id.substr(8);
						storageArr[indx].drpZoneAttempt[c2] = drpGuest.owner.wCount;
						setColor(drpGuest, "#ff0000");
						wCnt++;
					}
				}
			}
			cnt++;
		}
	}

	if (allDone.indexOf("n") <= -1) {
		_b = true;
	} else {
		_b = false;
	}

	this.done = function () {
		return _b;
	}

	this.getWCount = function () {
		return wCnt;
	}

	this.getRCount = function () {
		return tempR;
	}

	this.getDrpzone = function () {
		return drpZone;
	}
	let status = SCO.get("cmi.core.lesson_status");
	console.log(status, finalScore, "NNO");
	if (status !== "completed") {
		console.log(" 11111111 NNO");
		let rawScore = SCO.set("cmi.core.score.raw", finalScore);

	}
	saveData();

}

function addNextQuestion() {
	console.log("next quest");
	disableObj(nextBtn);
	enableObj(getElement("preBtn"));
	console.log("restbtnAct", qNo);
	if (qNo < data.optionArr.length - 1) {
		qNo++
		removePrevious();
		addQuestion(qNo);
		resetDragables();
		disableBTN();
		answerBtn.style.pointerEvents = "auto";
		answerBtn.style.opacity = 1;

		if (qNo < data.optionArr.length - 1) {
			enableObj(nextBtn);
		}

		if (qNo) {
			enableObj(preBtn);
		}

		enableDragables();
	}



	if(storageArr[0].quesDone="true")
	{
		let status = SCO.get("cmi.core.lesson_status");
		if (status !== "completed") {
		SCO.set("cmi.core.lesson_status", "completed");
		SCO.save();
		}
	}

	 makeAnimationSpace();
	handlingDoneQues();


}

function solutionForWrongOne(indx, drpArr) {
	//feedbackAnim.gotoAndStop("ideal");

	var lft;
	var top;
	var cnt = 0;
	var correctFeedback = false;

	for (var i = 0; i < drpArr.length; i++) {
		var cDragable = drpArr[i].guest;
		cDragable.wCount = drpArr[i].guest.wCount;
		var drpArea = drpArr[i];

		resetCurrentDragable(cDragable);

		var first = false;

		if (drpArr[i].wCount == attempt) {
			first = true;
			correctFeedback = true;
			answerForDrpZone(indx, drpArr[i]);
			var dd = drpArr[i].id.substr(8);
			allDone[dd] = "c";
		}

		/* if(cDragable.wCount >= attempt){
			if(!first){
				correctFeedback = true;
				var correctDrpArea = getDragablePos(indx, cDragable);
				
				lft = (correctDrpArea.offsetWidth/2-cDragable.offsetWidth/2);
				top = (correctDrpArea.offsetHeight/2-cDragable.offsetHeight/2);
				
				var cc = correctDrpArea.id.substr(8);
				allDone[cc] = "c";
				
				cDragable.isDone = true;
				correctDrpArea.isDone = true;
				correctDrpArea.appendChild(cDragable);
				cDragable.style.left = lft+"px";
				cDragable.style.top = top+"px";
				cDragable.removeAttribute("data-x");
				cDragable.removeAttribute("data-y");
				cDragable.style.transform = "none";
				setColor(cDragable, "#009900");
				cDragable.style.pointerEvents = "none";			
				startStoring(cDragable.id,correctDrpArea.id);
			}
		} */
	}

	if (correctFeedback) {
		disableBTN();
		disableObj(nextBtn);
		disableObj(preBtn);
		disableDragables();
		playFeedback("correct");
		correctFeedback = true;

		setTimeout(function () {
			if (qNo < data.optionArr.length - 1) {
				enableObj(nextBtn);
			}

			if (qNo) {
				enableObj(preBtn);
			}
			answerBtn.style.pointerEvents = "auto";
			answerBtn.style.opacity = 1;
			resetWrongDragables()
		}, 3500);
	}

	if (allDone.indexOf("n") <= -1) {
		storageArr[qNo].quesDone = "true";
		setTimeout(addNextQuestion, 3500);
	}

}

function answerForDrpZone(indx, drpArea) {
	console.log("dropArea answer *************");
	var r = drpArea.value.split("_")[0];
	var c = drpArea.value.split("_")[1];
	var cDragable = document.getElementById(data.quesArr[indx][r].ans[c]);

	var lft;
	var top;
	lft = (drpArea.offsetWidth / 2 - cDragable.offsetWidth / 2);
	top = (drpArea.offsetHeight / 2 - cDragable.offsetHeight / 2);

	cDragable.isDone = true;
	drpArea.isDone = true;

	cDragable.style.pointerEvents = "none";
	drpArea.appendChild(cDragable);
	cDragable.style.left = lft + "px";
	cDragable.style.top = top + "px";
	cDragable.removeAttribute("data-x");
	cDragable.removeAttribute("data-y");
	cDragable.style.transform = "none";
	setColor(cDragable, "#009900");

	startStoring(cDragable.id, drpArea.id);
}

function Fillsolution(indx) {
	if (cOption) {
		cOption.style.backgroundColor = 'transparent';
	}
	var lft;
	var top;
	disableBTN();
	playFeedback("correct");
	resetDragables();
	disableDragables();
	var cnt = 0;

	for (var n = 0; n < data.quesArr[indx].length; n++) {
		for (var i = 0; i < data.quesArr[indx][n].ans.length; i++) {
			var cDragable = document.getElementById(data.quesArr[indx][n].ans[i]);
			var drpArea = document.getElementById("dropZone" + cnt);

			lft = (drpArea.offsetWidth / 2 - cDragable.offsetWidth / 2);
			top = (drpArea.offsetHeight / 2 - cDragable.offsetHeight / 2);

			drpArea.appendChild(cDragable);
			cDragable.style.left = lft + "px";
			cDragable.style.top = top + "px";
			cDragable.removeAttribute("data-x");
			cDragable.removeAttribute("data-y");
			cDragable.style.transform = "none";
			setColor(cDragable, "#009900");

			startStoring(cDragable.id, drpArea.id);
			//storageArr[qNo].attempt = attempt;
			cnt++;
			console.log("NNNNNNNNNOOOOOO", cnt);
		}
	}

	storageArr[qNo].quesDone = "true";
	setTimeout(addNextQuestion, 3500);
}

function onSolutionClick() {
	disableObj(nextBtn);
	disableObj(preBtn);

	Fillsolution(qNo);
}

function startStoring(dragable, drpArea) {
	if (storageArr[qNo].ans.indexOf(dragable) <= -1) {
		storageArr[qNo].ans.push(dragable);
		storageArr[qNo].drp.push(drpArea);
	}
	console.log("storageArr", storageArr);

	saveData();
}

function saveData() {
	let status = SCO.get("cmi.core.lesson_status");
	if (status !== "completed") {
	
		SCO.set("cmi.suspend_data", JSON.stringify(storageArr));
		SCO.save();
	
	}

/* 	if(storageArr[0].quesDone===true){
		console.log(" varun   completed");
            SCO.set("cmi.core.lesson_status", "completed");
			SCO.save();  
			disableSolution();
	
	} */
}

function handlingDoneQues() {
	answerBtn.style.pointerEvents = "auto";
	answerBtn.style.opacity = 1;
	enableDragables();

	for (var k = 0; k < storageArr[qNo].attempt.length; k++) {
		var opts = document.getElementById("op" + k);
		opts.wCount = storageArr[qNo].attempt[k];
	}

	for (var l = 0; l < storageArr[qNo].drpZoneAttempt.length; l++) {
		var drpZones = document.getElementById("dropZone" + l);
		if (storageArr[qNo].drpZoneAttempt[l]) {
			drpZones.wCount = storageArr[qNo].drpZoneAttempt[l];
		}
	}

	if (storageArr[qNo].ans.length != 0) {
		console.log(storageArr, " _____handlingDoneQues");
		var lft;
		var top;
		resetDragables();

		for (var i = 0; i < storageArr[qNo].ans.length; i++) {
			var cDragable = document.getElementById(storageArr[qNo].ans[i]);
			var drpArea = document.getElementById(storageArr[qNo].drp[i]);

			lft = (drpArea.offsetWidth / 2 - cDragable.offsetWidth / 2);
			top = (drpArea.offsetHeight / 2 - cDragable.offsetHeight / 2);

			drpArea.appendChild(cDragable);
			cDragable.style.left = lft + "px";
			cDragable.style.top = top + "px";
			cDragable.removeAttribute("data-x");
			cDragable.removeAttribute("data-y");
			cDragable.style.transform = "none";
			setColor(cDragable, "#009900");

			cDragable.style.pointerEvents = "none";

			drpArea.guest = cDragable;
			drpArea.guest.isDone = true;
			drpArea.isDone = true;

			var cc = storageArr[qNo].drp[i].substr(8);
			allDone[cc] = "c";
		}

		if (storageArr[qNo].quesDone == "true") {
			disableDragables();
			answerBtn.style.pointerEvents = "none";
			answerBtn.style.opacity = 0.5;
		}

	}
}

function removePrevious() {
	for (var i = 0; i < data.optionArr[qNo - 1].length; i++) {
		var getPrevOption = document.getElementById("op" + i);
		getPrevOption.parentNode.removeChild(getPrevOption);
	}
}

function removePreviousOnpre() {
	for (var i = 0; i < data.optionArr[qNo].length; i++) {
		var getPrevOption = document.getElementById("op" + i);
		getPrevOption.parentNode.removeChild(getPrevOption);
	}
}

function resetCurrentDragable(obj) {
	dropZoneAct = null;
	var cDragable = obj;

	if (cDragable.isDone == false) {
		if (cDragable.owner) {
			cDragable.owner.guest = null;
		}

		cDragable.owner = null;

		cDragable.style.pointerEvents = "auto";
		_main.appendChild(cDragable);
		cDragable.style.left = cDragable.xx;
		cDragable.style.top = cDragable.yy;
		cDragable.removeAttribute("data-x");
		cDragable.removeAttribute("data-y");
		cDragable.style.transform = "none";
		setColor(cDragable, colorObj.initial)
	}

	for (var i = 0; i < data.optionArr[qNo].length; i++) {
		var allDragable = document.getElementById("op" + i);
		if (allDragable.isDone == false) {
			allDragable.style.pointerEvents = "auto";
		}
	}
}

function resetWrongDragables() {
	console.log("resetWrongDragables ........");
	for (var i = 0; i < data.optionArr[qNo].length; i++) {
		var cDragable = document.getElementById("op" + i);

		if (cDragable.owner) {
			cDragable.owner.guest = null;
		}

		if (cDragable.isDone == false) {
			if (cDragable.owner) {
				cDragable.owner.guest = null;
			}

			cDragable.owner = null;

			cDragable.style.pointerEvents = "auto";
			_main.appendChild(cDragable);
			cDragable.style.left = cDragable.xx;
			cDragable.style.top = cDragable.yy;
			cDragable.removeAttribute("data-x");
			cDragable.removeAttribute("data-y");
			cDragable.style.transform = "none";
			setColor(cDragable, colorObj.initial)

		}

	}
}

// function resetDragables() {
// 	var cnt = 0;

// 	for (var n = 0; n < data.quesArr[qNo].length; n++) {
// 		for (var i = 0; i < data.quesArr[qNo][n].ans.length; i++) {
// 			var cDropArea = document.getElementById("dropZone" + cnt);

// 			if (cDropArea.guest) {
// 				cDropArea.guest.style.pointerEvents = "auto";
// 				_main.appendChild(cDropArea.guest);
// 				cDropArea.guest.style.left = cDropArea.guest.xx;
// 				cDropArea.guest.style.top = cDropArea.guest.yy;
// 				cDropArea.guest.removeAttribute("data-x");
// 				cDropArea.guest.removeAttribute("data-y");
// 				cDropArea.guest.style.transform = "none";
// 				setColor(cDropArea.guest, colorObj.initial)

// 				cDropArea.guest = null;
// 			}
// 			cnt++;
// 		}
// 	}
// }
function resetDragables() {
	dropZoneAct = null;
	var cnt = 0;

	for (var i = 0; i < data.optionArr[qNo].length; i++) {
		var cDragable = document.getElementById("op" + i);

		if (cDragable.owner) {
			cDragable.owner.guest = null;
		}

		//if (cDragable.isDone == false) {
			if (cDragable.owner) {
				cDragable.owner.guest = null;
			}

			cDragable.owner = null;

			cDragable.style.pointerEvents = "auto";
			_main.appendChild(cDragable);
			cDragable.style.left = cDragable.xx;
			cDragable.style.top = cDragable.yy;
			cDragable.removeAttribute("data-x");
			cDragable.removeAttribute("data-y");
			cDragable.style.transform = "none";
			setColor(cDragable, colorObj.initial)

		//}

	}

	for (var n = 0; n < data.quesArr[qNo].length; n++) {
		for (var i = 0; i < data.quesArr[qNo][n].ans.length; i++) {
			var cDropArea = document.getElementById("dropZone" + cnt);

			if (cDropArea.guest) {
				cDropArea.guest.style.pointerEvents = "auto";
				_main.appendChild(cDropArea.guest);
				cDropArea.guest.style.position = "absolute";
				cDropArea.guest.style.left = cDropArea.guest.xx;
				cDropArea.guest.style.top = cDropArea.guest.yy;
				cDropArea.guest.removeAttribute("data-x");
				cDropArea.guest.removeAttribute("data-y");
				cDropArea.guest.style.transform = "none";
				setColor(cDropArea.guest, colorObj.initial)

				cDropArea.guest = null;
				cDropArea.isDone = false;
				cDropArea.addEventListener("click", dropzoneClicked);
			}
			cnt++;
		}
	}
	   for (let n = 0; n < data.optionArr[qNo].length; n++) {
		   let op = document.getElementById("op" + n);
		   op.style.pointerEvents = "auto";
		   op.isDone = false;
	   }
}
function checkAllDone() {
	var _d = true;

	for (var i = 0; i < data.quesArr.length; i++) {
		console.log("restbtnAct,all done loop no: ", i, storageArr[i].quesDone);
		if (storageArr[i].quesDone == "false") {
			_d = false;
			break;
		}
	}
	console.log("restbtnAct, _d", _d);
	return _d;
}

function makeAnimationSpace() {
	if (qNo) {
		enableObj(preBtn);
	}

    let noOfQuest = data.quesArr[0].length;
    console.log(noOfQuest, storageArr[0].ans.length);
    if(storageArr[0].ans.length !== noOfQuest){
        console.log("Not completed !!!");
        return;
    }

/* 	if (!checkAllDone()) {
		return;
	} */

	var actComDiv = document.createElement("div");
	document.body.appendChild(actComDiv);
	actComDiv.style.position = "absolute";
	actComDiv.style.left = 0 + "px";
	actComDiv.style.top = 0 + "px";
	actComDiv.style.width = 0 + "px";
	actComDiv.style.height = 720 + "px";
	actComDiv.style.zIndex = "200";
	actComDiv.style.backgroundColor = "#fff";

	animDiv = document.createElement("div");
	actComDiv.appendChild(animDiv);
	animDiv.style.position = "absolute";
	animDiv.style.width = 1280 + "px";
	animDiv.style.height = 233 + "px";
	animDiv.style.top = 243 + "px";
	animDiv.style.overflow = "hidden";
	animDiv.style.backgroundImage = "url(../__images/activityComplete.png)";
	animDiv.style.backgroundSize = "1280px 233px";
	animDiv.style.backgroundRepeat = "no-repeat";
	$(actComDiv).animate({ width: 1280 }, 500);
	setTimeout(completedDelay, 500);
	// let status = SCO.get("cmi.core.lesson_status");
	// if (status !== "completed") {
	// SCO.set("cmi.suspend_data", JSON.stringify(storageArr));
	// SCO.save();
	// }
	// SCO.set("cmi.core.lesson_status", "completed");
	// SCO.save();
/* 	setTimeout(function () {
		completedDelay();
		// Set SCORM status to "completed" here
		if (typeof SCO !== 'undefined') {
			SCO.set("cmi.core.lesson_status", "completed");
			SCO.save();
		}
	}, 500) */


	//console.log("restbtnAct, checkall done",checkAllDone());



	// setTimeout(completedDelay, 500);
	// // setTimeout(function () {
	// // 	completedDelay();
	// // 	// Set SCORM status to "completed" here

	// // }, 500);
	saveData()
}

function completedDelay() {
	var activityText = document.createElement("img");
	animDiv.appendChild(activityText);
	activityText.src = "../__images/activity.png";
	activityText.setAttribute("id", "activityText");
	var completedText = document.createElement("img");
	animDiv.appendChild(completedText);
	completedText.src = "../__images/completed.png";
	completedText.setAttribute("id", "completedText");
	playFeedback("completed");
}

function disableBTN() {
	submitBtn.style.pointerEvents = "none";
	submitBtn.style.opacity = 0.5;
	answerBtn.style.pointerEvents = "none";
	answerBtn.style.opacity = 0.5;
}

function enableBTN() {
	submitBtn.style.pointerEvents = "auto";
	submitBtn.style.opacity = 1;
	answerBtn.style.pointerEvents = "auto";
	answerBtn.style.opacity = 1;

	if (qNo < data.optionArr.length - 1) {
		enableObj(nextBtn);
	}

	if (qNo) {
		enableObj(preBtn);
	}
}

function setColor(mc, co) {
	mc.style.color = co;
}

function getChildByName(id) {
	return document.getElementById(id);
}

//==============================*********NNO*********==============================//

function setPositionOfDragable(dropzone, dragable) {
	var lft;
	var top;
	//dragable.style.zIndex = "10";

	if (dropzone.guest && dropzone.isDone == false) {
		_main.appendChild(dropzone.guest);
		dropzone.guest.style.left = dropzone.guest.xx;
		dropzone.guest.style.top = dropzone.guest.yy;

		console.log("guest: ++++++++++++++++", dropzone.guest.id);
		dropzone.guest.owner = null;
		dropzone.guest = null;
	}

	if (dropzone.isDone == false) {
		lft = parseInt(dropzone.style.left) + (dropzone.offsetWidth / 2) - (dragable.offsetWidth / 2);
		top = parseInt(dropzone.style.top) + (dropzone.offsetHeight / 2 - dragable.offsetHeight / 2);

		optDv.appendChild(dragable);
		dragable.style.left = lft + "px";
		dragable.style.top = top + "px";

		var preDrp = dragable.owner;
		dragable.owner = dropzone;
		dropzone.guest = dragable;

		if (preDrp) {
			preDrp.guest = null;
		}
		//console.log(dropzone.id," -22222222222222222222- ")
	}

	for (var i = 0; i < numDropzone + 1; i++) {
		if (document.getElementById("dropZone" + i).guest) {
			//if(document.getElementById("dropZone"+i).isDone == false){
			enableBTN();
			//}
			break;
		} else {
			disableBTN();
			answerBtn.style.pointerEvents = "auto";
			answerBtn.style.opacity = 1;

		}
	}
}


function disableDropZones() {
	for (var k = 0; k < numDropzone + 1; k++) {
		var getDrp = document.getElementById("dropZone" + k);
		getDrp.removeEventListener("click", dropzoneClicked);
		//getDrp.style.pointerEvents = "none";
	}
}

function enableDropZones() {
	for (var k = 0; k < numDropzone + 1; k++) {
		var getDrp = document.getElementById("dropZone" + k);
		getDrp.addEventListener("click", dropzoneClicked);
		//getDrp.style.pointerEvents = "auto";
	}
}


function disableDragables() {
	for (var k = 0; k < data.optionArr[qNo].length; k++) {
		var getOp = document.getElementById("op" + k)
		getOp.style.pointerEvents = "none";
	}
}

function enableDragables() {
	for (var k = 0; k < data.optionArr[qNo].length; k++) {
		var getOp = document.getElementById("op" + k);
		if (!getOp.isDone) {
			getOp.style.pointerEvents = "auto";
		}
	}
}

function playFeedback(val) {
	var ranNum;
	switch (val) {
		case "right":
			ranNum = parseInt(Math.random() * (rArr.length));
			console.log(ranNum)
			sourceOGG.src = "../__audio/" + rArr[ranNum] + ".ogg";
			sourceMP3.src = "../__audio/" + rArr[ranNum] + ".mp3";
			break;
		case "wrong":
			wArr = cArr;
			if (storageArr[qNo].attempt == 1) {
				wArr = wArr.concat(nArr);
			}
			if (storageArr[qNo].attempt == attempt) {
				for (var ii = 0; ii < nArr.length; ii++) {
					if (wArr.indexOf(nArr[ii]) > -1) {
						wArr.splice(wArr.indexOf(nArr[ii]), 1);
					}
				}
			}
			ranNum = parseInt(Math.random() * (wArr.length));
			sourceOGG.src = "../__audio/" + wArr[ranNum] + ".ogg";
			sourceMP3.src = "../__audio/" + wArr[ranNum] + ".mp3";
			break
		case "correct":
			sourceOGG.src = "../__audio/ThisIsTheCorrectAns.ogg";
			sourceMP3.src = "../__audio/ThisIsTheCorrectAns.mp3"
			break
		case "completed":
			sourceOGG.src = "../__audio/completed.ogg";
			sourceMP3.src = "../__audio/completed.mp3";
			break
	}

	audio.load();
	audio.play();
}

function playWrongFeedback(id) {
	sourceOGG.src = "../__audio/Right" + id + ".ogg";
	sourceMP3.src = "../__audio/Right" + id + ".mp3";
	audio.load();
	audio.play();
}


function playRemainingWrongFeedback(id) {
	sourceOGG.src = "../__audio/MoreGo" + id + ".ogg";
	sourceMP3.src = "../__audio/MoreGo" + id + ".mp3";
	audio.load();
	audio.play();
}

function addingCheckSolBtns() {
	checkSolution = document.createElement("div");
	checkSolution.className = "checkSolution";
	checkSolution.setAttribute("id", "checkSolution");
	_main.appendChild(checkSolution);

	answerBtn = document.createElement("div");
	//answerBtn.className = "answer";
	answerBtn.innerHTML = "SOLUTION";
	answerBtn.setAttribute("id", "answer");
	checkSolution.appendChild(answerBtn);

	submitBtn = document.createElement("div");
	//submitBtn.className = "submit";
	submitBtn.innerHTML = "CHECK";
	submitBtn.setAttribute("id", "submit");
	checkSolution.appendChild(submitBtn);

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


}