var count = 0, attempts = 0;
const introDelay = 1000;
var isMouseDown = false;
var mouseObject = null;
var fontFace = "Rubric, sans-serif", fontFace1 = "Ans, sans-serif";
var LAnsArr = [{ inClr: '#cccccc', bClr: '#000000' }];
var oneOrTwoAudio = ["Right1", "Right2", "Right3", "Right4"];
var cArr = ["Oops"];
var rArr = ["Amazing", "Brilliant", "Excellent", "Good", "GoodJob", "Superb", "Welldone", "Wonderful"];
var nArr = ["ThinkAgain", "GiveAnotherTry", "LetsGiveAnotherShot", "TryOnceAgain"];
var aSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var SVGline = function (l) { this.l = l; }
var wArray = [], wArr = [], QTopPosArr = [], QLeftPosArr = [], ATopPosArr = [], ALeftPosArr = [], Anstxt = [];
var NumOfBtns, audio, audioTime, Container, Svgdiv, submitBtn, answerBtn, _rubricTxt, Body, wBox, introVid, w1, w2, Wbox, Position_Of_WhiteBox_Top, _main;

var WhiteBoxWidth = (Question_Box_Width + Question_Box_Width + Position_Of_QuestionBox_Left + Position_Of_QuestionBox_Left + Horzontal_Space_Betn_Circl_And_Circl + Space_Betn_Txt_And_Circl + Space_Betn_Txt_And_Circl + 86);
var sourceMP3 = "";
var sourceOGG = "";
var animDiv;
var CombTxt, TmpTxt = [];
var storageArr = [];
var SCO;
// var status;
var scoreDisp;
var scorePanel;
var finalScore = 0;
var dataScore = 0
var ResetBtn;
var totalAttempts;
startIntro();

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

function startIntro() {




	Body = document.getElementsByTagName('body')[0];
	introVid = document.createElement('video');
	titleText = document.createElement('div');

	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.position = "absolute";
	titleText.style.fontFamily = "Rubric";
	titleText.style.opacity = 0;
	titleText.style.textAlign = "center";
	titleText.style.fontSize = "50px";

	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 = "240px";
			titleText.style.color = "#000";
			sourceWebm.src = "../__intro/Title_Vocab.webm"
			sourceMp4.src = "../__intro/Title_Vocab.mp4"
			introVid.load();
			introVid.play();
			setTimeout(showTitle, 5000);
			break;
		default:
			feedbackAnim();
			introVid.removeEventListener("ended", onEnd);
			$(titleText).animate({ opacity: 0 }, 1);
			$(introVid).animate({ opacity: 0 }, 1, Start);
			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, Start);

}

function feedbackAnim() {

	_main = getElement(MAINTAG);
	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 Start() {
	Body.removeChild(introVid);
	introVid = null;
	Body.removeChild(titleText);
	titleText = null;
	init_1();

	_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();
}


function init_1() {
	NumOfBtns = QesTxt.length;

	_main = getElement(MAINTAG);
	_rubricTxt = document.createElement("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.innerHTML = rubric;
	_rubricTxt.style.cursor = "default";
	_rubricTxt.style.fontSize = rubricfntSize + "px";
	_rubricTxt.style.fontFamily = fontFace;
	_rubricTxt.style.width = Math.min(_rubricTxt.offsetWidth, 1150) + "px";


	Wbox = createTag("div");
	Wbox.setAttribute("id", "wBox");
	_main.appendChild(Wbox);
	Wbox.style.position = "absolute";
	Wbox.style.left = Position_Of_WhiteBox_Left + "px";

	Wbox.style.height = ((Position_Of_QuestionBox_Top + Question_Box_Height + Position_Of_QuestionBox_Top) * NumOfBtns) - (Position_Of_QuestionBox_Top * (NumOfBtns - 1)) + "px";

	Wbox.appendChild(aSvg);
}

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);
	createLayout();

	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 = finalScore + "/" + storageArr.length;

	scorePanel.appendChild(scoreDisp);
	scoreDisp.setAttribute("id", "scoreDisp");
	addScorm();
}

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

	/* if (!SCO.connection.isActive) {
		return;
	} */

	let status = LMSget("cmi.core.lesson_status");
	let minScore = LMSget("cmi.core.score.min");
	if (!minScore) {
		LMSset("cmi.core.score.min", 0)
		LMSset("cmi.core.score.max", storageArr.length)
	}

	if (status !== "completed") {
		LMSset("cmi.core.lesson_status", "incomplete");
		finalScore = LMSget("cmi.core.score.raw");
		finalScore = parseInt(finalScore);
		finalScore = finalScore>0?finalScore:0;
		
		scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
		console.log("StorageArr****", storageArr);
		console.log("FIANL : ", finalScore);
		if (storageArr.length == finalScore) {
			LMSset("cmi.core.lesson_status", "completed");
		}
	}
	else {

		finalScore = LMSget("cmi.core.score.raw") || 0;
		finalScore = parseInt(finalScore);
		scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
		ResetBtn.style.visibility = "visible";

		ResetBtn.addEventListener("click", checkAgainScorm);
	}
	let lmsData = LMSget("cmi.suspend_data");
	console.log("LMS DATA: ", lmsData);

	if (lmsData != "null") {
		storageArr = JSON.parse(lmsData) || storageArr;

		handleSavedData();

		console.log(storageArr);
	}
	// saveData();

	console.log(status, LMSget("cmi.core.score.min"), LMSget("cmi.core.score.max"));
	// finalScore= LMSget("cmi.core.score.max",scoreDisp);
}

function handleSavedData() {
	// playFeedback("correct");
	answerBtn.style.cursor = "default";
	answerBtn.style.visibility = "visible";
	answerBtn.style.opacity = 0.5;
	answerBtn.style.zIndex = 1;
	answerBtn.removeEventListener("click", onanswerBtnClick);

	var div = document.getElementById('Svgcontainer');
	for (var i = 1; i <= NumOfBtns; i++) {
		if (storageArr[i - 1]["circleQ" + i] != null) {
			count++;
			var pkQ = document.getElementById("circleQ" + i);
			pkQ.style.border = "4px solid" + CnBcArr[(pkQ.Id) - 1].bclr;
			var pkA = document.getElementById("circleA" + Ans[i - 1][0]);

			x1 = pkQ.offsetLeft;
			y1 = pkQ.offsetTop;
			x2 = pkA.offsetLeft;
			y2 = pkA.offsetTop;

			var xxd = pkQ.lineMc.createline(x1 + 20, y1 + 20, x2 + 20, y2 + 20, '#009900', 5);
			aSvg.appendChild(xxd);

			Wbox.appendChild(aSvg);
			pkA.style.background = CnBcArr[(pkQ.Id) - 1].clr;
			pkA.style.border = "4px solid" + CnBcArr[(pkQ.Id) - 1].bclr;

			if (document.getElementsByName("CombTxt")[pkA.Id - 1] != undefined) {
				document.getElementsByName("CombTxt")[pkA.Id - 1].style.color = 'green';
				document.getElementsByName("CombTxt")[pkA.Id - 1].innerHTML = Ans[pkA.Id - 1][1];
			}


		}

	}

}


function createLayout() {
	for (i = 1; i <= NumOfBtns; i++) {

		var Qdiv = document.createElement('div');

		Qdiv.style.position = "absolute";
		Qdiv.style.overflow = "hidden";
		Qdiv.style.left = Position_Of_QuestionBox_Left + "px";
		Qdiv.style.height = Question_Box_Height + "px";
		Qdiv.style.width = Question_Box_Width + "px";
		Qdiv.style.top = Position_Of_QuestionBox_Top + ((i - 1) * (Question_Box_Height + Position_Of_QuestionBox_Top)) + "px";
		if (QesTxt[i - 1] == "") {
			var QdivImg = document.createElement('div');
			Qdiv.style.borderWidth = "3px";
			Qdiv.style.borderColor = "#F29B34";
			Qdiv.style.borderStyle = "solid";
			Qdiv.style.backgroundImage = "url(" + data._leftColImages[i - 1] + ")";
			//Qdiv.style.backgroundImage = "url(./Assets/images/QPic/img" + i + ".jpg)";
			Qdiv.style.backgroundRepeat = 'no-repeat';
			Qdiv.style.backgroundSize = 'contain';
			Qdiv.style.backgroundPosition = 'center';
		} else {
			var QdivTxt = document.createElement('div');
			Qdiv.appendChild(QdivTxt);
			QdivTxt.style.height = Question_Box_Height + "px";
			QdivTxt.style.width = Question_Box_Width + "px";
			QdivTxt.style.top = Qdiv.offsetTop + "px";
			QdivTxt.style.margin = "6px";
			//QdivTxt.style.background="#F29B34";
			QdivTxt.style.lineHeight = "29px";
			QdivTxt.style.textAlign = "right"
			QdivTxt.style.display = "table-cell";
			QdivTxt.style.verticalAlign = "middle";
			QdivTxt.style.fontSize = quesfntSize + "px";
			QdivTxt.style.fontFamily = fontFace1;
			QdivTxt.innerHTML = QesTxt[i - 1];
		}
		Wbox.appendChild(Qdiv);
		let key = 'circleQ' + i;
		storageArr.push({
			[key]: null,
			attempts: 0,
			isDone:false
		});
		var QdivC = document.createElement('div');
		Wbox.appendChild(QdivC);
		QdivC.id = 'circleQ' + i;
		QdivC.style.position = "absolute";
		QdivC.style.height = "30px";
		QdivC.style.width = "30px";
		QdivC.style.top = Qdiv.offsetTop + (Qdiv.offsetHeight / 2) - 17.5 + "px";
		QTopPosArr.push(Qdiv.offsetTop + (Qdiv.offsetHeight / 2) - 17.5);
		QdivC.style.background = CnBcArr[i - 1].clr;
		QdivC.style.borderRadius = "50px";
		QdivC.style.left = parseInt(Qdiv.offsetLeft) + parseInt(Qdiv.offsetWidth) + Space_Betn_Txt_And_Circl + "px";
		QLeftPosArr.push(parseInt(Qdiv.offsetLeft) + parseInt(Qdiv.offsetWidth) + Space_Betn_Txt_And_Circl);


		var clr = CnBcArr[i - 1].bclr;
		QdivC.style.borderWidth = "4px";
		QdivC.style.borderColor = clr;
		QdivC.style.borderStyle = "solid";
		QdivC.clk = true;
		QdivC.actives = true;
		QdivC.isRightAns = false;
		QdivC.attemptCount = 0;
		QdivC.sibling = null;
		QdivC.Id = i;
		//console.log(Ans[i-1][0]+"-------------------Ansss0000");
		//console.log(Ans[i-1][1]+"-------------------Ansss0000");
		QdivC.Ans = Ans[i - 1][0];
		QdivC.lineMc = new SVGline();
		QdivC.style.cursor = "pointer";
		QdivC.addEventListener("click", clickOnQ);

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

		var Adiv = document.createElement('div');
		Wbox.appendChild(Adiv);
		Adiv.style.position = "absolute";
		Adiv.style.overflow = "hidden";
		Adiv.style.top = parseInt(Qdiv.offsetTop) + "px";
		Adiv.style.height = Answer_Box_Height + "px";
		Adiv.style.width = Answer_Box_Width + "px";

		var AdivC = document.createElement('div');
		Wbox.appendChild(AdivC);
		AdivC.id = 'circleA' + i;
		AdivC.style.position = "absolute";
		AdivC.style.height = "30px";
		AdivC.style.width = "30px";
		AdivC.style.background = "#cccccc";
		AdivC.style.borderRadius = "50px";
		AdivC.style.top = QdivC.offsetTop + "px";
		AdivC.style.left = parseInt(QdivC.offsetLeft) + parseInt(QdivC.offsetWidth) + Horzontal_Space_Betn_Circl_And_Circl + "px";
		Adiv.style.left = parseInt(AdivC.offsetLeft) + parseInt(QdivC.offsetWidth) + Space_Betn_Txt_And_Circl + "px";
		AdivC.style.border = "4px solid #000000";
		AdivC.Id = i;
		AdivC.actives = true;
		AdivC.style.cursor = "pointer";
		AdivC.addEventListener("click", clickOnA);

		if (OptTxt[i - 1] == "") {


			//AnswerBox_Width

			var AdivImg = document.createElement('div');
			Adiv.appendChild(AdivImg);
			AdivImg.style.position = "absolute";
			AdivImg.style.height = 100 - 6 + "px";
			AdivImg.style.width = 200 - 6 + "px";

			/* if(Question_Box_Height>100){
				AdivImg.style.top=(Question_Box_Height-100)/2+"px";  
			  }
			  
			   if(Question_Box_Width>200){
			   AdivImg.style.left=parseInt(Adiv.offsetLeft)+"px";
			  
			   } */

			//AdivImg.style.background="#cccccc";
			/*  AdivImg.style.borderWidth="3px";
			 AdivImg.style.borderColor="#F29B34";
			 AdivImg.style.borderStyle="solid";
			 
			 AdivImg.style.background="url(./Assets/images/APic/img"+i+"_"+i+".png)"; */

			/* *************************** */
			Adiv.style.borderWidth = "3px";
			Adiv.style.borderColor = "#F29B34";
			Adiv.style.borderStyle = "solid";
			Adiv.style.backgroundImage = "url(" + data._rightColImages[i - 1] + ")";
			//Adiv.style.backgroundImage = "url(./Assets/images/APic/img" + i + ".jpg)";
			Adiv.style.backgroundRepeat = 'no-repeat';
			Adiv.style.backgroundSize = 'contain';
			Adiv.style.backgroundPosition = 'center';
			/* *************************** */

			Wbox.style.width = Position_Of_QuestionBox_Left + parseInt(Qdiv.offsetLeft) + parseInt(Qdiv.offsetWidth) + Space_Betn_Txt_And_Circl +
				parseInt(QdivC.offsetWidth) + Horzontal_Space_Betn_Circl_And_Circl + parseInt(AdivC.offsetWidth) + Space_Betn_Txt_And_Circl +
				+parseInt(Adiv.offsetWidth) + "px";

			aSvg.style.width = parseInt(Wbox.style.width) + "px";
			aSvg.style.height = parseInt(Wbox.style.height) + "px";

		} else {


			var AdivTxt = document.createElement('div');
			Adiv.appendChild(AdivTxt);
			AdivTxt.style.height = Answer_Box_Height + "px";
			AdivTxt.style.width = Answer_Box_Width + "px";

			// AdivTxt.style.background="#F29B34";
			AdivTxt.style.lineHeight = "29px";
			AdivTxt.style.textAlign = "left"
			AdivTxt.style.margin = "6px";
			AdivTxt.style.display = "table-cell";
			AdivTxt.style.verticalAlign = "middle";
			AdivTxt.style.fontSize = quesfntSize + "px";
			AdivTxt.style.fontFamily = fontFace1;
			AdivTxt.innerHTML = OptTxt[i - 1];

		}

		// console.log(Ans[i-1].length+"--------Anss");


		if (Ans[i - 1].length == 2) {
			//console.log("ends--------start");
			//var Atxt= str.replace('=','');
			//Anstxt=[];
			// Anstxt.push(Atxt);


			var Equldiv = document.createElement('div');
			Wbox.appendChild(Equldiv);
			Equldiv.style.position = "absolute";
			Equldiv.style.height = parseInt(Adiv.offsetHeight) + "px";
			Equldiv.style.width = (parseInt(Adiv.offsetWidth) + parseInt(Qdiv.offsetWidth) + 50) + "px";
			Equldiv.style.overflow = "hidden";
			Equldiv.style.top = parseInt(Adiv.offsetTop) + "px";

			// if(OptTxt[i-1].length!=0)
			// {
			// Equldiv.style.left=AnswerBox_Width+"px";   
			//}
			//else
			//{  
			Equldiv.style.left = parseInt(Adiv.offsetLeft) + parseInt(Adiv.offsetWidth) + "px";
			//}

			//Equldiv.style.background="#ffcccc";


			var EquldivSinTxt = document.createElement('div');
			Equldiv.appendChild(EquldivSinTxt);

			EquldivSinTxt.style.height = parseInt(Adiv.offsetHeight) + "px";
			EquldivSinTxt.style.width = 10 + "px";
			EquldivSinTxt.style.lineHeight = "29px";
			EquldivSinTxt.style.textAlign = "left"
			EquldivSinTxt.style.margin = "6px";
			EquldivSinTxt.style.display = "table-cell";
			EquldivSinTxt.style.verticalAlign = "middle";
			EquldivSinTxt.style.fontSize = quesfntSize + "px";
			EquldivSinTxt.style.fontFamily = fontFace1;
			EquldivSinTxt.innerHTML = "=";
			//EquldivSinTxt.style.background="#F29B34";

			var EquldivLine = document.createElement('div');
			Equldiv.appendChild(EquldivLine);
			EquldivLine.style.position = "absolute";
			// EquldivLine.style.background="#ff00ff";
			EquldivLine.style.left = 20 + "px";
			EquldivLine.style.top = 0 + "px";
			EquldivLine.style.height = parseInt(Equldiv.offsetHeight) - 3 + "px";
			//EquldivLine.style.width=parseInt(Equldiv.offsetWidth)+500+"px";
			EquldivLine.style.width = 250 + "px";
			EquldivLine.style.borderBottom = "3Px solid #000000";


			CombTxt = document.createElement('div');
			EquldivLine.appendChild(CombTxt);
			CombTxt.Id = i;
			CombTxt.setAttribute("name", "CombTxt");
			CombTxt.style.height = parseInt(EquldivLine.offsetHeight) + "px";

			//CombTxt.style.width=parseInt(Equldiv.offsetWidth)+200+"px";

			CombTxt.style.lineHeight = "29px";
			CombTxt.style.textAlign = "center"
			CombTxt.style.margin = "6px";
			CombTxt.style.display = "table-cell";
			CombTxt.style.verticalAlign = "middle";
			CombTxt.style.fontSize = quesfntSize + "px";
			CombTxt.style.fontFamily = fontFace1;

			Wbox.style.width = Position_Of_QuestionBox_Left + parseInt(Qdiv.offsetLeft) + parseInt(Qdiv.offsetWidth) + Space_Betn_Txt_And_Circl +
				parseInt(QdivC.offsetWidth) + Horzontal_Space_Betn_Circl_And_Circl + parseInt(AdivC.offsetWidth) + Space_Betn_Txt_And_Circl +
				+parseInt(Adiv.offsetWidth) + parseInt(Equldiv.offsetWidth) + "px";

			aSvg.style.width = parseInt(Wbox.style.width) + "px";
			aSvg.style.height = parseInt(Wbox.style.height) + "px";

		} else {
			//Anstxt=[];
			//Anstxt.push(OptTxt[i-1]);

			Wbox.style.width = Position_Of_QuestionBox_Left + parseInt(Qdiv.offsetLeft) + parseInt(Qdiv.offsetWidth) + Space_Betn_Txt_And_Circl +
				parseInt(QdivC.offsetWidth) + Horzontal_Space_Betn_Circl_And_Circl + parseInt(AdivC.offsetWidth) + Space_Betn_Txt_And_Circl +
				+parseInt(Adiv.offsetWidth) + "px";

			aSvg.style.width = parseInt(Wbox.style.width) + "px";
			aSvg.style.height = parseInt(Wbox.style.height) + "px";
		}

	}
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	if (HedArr.length != 0) {
		w1 = document.createElement('div');
		Wbox.appendChild(w1);
		w1.className = "dBox";
		w1.innerHTML = HedArr[0];
		w1.style.fontSize = quesfntSize + "px";

		w2 = document.createElement('div');
		Wbox.appendChild(w2);
		w2.className = "dBox";
		w2.style.fontSize = quesfntSize + "px";
		w2.innerHTML = HedArr[1];

		var tmp = [3, 4, 2];

		w1.style.top = -w2.offsetHeight - tmp[GRADE - 1] + "px";

		w2.style.top = parseInt(w1.offsetTop) + "px";

		if (w1.offsetWidth > w2.offsetWidth) {
			w2.style.width = parseInt(w1.offsetWidth) - 25 + "px";

		} else {
			w1.style.width = parseInt(w2.offsetWidth) - 25 + "px";
		}

		w1.style.left = (parseInt(QdivC.offsetLeft) - parseInt(w2.offsetWidth) + 40) / 2 + "px";
		w2.style.left = (parseInt(Wbox.offsetWidth) - parseInt(w2.offsetWidth) - 7) - parseInt(w1.offsetLeft) + "px";

		w1.style.visibility = "visible";
		w2.style.visibility = "visible";

		// //console.log(_rubricTxt+"--------");

		Wbox.style.top = (parseInt(_rubricTxt.offsetHeight) + parseInt(w2.offsetHeight) + 15) + Position_Of_WhiteBox_Top + "px";

	}
	else {


		Wbox.style.top = (parseInt(_rubricTxt.offsetHeight) + 15) + Position_Of_WhiteBox_Top + "px";
	}



	Wbox.style.visibility = "visible";

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

	CheckSolutionDiv.style.top = parseInt(Wbox.offsetTop) + parseInt(Wbox.offsetHeight) - 450 + "px";
	CheckSolutionDiv.style.left = parseInt(Wbox.offsetLeft) + parseInt(Wbox.offsetWidth) - 80 + "px";

	submitBtn = createTag("div");
	submitBtn.setAttribute("id", "submit");
	submitBtn.innerHTML = "CHECK";
	CheckSolutionDiv.appendChild(submitBtn);

	submitBtn.style.visibility = "visible";
	submitBtn.style.opacity = 0.5;
	submitBtn.style.cursor = "default";

	answerBtn = createTag("div");
	answerBtn.setAttribute("id", "answer");
	answerBtn.innerHTML = "SOLUTION";
	CheckSolutionDiv.appendChild(answerBtn);
	answerBtn.style.visibility = "visible";

	ResetBtn = document.createElement("div");
	//ResetBtn.className = "answer";

	ResetBtn.setAttribute("id", "Reset");
	ResetBtn.innerHTML = "RESET";
	ResetBtn.addEventListener("click", checkAgainScorm)
	CheckSolutionDiv.appendChild(ResetBtn);





	answerBtn.addEventListener("click", onanswerBtnClick);


}



function clickOnQ(e) {

	var optQ = e.target;

	mouseObject = optQ;
	isMouseDown = true;
	optQ.actives = true;
	resetAll();

	optQ.style.top = QTopPosArr[(optQ.Id) - 1] - 2 + "px";
	optQ.style.left = QLeftPosArr[(optQ.Id) - 1] - 2 + "px";

	optQ.style.border = "6px solid" + CnBcArr[(optQ.Id) - 1].bclr;

	if (optQ.ln != undefined && optQ.sibling != null) {
		aSvg.removeChild(optQ.ln);
		optQ.sibling.style.cursor = "pointer";
		optQ.sibling.style.background = "#cccccc";
		optQ.sibling.style.border = "4px solid #000000";
		optQ.sibling.actives = true;
		optQ.ln = null;

		count--;

		if (document.getElementsByName("CombTxt")[optQ.sibling.Id - 1] != undefined) {
			document.getElementsByName("CombTxt")[optQ.sibling.Id - 1].innerHTML = "";
		}

	}

	if (attempts == 0) {

		if (count < 5) {
			submitBtn.removeEventListener("click", onSubmitClick);
			submitBtn.style.opacity = 0.5;
			submitBtn.style.cursor = "default";

		}


	} else {
		if (count < wArray.length) {
			submitBtn.removeEventListener("click", onSubmitClick);
			submitBtn.style.opacity = 0.5;
			submitBtn.style.cursor = "default";

		}

	}
}

function checkAgainScorm() {
	console.log("Check again ************");
	resetAll()
	// enableAll();
	finalScore = 0;
	scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
	storageArr = []
	//console.log(totalAttempts);
	totalAttempts = 0;
	console.log(totalAttempts);
	var svgtag = document.getElementsByTagName("svg")[0];
	while (svgtag.firstChild) {
		svgtag.removeChild(svgtag.firstChild);
	}
	//console.log("asdf asdf asdf ");
	ResetBtn.style.pointerEvents = "none";
	ResetBtn.style.opacity = 0.5;
	count = 0;
	for (var j = 1; j <= NumOfBtns; j++) {

		//console.log(document.getElementById("circleA" + j));
		var resetPkA = document.getElementById("circleA" + j)
		resetPkA.style.background = "rgb(204, 204, 204)"
		resetPkA.style.border = "4px solid rgb(0, 0, 0)"

		//console.log(j);
		//console.log(NumOfBtns);
		let key = "circleQ" + j;
		var pkk = document.getElementById("circleQ" + j);
		//Pushing an object into the array
		storageArr.push({
			[key]: null,
			attempts: 0,
			isDone:false
		})
	}
}


function resetAll() {
	console.log("reset------------*****************");
	for (var i = 1; i <= NumOfBtns; i++) {
		var x = document.getElementById("circleQ" + i);

		x.style.top = QTopPosArr[(i) - 1] + "px";
		x.style.left = QLeftPosArr[(i) - 1] + "px";

		x.style.background = CnBcArr[(x.Id) - 1].clr;
		x.style.border = "4px solid" + CnBcArr[(x.Id) - 1].bclr;

	}
}


SVGline.prototype.createline = function (x1, y1, x2, y2, color, w) {

	var aLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
	aLine.setAttribute('x1', x1);
	aLine.setAttribute('y1', y1);
	aLine.setAttribute('x2', x2);
	aLine.setAttribute('y2', y2);
	aLine.setAttribute('stroke', color);
	aLine.setAttribute('stroke-width', w);
	aLine.align
	return aLine;
}

function clickOnA(e) {
	console.log("baaaaa....");

	var optA = e.target;
	isMouseDown = false;

	if (mouseObject && optA.actives) {

		mouseObject.clk = false;

		mouseObject.style.background = CnBcArr[(mouseObject.Id) - 1].clr;
		mouseObject.style.border = "4px solid" + CnBcArr[(mouseObject.Id) - 1].bclr;


		mouseObject.style.top = QTopPosArr[(mouseObject.Id) - 1] + "px";
		mouseObject.style.left = QLeftPosArr[(mouseObject.Id) - 1] + "px";


		if (mouseObject.Ans[0] == optA.Id) {

			mouseObject.isRightAns = true;
			mouseObject.ans = optA.Id;
			x1 = mouseObject.offsetLeft;
			y1 = mouseObject.offsetTop;
			x2 = optA.offsetLeft;
			y2 = optA.offsetTop;
			var xx = mouseObject.lineMc.createline(x1 + 20, y1 + 20, x2 + 20, y2 + 20, '#000000', 5);
			mouseObject.ln = xx;
			aSvg.appendChild(xx);
			
		}
		else {
			
			mouseObject.isRightAns = false;
			x1 = mouseObject.offsetLeft;
			y1 = mouseObject.offsetTop;
			x2 = optA.offsetLeft;
			y2 = optA.offsetTop;
			var xxx = mouseObject.lineMc.createline(x1 + 20, y1 + 20, x2 + 20, y2 + 20, '#000000', 5);
			mouseObject.ln = xxx;
			xxx.style.position = "absolute";
			aSvg.appendChild(xxx);
		}
		document.getElementById(optA.id).style.background = CnBcArr[(mouseObject.Id) - 1].clr;
		document.getElementById(optA.id).style.borderColor = CnBcArr[(mouseObject.Id) - 1].bclr;

		mouseObject.actives = false;
		mouseObject.sibling = optA;
		mouseObject.ansA = optA;
		mouseObject = null;

		optA.actives = false;
		optA.style.cursor = "default";
		count++;
		if (attempts == 0) {

			if (count == NumOfBtns) {
				submitBtn.addEventListener("click", onSubmitClick);
				submitBtn.style.opacity = 1;
				submitBtn.style.cursor = "pointer";


			} else {

				submitBtn.removeEventListener("click", onSubmitClick);
				submitBtn.style.opacity = 0.5;
				submitBtn.style.cursor = "default";

			}

		} else {

			if (count == wArray.length) {
				submitBtn.addEventListener("click", onSubmitClick);
				submitBtn.style.opacity = 1;
				submitBtn.style.cursor = "pointer";
			}
		}
	}
}

function NumCount() {

	console.log("aaaaaa....");
	for (i = 1; i <= NumOfBtns; i++) {
		var pkQ = document.getElementById("circleQ" + i);
		var pkA = document.getElementById("circleA" + i);

		if (!pkQ.actives && !pkA.actives) {

			count++;

		} else {

			count--;
		}
	}
	console.log("question" + pkQ);
	console.log("question" + pkA);
}


function desableAll() {
	console.log("avaaaa....");


	for (i = 1; i <= NumOfBtns; i++) {
		var pkQ = document.getElementById("circleQ" + i);

		pkQ.actives = false;
		pkQ.style.cursor = "default";
		pkQ.removeEventListener("click", clickOnQ);

		var pkA = document.getElementById("circleA" + i);
		pkA.actives = false;
		pkA.style.cursor = "default";
		pkQ.removeEventListener("click", clickOnA);
	}
	submitBtn.style.opacity = 0.5;
	submitBtn.style.zIndex = 1;
	submitBtn.style.cursor = "default";


	answerBtn.style.cursor = "default";
	answerBtn.style.opacity = 0.5;
	answerBtn.removeEventListener("click", onanswerBtnClick);
}

function enableAll() {
	console.log("Enabling elements...");

	for (var i = 1; i <= NumOfBtns; i++) {
		var pkQ = document.getElementById("circleQ" + i);

		pkQ.actives = true;
		pkQ.style.cursor = "pointer";
		pkQ.addEventListener("click", clickOnQ);

		var pkA = document.getElementById("circleA" + i);
		pkA.actives = true;
		pkA.style.cursor = "pointer";
		pkA.addEventListener("click", clickOnA);
	}

	submitBtn.style.opacity = 1;
	submitBtn.style.zIndex = 2;
	submitBtn.style.cursor = "pointer";

	answerBtn.style.cursor = "pointer";
	answerBtn.style.opacity = 1;
	answerBtn.addEventListener("click", onanswerBtnClick);

	console.log("Elements enabled!");
}

function onSubmitClick() {
	submitBtn.removeEventListener("click", onSubmitClick);
	submitBtn.style.opacity = 0.5;
	submitBtn.style.cursor = "default";
	answerBtn.style.opacity = 0.5;
	answerBtn.style.cursor = "default";
	answerBtn.removeEventListener("click", onanswerBtnClick);
	// console.log("finalScore on submit click",finalScore);
	// scoreDisp.innerHTML = finalScore+"/" + storageArr.length;
	
	let status = LMSget("cmi.core.lesson_status");
	

	checkAnswer();
	scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
	if (status !== "completed") {
		let rawScore = LMSset("cmi.core.score.raw", finalScore);
	}
}

function checkAnswer() {
	var _rightCnt = 0;
	var _wrongCnt = 0;
	var tempR = 0;
	for (var i = 0; i < NumOfBtns; i++) {
		var pkk = document.getElementById("circleQ" + (i + 1));
		totalAttempts = storageArr[i].attempts += 1;

		if( storageArr[i].isDone){
			console.log("DONE: ", pkk);
			continue;
		}
		
		if (!pkk.isRightAns) {
			if (!pkk.actives) {
				console.log("wronggggg");
				_wrongCnt++;
				wArray.push(_wrongCnt);
				aSvg.removeChild(pkk.ln);
				x1 = pkk.offsetLeft;
				y1 = pkk.offsetTop;
				x2 = pkk.sibling.offsetLeft;
				y2 = pkk.sibling.offsetTop;

				var xx = pkk.lineMc.createline(x1 + 20, y1 + 20, x2 + 20, y2 + 20, '#FF0000', 5);
				pkk.ln = xx;

				aSvg.appendChild(xx);

				console.log("xxxx:" + xx);

				console.log(pkk, "wrong")


				// //
				if (document.getElementsByName("CombTxt")[pkk.sibling.Id - 1] != undefined) {
					document.getElementsByName("CombTxt")[pkk.sibling.Id - 1].style.color = 'red';

				}
				pkk.removeEventListener("click", clickOnQ);
				pkk.style.cursor = "default";
			}
		} else {
			var rectangleR = pkk.ln;
			aSvg.removeChild(rectangleR);
			finalScore++;
			x1 = pkk.offsetLeft;
			y1 = pkk.offsetTop;
			x2 = pkk.sibling.offsetLeft;
			y2 = pkk.sibling.offsetTop;

			var xxd = pkk.lineMc.createline(x1 + 20, y1 + 20, x2 + 20, y2 + 20, '#009900', 5);

			pkk.ln = xxd;

			aSvg.appendChild(xxd);
			tempR++;
			_rightCnt++;

			console.log(storageArr, pkk, pkk.id, " right *-*-*-", pkk.isRightAns);
			let idd = pkk.id.replace("circleQ", "");
			storageArr[i][pkk.id] = "circleA" + pkk.ans;
			storageArr[i].isDone = true;
			idd++;

			console.log(idd, "***********8888899997774445566");

			// let attCnt = parseInt(storageArr[i].attempts);
			// // console.log(attCnt+=1, "NNO");
			// storageArr[i].attempts = attCnt+=1;

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

			if (document.getElementsByName("CombTxt")[pkk.sibling.Id - 1] != undefined) {
				document.getElementsByName("CombTxt")[pkk.sibling.Id - 1].style.color = 'green';
				document.getElementsByName("CombTxt")[pkk.sibling.Id - 1].innerHTML = Ans[pkk.Id - 1][1];
			}

			pkk.removeEventListener("click", clickOnQ);
			pkk.style.cursor = "default";
		}
	}

	if (_rightCnt >= 1 && _wrongCnt <= 0) {
		playFeedback("right");
		//feedbackVid.playCorrectFeedback();
		feedbackAnim.gotoAndPlay("right");
		desableAll();
		LMSset("cmi.suspend_data", JSON.stringify(storageArr));
		LMSset("cmi.core.lesson_status", "completed");
		setTimeout(activityComplete, 3000);
	}else {
		console.log(NumOfBtns - 1);

		// console.log(storageArr[a]);
		if (!attempts && tempR) {
			attempts++;
			// 	for(var a=0;a<NumOfBtns-1;a++){
			// 		storageArr[a].attempts=attempts
			//    }
			// storageArr[i].attempts=attempts
			playWrongFeedback(tempR);

		} else {
			attempts++;
			// storageArr[i].attempts=attempts

			playFeedback("wrong");

		}
		//feedbackVid.playWrongFeedback();
		feedbackAnim.gotoAndPlay("wrong");

	}
	console.log(storageArr);
	setTimeout(function () { feedbackAnim.gotoAndStop("ideal"); }, 3000)

	let status = LMSget("cmi.core.lesson_status");
	if (status !== "completed") {
		LMSset("cmi.suspend_data", JSON.stringify(storageArr));
		//SCO.save();
	}
}

function onanswerBtnClick() {
	seeAnswers();
}


function seeAnswers() {
	storageArr = []
	playFeedback("correct");
	totalAttempts = 0;
	answerBtn.style.cursor = "defauldesableAll()fit";
	answerBtn.style.visibility = "visible";
	answerBtn.style.opacity = 0.5;
	answerBtn.style.zIndex = 1;
	answerBtn.removeEventListener("click", onanswerBtnClick);

	var div = document.getElementById('Svgcontainer');

	for (var i = 1; i <= NumOfBtns; i++) {

		var pkQ = document.getElementById("circleQ" + i);

		pkQ.style.border = "4px solid" + CnBcArr[(pkQ.Id) - 1].bclr;

		if (pkQ.ln != undefined) {

			aSvg.removeChild(pkQ.ln);
		}

		var pkA = document.getElementById("circleA" + Ans[i - 1][0]);
		var Saveans = pkA.id
		x1 = pkQ.offsetLeft;
		y1 = pkQ.offsetTop;
		x2 = pkA.offsetLeft;
		y2 = pkA.offsetTop;

		var xxd = pkQ.lineMc.createline(x1 + 20, y1 + 20, x2 + 20, y2 + 20, '#009900', 5);
		aSvg.appendChild(xxd);

		Wbox.appendChild(aSvg);
		pkA.style.background = CnBcArr[(pkQ.Id) - 1].clr;
		pkA.style.border = "4px solid" + CnBcArr[(pkQ.Id) - 1].bclr;

		if (document.getElementsByName("CombTxt")[pkA.Id - 1] != undefined) {
			document.getElementsByName("CombTxt")[pkA.Id - 1].style.color = 'green';
			document.getElementsByName("CombTxt")[pkA.Id - 1].innerHTML = Ans[pkA.Id - 1][1];
		}
		let key = 'circleQ' + i;

		storageArr.push({
			[key]: Saveans,
			attempts: 2
		});
		//console.log(storageArr);
	}


	console.log(storageArr);

	LMSset("cmi.suspend_data", JSON.stringify(storageArr));
	SCO.save();


	desableAll();
	LMSset("cmi.core.lesson_status", "completed");
	setTimeout(activityComplete, 5000);

}

function activityComplete() {
	console.log("activityComplete************");
	var Main = document.getElementById('main');
	var Main2 = document.getElementById('checkSolution');
	var div1 = document.getElementById('wBox');

	var divdBox1 = document.getElementById('dBox1');
	var divdBox2 = document.getElementById('dBox2');

	Main.removeChild(_rubricTxt);
	Main.removeChild(div1);

	Main2.removeChild(submitBtn);
	Main2.removeChild(answerBtn);

	document.getElementById("main").style.display = "none";
	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(function () {
		completedDelay();
		// Set SCORM status to "completed" here		
	}, 500);
}

function completedDelay() {
	console.log("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 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 (attempts == 1) {
				wArr = wArr.concat(nArr);
			}
			if (attempts == ATTEMPTS_ALLOWED) {
				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";
			audio.addEventListener("ended", FeedbacksoundComplete);

			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 playVideo() {
	fVideo.play();
	fVideo.addEventListener("ended", onVideoEnd);

}

function onVideoEnd() {
	fVideo.style.zIndex = -1;
	fVideo.removeEventListener("ended", onVideoEnd);
	fVideo.src = "";

};


function playWrongFeedback(id) {
	// audio = document.createElement("audio");
	sourceOGG.src = "../__audio/" + oneOrTwoAudio[id - 1] + ".ogg";
	sourceMP3.src = "../__audio/" + oneOrTwoAudio[id - 1] + ".mp3";
	audio.load();
	audio.play();
	audio.addEventListener("ended", FeedbacksoundComplete);
}


function FeedbacksoundComplete() {
	audio.removeEventListener("ended", FeedbacksoundComplete);
	console.log(totalAttempts);
	console.log(ATTEMPTS_ALLOWED);
	if (totalAttempts == ATTEMPTS_ALLOWED) {
		totalAttempts = 0;
		console.log("checKSeeAnswerCall");
		setTimeout(() => {
			seeAnswers();
		}, 500)
		handleSavedData();
	}
	Ree();
}
console.log(attempts);
console.log(ATTEMPTS_ALLOWED);

function Ree() {
	count = 0;

	for (var i = 0; i < NumOfBtns; i++) {
		var pkk = document.getElementById("circleQ" + (i + 1));

		if (!pkk.isRightAns) {
			answerBtn.style.opacity = 1;
			answerBtn.style.cursor = "pointer";
			answerBtn.addEventListener("click", onanswerBtnClick);
			var rectangleD = pkk.ln;
			aSvg.removeChild(rectangleD);
			pkk.ln = null;
			pkk.actives = true;
			pkk.ansA.actives = true;
			pkk.style.cursor = "pointer";
			pkk.ansA.style.cursor = "pointer";

			document.getElementById(pkk.ansA.id).style.background = LAnsArr[0].inClr;
			document.getElementById(pkk.ansA.id).style.borderColor = LAnsArr[0].bClr;

			if (document.getElementsByName("CombTxt")[pkk.ansA.Id - 1] != undefined) {
				document.getElementsByName("CombTxt")[pkk.ansA.Id - 1].innerHTML = "";
				document.getElementsByName("CombTxt")[pkk.ansA.Id - 1].style.color = 'black';
			}

			pkk.style.cursor = "pointer";
			pkk.addEventListener("click", clickOnQ);
		} else {
			answerBtn.style.opacity = 1;
			answerBtn.style.cursor = "pointer";
			// answerBtn.addEventListener("click", onanswerBtnClick);
		}
	}

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

}

function createTag(str) {
	return (document.createElement(str));
}

function LMSget(key) {
	let val = null;
	//return localStorage.getItem(key);
	try {
		val = SCO.get(key);
	} catch (err) {
		console.log("LMS GET ERROR: ", val);
	}
	return val;
}

function LMSset(key, value) {
	//localStorage.setItem(key, value); return;
	try {
		SCO.set(key, value);
		SCO.save();
	} catch (err) {
		console.log("LMS SET ERROR: ", err);
	}
}

