/* JavaScript Document  
/  @author Ch-Nityanand Ojha
*/
var GRADE = 2;

var sourceOGG = ""
var sourceMP3 = ""


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


var drawNextQuestionDelay = 3000;
var drawIncorrectQuestionDelay = 4000;
var makeAnimationSpaceDelay = 3500;
var playAnimationDelay = 60;
var MAX_CHILDREN=2;
var introDelay = 1000;
var SAVE_DATA = true;
var VERT_MARG = 15;
var visible=["hidden","visible"];
var fontFace = "Rubric, sans-serif";
var fontFace1 = "Ans, sans-serif";
var optMargin = 5;
var storedData=[];
var storedAtt=[];
var cData=[];
var allDone = [];
var SAVE_ANS = true;
var colorObj = {initial:"#ffff99", select:"#99ffff",defaultText:"#000000", correctText:"#009900", wrongText:"#FF0000"};
const noSpaceWords = [".",","];
var _main;
var MAX_COUNT=0;
var MIN_REQUIRED=1;
var _rubricTxt;
var _quesTxt;
var srialNo;
var option;
var audio;
var count=1;
var interval;
var submitBtn;
var answerBtn;
var checkSol;

var preNxt;

var filledCount=0;
var correctCount=0;
var containerEnabled=false;
var opArr=[];
var optDiv;

var currentQ = 0;
var inCorrect = 0;
var selMC;
var prevBox;
var dropEnabled=false;
var attempts=0;
var introVid;
var onTarget=false;
var optMaxWidth=0;

var questionDone=0;
var rCount = 0;
var optionCount=0;
var ALLOWED=0;
var MARK = MARKUP || null;
var MARKC="";
var SCO;
var Status;
var scoreDisp;
var finalScore = 0;
var uniqueObjects = []
var filteredData=[]
//clicknPlace();

//////// G for grammer, V for vocabulary..........
var introType = "";
startIntro()
function startIntro()
{
	introVid = createTag("video");
	titleText = createTag("div");
	document.body.appendChild(introVid);
	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);
	//console.log("START........");
	
	if(introType.length==0) 
		introVid.style.visibility = 'hidden';
	
	
	switch (introType.toLowerCase())
	{
		case "g":
			titleText.innerHTML = data.title;
			titleText.style.width = "630px";
			titleText.style.top="400px";
			titleText.style.left="590px";
			titleText.style.color = "#000";
			introVid.src = "../__intro/Title_Grammar.webm"
			introVid.play();
			setTimeout(showTitle, 3000);
			break;
		case "v":
		    titleText.innerHTML = data.title;
			titleText.style.width = "712px";
			titleText.style.top="400px";
			titleText.style.left="205px";
			titleText.style.color = "#000";
			introVid.src = "../__intro/Title_Vocab.webm";				
			introVid.play();
			setTimeout(showTitle, 5000);
			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, createLayout);
		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, createLayout);
}


function resetActivity() {

	finalScore = 0;
	questionDone=0;
	scoreDisp.innerHTML = finalScore + "/" + finalmarks;

	cData = {}
	storedData = []
	cleanAll();	
	arrangeOptions(currentQ);
	var obj;
	for(var i=0;i<optionCount;i++)
	{
		obj = getElement("op"+i);
		//console.log("RESETING:  ", obj);
		if(!obj.classList.contains("option-right")){			
			//console.log("RESET: ",obj, obj.clicked, obj.isDone);	
			//obj.removeChild(obj.lastChild);
			optDiv.appendChild(obj);
			obj.clicked = false;
			enableOpt(obj);
			obj.classList.remove("option-wrong");
			
			//$(obj).animate({left:obj.xpos, top:obj.ypos},200);
			obj.style.left = obj.xpos + "px";
			obj.style.top = obj.ypos + "px";
		}
	}
	// 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", finalmarks)
	}
	if (status !== "completed") {
		finalScore = SCO.get("cmi.core.score.raw") || 0;
		finalScore = parseInt(finalScore);
		scoreDisp.innerHTML = finalScore + "/" + finalmarks;
		console.log("FIANL : ", finalScore);
	}
	else {
		setScore = SCO.get("cmi.core.score.raw") || 0;
		finalScore = parseInt(setScore);
		scoreDisp.innerHTML = finalScore + "/" + finalmarks;
		ResetBtn.style.visibility = "visible";
		ResetBtn.addEventListener("click", resetActivity);
	}
	

	let lmsData = SCO.get("cmi.suspend_data");
	console.log("LMS DATA: ", lmsData);
	if (lmsData.length) {
		console.log("rajji0",cData,storedData,storedData[currentQ]);
		receiveFullData = lmsData.split("*")
		console.log("rajji1",cData,storedData,storedData[currentQ]);
		cData = JSON.parse(receiveFullData[0]);
		// storedData[currentQ]=cData
		attempts=receiveFullData[1]
		console.log("rajji2",cData,storedData,storedData[currentQ]);
		questionDone=JSON.parse(receiveFullData[2])
	}
	storedData[currentQ]=cData
	console.log("DATA: ", lmsData);
}

function feedbackAnim(){
	_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 createLayout(){
	//console.log("TTT:  ",TEMP);
	
	//optMargin = Math.floor(quesfntSize/10);
	
	if(MARK){
	MARKC = MARK.replace(new RegExp("<", 'g'), "</"); 
	}
	//console.log("MARKC: ", MARKC);
	optMargin = getWidthOf("_",".option", quesfntSize);
	optMargin = 50;		
	
	document.body.removeChild(introVid);	
	introVid = null;
	document.body.removeChild(titleText);
	titleText = null;	
	
		_main = getElement(MAINTAG);

	//_stage=createTag("div");
	//_stage.setAttribute("id", "stage");
	//_main.appendChild(_stage);
		
	checkSol = createTag("div");
	checkSol.setAttribute("id", "checkSolution");
	_main.appendChild(checkSol);
	
	submitBtn = createTag("div");
	submitBtn.setAttribute("id", "submitBtn");
	submitBtn.innerHTML = "CHECK";
	
	answerBtn = createTag("div");
	answerBtn.setAttribute("id", "answerBtn");
	answerBtn.innerHTML = "SOLUTION";
	

	
	ResetBtn = document.createElement("div");
	//ResetBtn.className = "answer";
	ResetBtn.innerHTML = "RESET";
	ResetBtn.setAttribute("id", "Reset");
	checkSol.appendChild(ResetBtn);
	
	checkSol.appendChild(submitBtn);
	checkSol.appendChild(answerBtn);
	
	//submitBtn = document.getElementById("submitBtn");
	submitBtn.style.pointerEvents = "none";
	submitBtn.style.opacity = 0.5;
	//submitBtn.style.visibility = "hidden";

	submitBtn.addEventListener("click", onSubmitClick);

	//answerBtn = document.getElementById("answerBtn");
	//answerBtn.style.visibility = "hidden";
	answerBtn.addEventListener("click", onSolution);
	
	srialNo = document.createElement("div");
	_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");
	_main = document.getElementById("main");
	
	_rubricTxt = document.createElement("div");
	_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.position = "absolute";
	//_rubricTxt.innerHTML = 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.fontSize = rubricfntSize + "px";
	_rubricTxt.style.fontFamily = fontFace;
	_rubricTxt.style.width = Math.min(1000,_rubricTxt.offsetWidth)+"px";
	_rubricTxt.style.color = "#3d8eb9";
	/*_rubricTxt.style.pointerEvents = "none";*/
	
	optDiv = createTag("div");
	optDiv.setAttribute("id","optDv");
	optDiv.style.left = Q_BOX_LEFT + "px";
	
	
	//optDiv.style.top = Q_BOX_TOP + "px";
	getElement("main").appendChild(optDiv);
	
	addNumbering(currentQ);
	addNextPrev();
	
	
soundComplete();
try {
	addScorm();
} catch (err) {
}
arrangeOptions(currentQ);
// createDropBoxes()
	//soundComplete();
	//arrangeOptions();
	//createDropBoxes();
	
}


function addNextPrev()
{
	preNxt = createTag("div");
	preNxt.setAttribute("id", "preNext");
	_main.appendChild(preNxt);
	
	preNxt.style.top = "597px";
	preNxt.style.left = "355px";
	preNxt.style.visibility = "hidden";
	
	var preBtn = createTag("div");
	preBtn.className = "prenxt";
	preBtn.setAttribute("id", "prev");
	preBtn.style.cssFloat = "left";
	preBtn.addEventListener("click", onPrev);
	
	preNxt.appendChild(preBtn);
	disableObj(preBtn);
	
	var nxtBtn = createTag("div");
	nxtBtn.className = "prenxt";
	nxtBtn.setAttribute("id", "next");
	nxtBtn.style.cssFloat = "right";
	nxtBtn.addEventListener("click", onNext);
	
	preNxt.appendChild(nxtBtn);
	
	//preNxt.addEventListener("click", onNextPrev);
	
}


function onNext(e)
{
	cleanAll();	
	++currentQ;
	arrangeOptions();
	//checkNextPrev();
}

function onPrev(e)
{
	cleanAll();	
	--currentQ
	arrangeOptions();
	//checkNextPrev();
}


function checkNextPrev()
{	
	//console.log("Current Q: ", currentQ);
	(currentQ)? enableObj(getElement("prev")):disableObj(getElement("prev"));	
	(currentQ < questionArr.length-1)?enableObj(getElement("next")):disableObj(getElement("next"));
}



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.load()
audio.load();
audio.play();
    audio.addEventListener("ended", rubComplete);


   }


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

function soundComplete(){
	//document.getElementById("wBox").style.visibility = "visible";
	submitBtn.style.visibility = "visible";
	answerBtn.style.visibility = "visible";
	getElement("checkSolution").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");
	finalmarks=questionArr[currentQ][0].split(BREAKMARK).filter(data=>data!=="").length;
	scoreDisp.innerHTML = finalScore + "/" + finalmarks;
	// scoreDisp.innerHTML = setScore + "/" + questionArr.length;
	scorePanel.appendChild(scoreDisp);
	scoreDisp.setAttribute("id", "scoreDisp")
	
}

function arrangeOptions()
{	
	//feedbackVid.doReset();
	feedbackAnim.gotoAndStop("ideal");
	
	var opt;
	var count=0;
	var prevW=10;
	var offset=0;
	var ln=0;
	var wd=0;
	var url;
	var tempArr=[];
	var boxW=0;
	var toggle = false;
	var iid=0;
	var toggeling = true;
	optionCount =0;
	var boxCount = 0;	
	//cleanAll();
	boxCount = createDropBoxes();
	disableSubmitBTN();
	enableSolution();
	clickedArr=[];
	filledCount=0;
	attempts=0;
	srialNo.style.visibility = visible[Number(Boolean(questionArr.length-1))];
	getElement("sNum").innerHTML = (currentQ+1)+".";
	
	//qText = getBroken(quesArr[currentQ]);
	
	MAX_COUNT = (ansArrays[currentQ].length >2)?2:1;
	//console.log("MAX:  ", MAX_COUNT);
	optMaxWidth = 0;
	correctCount = 0;
	preNxt.style.visibility = srialNo.style.visibility;
	checkNextPrev();
	
	if(!BREAKMARK.length)
	{
		BREAKMARK = " ";
		toggeling = false;
		toggle = true;
	}	
	
	
	for(var h=0;h<questionArr[currentQ].length;h++)
	{		
		tempArr = questionArr[currentQ][h].split(BREAKMARK);
		//console.log("QQQQQ:  ", tempArr);
		
		for(var i=0;i<tempArr.length;i++)
		{			
			var bg;
			var temp;
			if(tempArr[i] == " " || tempArr[i] == "")
			{					
				toggle = !toggle;
				continue;				
			}
			
			opt = document.createElement("div");
			opt.className = "option";
			
			opt.style.fontSize = quesfntSize + "px";
			opt.atts =0;
			opt.clicked = false;
			opt.isDone=false;
			opt.onTarget = false;
			opt.innerHTML = tempArr[i];			
			temp = prevW+getWidthOf(tempArr[i],".option",quesfntSize);
			offset = Math.max(temp,offset);
			wd= parseInt(offset/MAX_WIDTH);
			//ln= ln + Math.floor(offset/MAX_WIDTH);
			//opt.ans = getAns(opt);
			boxW = Math.max(boxW,prevW);
			//console.log("ANS: ", getAns(opt));
			if(offset>MAX_WIDTH)
			{
				//console.log("MAXXXXXXX: ", offset, MAX_WIDTH);
				prevW=10;
				offset -= (optMargin+getWidthOf(tempArr[i],".option",quesfntSize));
				ln++;
			}
			
			optDiv.appendChild(opt);
			opt.style.top = (ln*LINE_HEIGHT) + "px";
			opt.style.height = 40+"px";
					
			opt.style.left = (prevW)+"px";
			prevW = parseInt(opt.style.left) + getWidthOf(tempArr[i],".option",quesfntSize) + optMargin;
			if(noSpaceWords.indexOf(tempArr[i]) > -1)
			{				
				prevW -= (optMargin*3);
				opt.style.left = (prevW)+"px";				
			}
							
			boxW = Math.max(boxW,prevW);
			
			//opt.addEventListener("click", onOpt);
			
			opt.xpos = parseInt(opt.style.left);
			opt.ypos = parseInt(opt.style.top);
			
			toggle && myFun(opt,iid++,count++);
			toggeling && (toggle = !toggle);
			
			MIN_REQUIRED = MIN_REQUIRED || 1;
			//console.log("--",opt,opt.innerHTML,opt.offsetHeight);
			//console.log(i,"OFFSET:  ", offset,  "  PrevW:  ", prevW);
		}
		//console.log(ln,LINE_HEIGHT);
		
		//optDiv.style.height = (((ln+1)*(LINE_HEIGHT/2)))+"px";	
	}
	//console.log("======MAX:  ", optMaxWidth);
	if(boxCount>2){
		ALLOWED = 2;
		ATTEMPTS_ALLOWED = 2;
	}else{
		ALLOWED =1;
		ATTEMPTS_ALLOWED = 1;
	}

	
	optionCount = count;
	optDiv.style.width = boxW + 10 +"px";
	optDiv.style.height = (LINE_HEIGHT*(ln+1))+"px";
	SAVE_DATA && handleDoneQuestions();
	setDropBoxWidth();
}

function getAns(obj){
	var cc = parseInt(obj.id.substr(2,1));
	for(var i=0;i<ansArrays[currentQ].length;i++){
		//console.log("ANSSS:  ", ansArrays[i]);		
		//var cc = obj.id.replace("op","");
		
		//console.log(cc," ****",ansArrays[currentQ][i], ansArrays[currentQ][i].indexOf(cc));
		if(ansArrays[currentQ][i].indexOf(cc) > -1)
		{
			//console.log("IIIDDD: ", obj, "dropbox"+i);
			return "dropBox"+i;
			
		}
	}
	
}

function setDropBoxWidth()
{
	var box;
	var prevPos = 50;
	var wd;
	
	for(var i=0;i<optionArr[currentQ].length;i++)
	{		
		//console.log(i,"BOXXXXX:  ", prevPos,optMaxWidth);		
		box = getElement("dropBox"+i);
		//console.log("BOX: ", box);
		wd = ((optMaxWidth + OPT_MARG)*2) + OPT1LEFT;
		//box.style.width = Math.max(210, wd) + "px";
		
		box.style.width = 200 + "px"; //change
		box.style.left = prevPos + "px";
		prevPos = parseInt(box.style.left) + parseInt(box.style.width) + BOX_MARG;
	}
	
	var tt = _rubricTxt.offsetTop + (_rubricTxt.offsetHeight) +(VERT_MARG*GRADE);	
	optDiv.style.top =tt+30  +"px";
	srialNo && (srialNo.style.top = tt+"px");	
	tt += optDiv.offsetHeight + (VERT_MARG*GRADE);
	//optDiv.style.top = tt+"px";	
}


function handleDoneQuestions()
{
	//console.log("Handle: ", storedData[currentQ]);
	var obj;
	var opStatus={'iid':'0','isDone':false, 'atts':0};
	var count=0;
	try{
		cData = storedData[currentQ];	
		//console.log(ALLOWED, "STATUS: ", storedData);
		for(var i=0;i<storedData[currentQ].length;i++)
		{
			//console.log("****: ", storedData[currentQ][i], storedData[currentQ][i].atts);
			obj = getElement("op"+i);
						
			if(cData[i].atts>=ALLOWED){
				makeCorrect(obj,false);		
				cData[i].iid = obj.opID;
				cData[i].isDone = true;	
				count++;
				obj.isDone = true;
			}
		}
		//console.log("/*/*/*/*: ", cData);
		if(count >= getElement(".draggable").length)
		{
			disableSolution();
			disableSubmitBTN();
		}
	}catch(err){
		//console.log("BLANK: ", err);
		cData=[];
		return;
	}
	
}


function myFun(opt,iid,count)
{
	//console.log("*****: ", opt);
	opt.classList.add("draggable");
	opt.classList.add("yes-drop");
	opt.setAttribute("id", "op"+iid);	
	opt.style.cursor = "pointer";
	addMarkup(opt);
	opt.ans = getAns(opt);
	optMaxWidth = Math.max(optMaxWidth, getWidthOf(opt.innerHTML,".option",quesfntSize));
	opt.opID = count;	
	//console.log(opt,opt.ans);
}

function addMarkup(obj){
	if(MARK && MARKC.length)
	obj.innerHTML = MARK+ obj.innerHTML + MARKC;
}

function removeMarkup(obj){

	var str = obj.innerHTML;
	str = str.replace(MARK,"");
	str = str.replace(MARKC, "");
	obj.innerHTML = str;
}


function resetOptPosition()
{
	var obj;
	for(var i=0;i<optionCount;i++)
	{
		obj = getElement("op"+i);
		//console.log("RESETING:  ", obj);
		if(!obj.classList.contains("option-right")){			
			//console.log("RESET: ",obj, obj.clicked, obj.isDone);	
			//obj.removeChild(obj.lastChild);
			optDiv.appendChild(obj);
			obj.clicked = false;
			enableOpt(obj);
			obj.classList.remove("option-wrong");
			
			//$(obj).animate({left:obj.xpos, top:obj.ypos},200);
			obj.style.left = obj.xpos + "px";
			obj.style.top = obj.ypos + "px";
		}
	}
	
}


function createDropBoxes()
{
	var marg;
	var boxW;
	var M_WIDTH = DROPBOX_W || parseInt(optDiv.style.width);
	//M_WIDTH = Math.max(M_WIDTH, (BOX_W*3.2));
	//M_WIDTH = Math.max(M_WIDTH, (BOX_W*ansArrays.length*1.05));
	//console.log("MWIDTH:  ", M_WIDTH, parseInt(optDiv.style.width));
	
	for(var i=0;i<ansArrays[currentQ].length;i++)
	{
		//console.log("HERE: -------------",i);
		var dropBox = createTag("div");
		dropBox.className = "dropBoxC";			
		dropBox.setAttribute("id", "dropBox"+i);
		dropBox.kids = 0; 
		dropBox.style.height = (LINE_HEIGHT * (MAX_CHILDREN/2)) +(10*(MAX_CHILDREN/2))+90 + 'px';
		boxW = (DROPZONE_M*2) + (OBJ_W*2);
		//console.log("HERE**************: ", boxW);		
		//dropBox.style.width = boxW+"px";
	
		//dropBox.addEventListener("click", onContainer);
		
		M_WIDTH = Math.max(M_WIDTH, (boxW*1.05*ansArrays[currentQ].length));		
		//marg = (parseInt(optDiv.style.width) - (BOX_W*ansArrays.length))/(ansArrays.length-1);
		marg = (M_WIDTH - (boxW*ansArrays.length))/(ansArrays[currentQ].length-1);
		//console.log("MARGGGGG:  ", marg,M_WIDTH);
		
		dropBox.style.left = parseInt(_rubricTxt.style.left) +(i*(boxW + BOX_MARG)) + "px";
		
		dropBox.style.top = dropBox_Top+"px";
		dropBox.classList.add("dropzone");
		
		var boxTitle = createTag("div");
		boxTitle.className = "boxTitleC";
		boxTitle.style.pointerEvents = "none";
		boxTitle.style.fontSize = quesfntSize + "px";
		//boxTitle.style.width =  BOX_W+ "px";
		//boxTitle.style.width = 
		boxTitle.style.height = BOX_TITLE_H + "px";
		boxTitle.innerHTML = optionArr[currentQ][i];
		//boxTitle.innerHTML = "Column " + (i+1);
		//optDiv.appendChild(dropBox);
		_main.appendChild(dropBox);
		dropBox.appendChild(boxTitle);					
	}
	
	return ansArrays[currentQ].length;
}


function onOpt(e){	
	
	//console.log("== ", e.target.parentNode.clicked,"       TAR:  ", e.target, "   CT:  ", e.currentTarget);
	//console.log("CLICKE.......DOWN..... ", e.currentTarget);
	var sel = e.target.clicked;
	var obj = e.target;
	var str = obj.innerHTML;
	selMC = e.target;
	for(var i=0;i<MIN_REQUIRED;i++)
	{
		//console.log(i,"-=-=-==-=-=", getElement("op"+i));
		getElement("op"+i).classList.remove("option-selected");
		getElement("op"+i).clicked = false;
	}
	
	obj.classList.add("option-selected");
	obj.clicked = true;
	removeMarkup(obj);
	selMC=obj;
	//!dropEnabled?enableContainer():console.log("111111111111111");
	
	if(e.target.parentNode.className.indexOf("dropBoxC") > -1)
	{
		//console.log("333");
		prevBox = e.target.parentNode;
	}else
	{
		//console.log("444");		
		prevBox=null;
	}
	
}


function cleanup(obj){
	var limit = obj.childNodes.length
	
	for(var j=1;j<limit;j++)
	{
		//console.log("cleaning: ",j, obj);
		obj.removeChild(obj.childNodes[1]);		
	}
}

function addNumbering(indx){
	
	var spn = createTag("span");
	spn.setAttribute("id", "sNum");
	spn.style.fontSize = quesfntSize + "px";
	srialNo.className = "serialNo";	
	
	_main.appendChild(srialNo);	
	srialNo.style.width = (quesfntSize*1.5)+"px";
	srialNo.style.display = "table";	
	//srialNo.style.height = (quesfntSize*1.3)+"px";
	srialNo.style.paddingTop = "0.2%";
	srialNo.style.paddingLeft = "0.2%";
	spn.innerHTML = (indx+1);  //change
	//spn.innerHTML = (indx+1)+"."; 
	srialNo.appendChild(spn);
	//srialNo.innerHTML = (indx+1)+".";
	srialNo.style.top = Q_BOX_TOP +100+ "px";
	srialNo.style.marginTop = +24+ "px";
	srialNo.style.left = Q_BOX_LEFT - (parseInt(srialNo.style.width) + 15) +5+ "px";	
	srialNo.style.height = srialNo.style.width;
	
}

function enableContainer()
{	
	var obj;
	cont = document.getElementsByClassName("dropBoxC");
	for(var i=0;i<cont.length;i++)
	{
		obj = cont[i];
		//console.log("ENA OBJ:  ", obj);
		obj.addEventListener("click", onContainer);		
		//obj.style.pointerEvents="auto";
		obj.style.cursor = "pointer";
	}
	dropEnabled=true;
	
}

function resetContainer()
{
	var obj;
	for(var i=0;i<optionArr[0].length;i++)
	{
		obj = getElement("tar"+i);
		//console.log("TAR.........",obj.isDone,i);
		if(!obj.isDone)
		{
			//console.log(obj+"SSSSS Reset");
			obj = getElement("tar"+i);
			obj.style.cursor = "auto";
			obj.style.color = colorObj.defaultText;
			obj.innerHTML="";
		}
	}
}



function disableCotainer()
{	
	var obj;
	cont = document.getElementsByClassName("dropBoxC");
	for(var i=0;i<cont.length;i++)
	{
		obj = cont[i];
		//console.log("DIS OBJ:  ", obj);
		obj.removeEventListener("click", onContainer);		
		//obj.style.pointerEvents ="none";
		obj.style.cursor = "default";
	}
	dropEnabled=false;
}

function enableOpt(obj)
{
	obj.style.cursor = "pointer";
	obj.style.pointerEvents = "auto";
	
}

function disableOpt(obj)
{
	obj.style.cursor = "default";
	obj.style.pointerEvents = "none";
	
}

function onContainer(e)
{
	//console.log("++  ",e.target, "=====");
	var tar = e.target;
	tar.onTarget=false;
	
	
	
	
	
	if(tar.childNodes.length>MAX_CHILDREN)
	{
		//console.log("=================: ",tar.childNodes, selMC);		
		sendBack(selMC);		
		return;
	}
	if(tar.className.indexOf("dropBoxC") == -1)
	{		
		//console.log("HERE:  ", e.target.className);		
		//getElement("stage").style.pointerEvents = "auto";
		//console.log("MAX FILLED:  ",e.target.parentNode, e.target.childNodes.length,getElement("stage").style.cursor);
		return;
	}
	
	var idd;
	var str="";
	var obj;
	
	if(prevBox)
	{	
		//console.log("case1111111111111111111111  PREV",selMC.parentNode.id);
		appendAtGlobal(tar,selMC,selMC.parentNode);
		
		refreshBox(tar);	
		selMC.clicked=false;		
		refreshBoxAnim(prevBox);
	}else
	{
		//console.log("case2222222222222222   NO PREV",);
		appendAtGlobal(tar,selMC,selMC.parentNode);		
		refreshBox(tar);
		selMC.clicked=false;
		e.target.kids++;
		
	}	
	//disableCotainer();
	checkSubmit();
		
}

function refreshBox(par)
{
	var max_h = 2;
	
	var lft;
	var rt;
	var off;
	var obj;
	var yOffset=1;
	var ypos = 1;
	var temp;
	var id;
	
	for(var i=1;i<par.childNodes.length;i++)
	{
		obj = par.childNodes[i];
		obj.style.transform = "none";
		obj.classList.remove("option-selected");
		temp = !(Boolean(i/2));
		temp = Number(temp);
		id = i
		id = (id%2)?id+1:id;
				
		//console.log(i, (i%2), Math.floor(i/2), temp);
		
		obj.style.top = pos[i-1].top + "px";
		obj.style.left = pos[i-1].left + "px";
		// nno changes
		obj.style.WebkitTransform = "none";
		/*
		temp = (i+1)%max_h;			
		lft = temp * (optMaxWidth+OPT_MARG)+OPT1LEFT;
		
		ypos = (par.offsetHeight - ypos - obj.offsetHeight) * (2%i);
		
		//console.log("//////////: ",  par.offsetHeight, obj.offsetHeight);
		off = par.offsetHeight - (obj.offsetHeight*yOffset);//par.offsetHeight - (obj.offsetHeight*yOffset);
		
		rt = off - (15*yOffset);		
		
		
		obj.style.left = lft + "px";
		obj.style.top= rt + "px";
		
		(((i+1)%max_h)==0)?yOffset++:yOffset;
		console.log("LEFT: ", lft);				
		*/
	}
	//disableCotainer();
	//console.log("OFF:  ");
}


function refreshBoxAnim(par)
{
	var max_h = 2;
	
	var lft;
	var rt;
	var off;
	var obj;
	var yOffset=1;
	var ypos = 1;
	var temp;
	var id;
	
	for(var i=1;i<par.childNodes.length;i++)
	{
		obj = par.childNodes[i];
		obj.style.transform = "none";
		obj.classList.remove("option-selected");
		temp = !(Boolean(i/2));
		temp = Number(temp);
		id = i
		id = (id%2)?id+1:id;
				
		//console.log(i, (i%2), Math.floor(i/2), temp);
		
		obj.style.top = pos[i-1].top + "px";
		obj.style.left = pos[i-1].left + "px";
		/*
		temp = (i+1)%max_h;
		lft = temp * (optMaxWidth+OPT_MARG)+OPT1LEFT;
		off = par.offsetHeight - (obj.offsetHeight*yOffset);
		rt = off - (7*yOffset);		
		$(obj).animate({left:lft,top:rt,opacity:1},400);
		
		(((i+1)%max_h)==0)?yOffset++:yOffset;		
		*/
		//console.log("#######: ",obj,obj.style.left, obj.style.top);
	}
}

function refreshBoxOnly(par)
{
	var max_h = 1;
	
	var lft;
	var rt;
	var off;
	var obj;
	var yOffset=1;
	var temp;
	//console.log("ANIMATE: ", par);
	for(var i=1;i<par.childNodes.length;i++)
	{
		obj = par.childNodes[i];
		obj.style.top = pos[i-1].top + "px";
		obj.style.left = pos[i-1].left + "px";
		
		/*temp = (i+1)%max_h;
		lft = temp * (optMaxWidth+OPT_MARG)+OPT1LEFT;
		off = par.offsetHeight - (obj.offsetHeight*yOffset);
		rt = off - (7*yOffset);		
		$(obj).css({left:lft,top:rt,opacity:1});
		
		(((i+1)%max_h)==0)?yOffset++:yOffset;		*/
		//console.log("#######: ",obj);
	}
}




function checkSubmit()
{
	//console.log("Options:  ", optionCount);
	//console.log("FILLED:  ", filledCount);
	var flag = false;
	var box;
	var kid;

	for(var i=0;i<ansArrays[currentQ].length;i++){
		box = getElement("#dropBox"+i);
		//console.log("BOX....: ", box, box.children.length);
			for(var j=1; j<box.children.length;j++)
			{
				kid = box.children[j];
				//console.log("TTTTTTTTT", kid);
				if(!kid.isDone){
					//console.log("TRUE: ", kid);
					flag = true;
					break;
				}
				
			}
			if(flag)
				break;
		}	
	if(flag){
		enableSubmitBTN();
	}else{
		disableSubmitBTN();
	}	
			
}

function onSubmitClick1(e){
	var obj;
	opArr = getElement(".option");	
	for(var i=0;i<opArr.length;i++){
		obj = opArr[i];
		//console.log("OB: ", obj.clicked);
		if(obj.clicked && obj.ans){
			//console.log("CHECK: ", obj, obj.parentNode);
		}
		
	}
	
}

function onSubmitClick(e){
	//console.log("111111***: ",(cData));
	var obj;
	var opt;
	var wCount=0;
	var tempR=0;
	var box;
	var fImage;
	//setOptPosition();
	//return;
	var TansArr=[];
	var tAns=[];
	filledCount=0;
	var opStatus={'iid':'0','isDone':false, 'atts':0};
	var oAtts=0;
	var count=0;
	disableSubmitBTN();
	disableSolution();
	disableObj(getElement("prev"));
	disableObj(getElement("next"));
	toggleOptions(false);
	
	
	for(var i=0;i<ansArrays[currentQ].length;i++)
	{
		box = getElement("dropBox"+i);		
		//console.log("11111111:  ",TansArr);
		for(var j=1;j<box.childNodes.length;j++)
		{
			//console.log("222222:  ",box.childNodes[j]);
			opStatus={'iid':'0','isDone':false, 'atts':0};
			oAtts = parseInt(box.childNodes[j].atts);
			opStatus.iid = box.childNodes[j].opID;	
			//console.log("OBJ DONE: ", box.childNodes[j].isDone);
			if(box.childNodes[j].isDone){
				//console.log("Already done: ",box.childNodes[j]);
				tempR++; 
			
				continue;
			}
			
			if(ansArrays[currentQ][i].indexOf(box.childNodes[j].opID) == -1)
			{
				box.childNodes[j].classList.add("option-wrong");				
				disableOpt(box.childNodes[j]);
				wCount++;				
				box.childNodes[j].atts = parseInt(box.childNodes[j].atts)+1;
				box.childNodes[j].atts = oAtts+1;
				opStatus.atts = oAtts+1;
				opStatus.isDone = false;

				cData.push(opStatus);

			}else{
				box.childNodes[j].classList.add("option-right");
				box.childNodes[j].classList.remove("draggable");
				tempR++;
				console.log(tempR, " ***********-----------------");
				finalScore++;
				scoreDisp.innerHTML = finalScore + "/" + finalmarks;
				let status = SCO.get("cmi.core.lesson_status");
				if (status !== "completed") {
					SCO.set("cmi.core.score.raw", finalScore);
					SCO.save()
				}
				box.childNodes[j].isDone = true;
				disableOpt(box.childNodes[j]);
				
				box.childNodes[j].atts = ALLOWED;
				opStatus.atts = ALLOWED;
				opStatus.isDone = true;
				cData.push(opStatus);
			}
			
			//console.log("OP: ",(cData));
		}
		
		//cData.push(tAns);
		
		TansArr[i] = tAns;
		tAns=[];		
	}
	//console.log("@@@@@@@@@@@:  ", tempR);
	rCount = tempR;	
	//console.log("final ans:  ", rCount, tempR);
	
	//tempR += rCount;
	//rCount + tempR;
	if(wCount)
	{
		if(++attempts<ALLOWED && tempR)
		{
			//console.log("-----------------",optionCount, wCount, tempR);
			if(tempR <= wCount || (tempR+wCount) !=optionCount){			
				playWrongFeedback(tempR, postWrong);
			}else{
				playRemainingWrongFeedback(optionCount - tempR, postWrong);
			}
		}else{
			playFeedback("wrong", postWrong);
		}
		
		//feedbackVid.playWrongFeedback();
		feedbackAnim.gotoAndPlay("wrong");
		//setTimeout(postSubmit, drawIncorrectQuestionDelay);		
		//cData.attempt = attempts;		
	}else
	{
		//feedbackVid.playCorrectFeedback();
		feedbackAnim.gotoAndPlay("right");
		//setTimeout(postSubmit, drawNextQuestionDelay);
		//cData.allDone = true;
		//console.log("RIGHT........");
		playFeedback("right", postRight);
		//cData.isDone = true;
	}
	
	//cData.attempts = attempts;
	storedData[currentQ] = cData;
	filledCount = 0;		
	SAVE_ANS && saveAnswers(cData);
	//console.log("SAVED: ", storedData);
	//console.log("TOTAL Correct Ans:  ", correctCount);	
} 

function toggleOptions(activate){
	var obj;
	var evt = "none";
	if(activate){
		evt = "auto";
	}
	var opts = getElement(".draggable");
	for(var i=0;i<opts.length;i++){
		obj = opts[i];
		obj.style.pointerEvents = evt;
	}
	
}


function postRight()
{	
	feedbackAnim.gotoAndStop("ideal");
	
	//console.log("POST RIGHT==========",rCount,optionCount);
	if(rCount >= optionCount){
		//questionDone++;
		//console.log("Correct222222:  ", questionDone);
		
		allDone[currentQ] = true;
	}else{
		//console.log("ELSE........");
		toggleOptions(true);
		enableSolution();
		checkNextPrev()
		return;		
	}
	
	if(questionDone >= questionArr.length)
	{
		//console.log("Correct3333333:  ", questionDone);
		disableObj(getElement("#prev"));
		disableObj(getElement("#next"));
		finishActivity();
	}else
	{		
		checkNextQ();
		
	}
	
}

function postWrong(){	
	feedbackAnim.gotoAndStop("ideal");
	
	toggleOptions(true);
	//console.log("================ POST ========", correctCount,rCount);	
	var play=false;			
	//console.("case3",wCount, rCount);
	if(attempts >= ALLOWED)
	{
		showCorrectAns();
	
	}else
	{
		checkNextPrev();	
		enableSolution();
	resetOptPosition();
	}
	/*
	for(var i=0;i<ansArrays[currentQ].length;i++)
	{		
		refreshBoxAnim(getElement("dropBox"+i));
	}*/
}



function showCorrectAns()
{
	var obj;
	var tar;
	var ansID;	
	var count=0;
	//console.log(cData, " cData ^^^^^^^^^^^^^^^");
	//var arr={};
	resetOptPosition();
	var opStatus={'iid':'0','isDone':false, 'atts':0};
	var tArr=[];
	filledCount=0;
	//console.log(ALLOWED, "STATUS: ", cData);
	var isPlaying = false;
	for(var i=0;i<optionCount;i++)
	{
		obj = getElement("op"+i);
		//console.log("SHOW OBJ:  ", obj, obj.atts);
		opStatus={'iid':'0','isDone':false, 'atts':0};
		if(obj.isDone){			
			//console.log("=====---------");
			continue;
		}
		if(obj.childNodes.length >=2){
			//console.log("CHILD: ", (obj.lastChild));
			obj.removeChild(obj.lastChild);
		}
		//console.log("SH: ", (parseInt(obj.atts)), ALLOWED);
		
		if((parseInt(obj.atts))>=ALLOWED){		
			makeCorrect(obj,true);					
			opStatus.iid = obj.opID;
			opStatus.isDone = true;
			opStatus.atts = ALLOWED;
			count++;			
			//arr[i]= parseInt(obj.atts);			
			cData.push(opStatus);	
			isPlaying =true;		
		}
		
	}	
	//resetOptPosition();
	//console.log("SHOEWeee: ", (rCount+count) , optionCount);	
	for(var j=0;j<ansArrays[currentQ].length;j++)
	{
		console.log("SETTING:  ", j)
		refreshBoxAnim(getElement("dropBox"+j));
	}
	
	if((rCount+count) >= optionCount){		
		if(isPlaying){
			//questionDone++;
			SAVE_ANS && saveAnswers(cData);
			playFeedback("correct",checkNextQ);
			console.log("Correct:  ", questionDone);
		}
	}else{
		if(isPlaying){
			playFeedback("correct", resetOpt);
		}
	}
	
	//var aArr = ansArrays[currentQ];
	
	//cData.ans = aArr;
	//cData.attempts = ATTEMPTS_ALLOWED;
	//cData.isDone = true;
	storedData[currentQ] = cData;
	SAVE_ANS && saveAnswers(cData);
	//console.log("Now Saved: ", storedData);
	
}

function makeCorrect(_obj, animate){
	
	

	var str = _obj.innerHTML
	_obj.classList.remove("option-wrong");
	_obj.classList.add("option-right");
	_obj.classList.remove("draggable");
	ansID = getAnsID(_obj.opID);
	tar = getElement("dropBox"+ansID);
	_obj.setAttribute('data-x',0);
	_obj.setAttribute('data-y',0);
	appendAt("main", _obj);				
	removeMarkup(_obj);
		
	_obj.style.left = 0+"px";
	_obj.style.top = 0+"px";
	//console.log("APPENDING:  ", i , obj,obj.parentNode, obj.xpos, obj.ypos);			
	//wait(5000);
	//tar.appendChild(_obj);
	//console.log("APPEND: ", _obj, animate);
	appendAtGlobal(tar,_obj, _obj.parentNode);			
	if(animate){
		refreshBoxAnim(tar);
	}else{
		refreshBoxOnly(tar);
	}
	_obj.style.pointerEvents = "none";
}


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


/* function checkNextQ()
{
	
	
	if(questionDone >= questionArr.length)
	{
		//console.log("CCCCCCCCCCCCCCC", questionDone);
		disableSolution();			
		
		finishActivity();
	}
	
	if(currentQ>=questionArr.length-1){
		//console.log("TTTTTTTTTT");
		setTimeout(enableObj,drawNextQuestionDelay,getElement("#prev"));		
	}else{		
		//cleanAll();
		currentQ++;
		
		setTimeout(function (){
			cleanAll();
			arrangeOptions();
			
		}, drawNextQuestionDelay);
		
	}
	
} */


function checkNextQ()
{
	//console.log("goint next:  ", currentQ, quesArr.length);
	questionDone++;
	// let status = SCO.get("cmi.core.lesson_status");
	// if (status !== "completed") {
	// 	SCO.set("cmi.suspend_data", JSON.stringify(filteredData) + "*" +attempts+"*"+questionDone);
	// 	SCO.save();
	// }
	if(questionDone == questionArr.length)
	{
		disableSolution();			
		finishActivity();
	}
	
	if(currentQ>=questionArr.length-1){
		//console.log("TTTTTTTTTT");
		setTimeout(enableObj,drawNextQuestionDelay,getElement("#prev"));		
	}else{		
		//cleanAll();
		currentQ++;
		
		setTimeout(function (){
			cleanAll();
			arrangeOptions();
			
		}, drawNextQuestionDelay);
		
	}
}



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

	/* const uniqueData = cData.filter((obj, index, self) => {
	console.log(obj, index, self);
    index === self.findIndex((t) => (
    t.iid === obj.iid 
    ))}); */
	
	
cData.forEach(obj => {
    if (!uniqueObjects[obj.iid] || obj.isDone) {
        uniqueObjects[obj.iid] = obj;
    }
});
console.log("uniques: ", uniqueObjects);
 filteredData = uniqueObjects.filter(item => item !== null);
console.log(filteredData);

// const resultArray = Object.values(uniqueObjects).filter(obj => obj.isDone);
// console.log(resultArray);
//console.log(uniqueData);





// storedData=filteredData
// storedData[currentQ] = filteredData;
// console.log(storedData[currentQ]);
// console.log(storedData);

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

function cleanAll()
{	
	
	//console.log("start cleaninbg................");
	try{
		var optD = getElement("optDv");
		
		while(optD.hasChildNodes())
		{
			optD.removeChild(optD.lastChild);
		}
	}catch(er){
		//console.log("OPTDIV: ", er)
	}
	
	try{
		//console.log("BOXes...");
		cleanBoxes();
	}catch(err){
		//console.log("CLEANING ERR: ",err);
	}
	//console.log("======: LIMIT: ", limit);
	
	
}

function cleanBoxes(){
	var limit = ansArrays[currentQ].length;
	
	for(var ii=0;ii<limit;ii++)
	{	
		//console.log(ii,"GO clean:  ", 	getElement("dropBox"+ii));	
		cleanup(getElement("dropBox"+ii));		
		//console.log("+++++++++++: ", ii);
		getElement("dropBox"+ii).parentNode.removeChild(getElement("dropBox"+ii))
	}
	
}




function getAnsID(id)
{
	for(var i=0;i<ansArrays[currentQ].length;i++)
	{
		if(ansArrays[currentQ][i].indexOf(id) != -1)
		{
			return i;
		}
		
	}
	
}


function onSolution()
{

	disableSolution();
	disableSubmitBTN();
	disableObj(getElement("prev"));
	disableObj(getElement("next"));
	
	for(var i=0; i<optionCount;i++)
	{
		//console.log("SOL:  ", getElement("op"+i));
		disableOpt(getElement("op"+i));
		getElement("op"+i).atts = ALLOWED;
		
	}
	//console.log("TRRRRRRRRRRRRRR.........");
	showCorrectAns();
	//finishActivity();
}

//=====================================NITYA============================================================================

function setPositionOfDragable(dropzone, dragable){
	var lft;
	var top;
	dragable.style.zIndex = "10";
	
	console.log(dropzone.isDone," dropzone.isDone")
	if(dropzone.guest && dropzone.isDone == false){
		_main.appendChild(dropzone.guest);
		dropzone.guest.style.left = dropzone.guest.xx;
		dropzone.guest.style.top = dropzone.guest.yy;
		dropzone.guest.removeAttribute("data-x");
		dropzone.guest.removeAttribute("data-y");
		dropzone.guest.style.transform = "none";
		//console.log("guest: ++++++++++++++++",dropzone.guest.id);
		dropzone.guest.owner = null;
		dropzone.guest = null;
	}
	
	if(dropZoneAct != null  && dropzone.isDone == false){
		lft = (dropzone.offsetWidth/2)-(dragable.offsetWidth/2);
		top = (dropzone.offsetHeight/2-dragable.offsetHeight/2);
		
		dropzone.appendChild(dragable);
		dragable.style.left = lft+"px";
		dragable.style.top = top+"px";
		dragable.removeAttribute("data-x");
		dragable.removeAttribute("data-y");
		dragable.style.transform = "none";
		
		dragable.owner = dropzone;
		dropzone.guest = dragable;
		dropZoneAct = null;
		//console.log(dropzone.id," -11111111111111111111- ",dropzone.guest.id)
	}
	
	
	/*for(var i=0; i<numDropzone+1; i++){
		if(document.getElementById("dropZone"+i).childNodes.length > 0){
			console.log("333333333333")
			enableBTN();
		}else{
			disableBTN();
			answerBtn.style.pointerEvents = "auto";
			answerBtn.style.opacity = 1;
			break;
		}
	}*/
	
}




//===================================================INTERACT======================================================================


interact('.draggable').draggable({
    // enable inertial throwing
    inertia: false,
    // keep the element within the area of it's parent
    restrict: {
		restriction: "#main",
		endOnly: false,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    },
    // enable autoScroll
    autoScroll: true,

    // call this function on every dragmove event
    onmove: dragMoveListener,
    // call this function on every dragend event
   
	onstart: function (event)
	{
		//console.log("START-------------", event.target);
		
		event.target.removeAttribute("data-x");
		event.target.removeAttribute("data-y");
		event.target.style.transform = "none";
		onOpt(event);
	}, 
	
	onend: function (event)
	{
		event.target.removeAttribute("data-x");
		event.target.removeAttribute("data-y");
		if(!event.target.onTarget){
			sendBack(event.target);
		}
		
	}
  });
  
function sendBack(obj)
{
	
	var id;
		var boo=false;

		//console.log("ENDDDDD:  TIME TO SEND BACK", obj.onTarget);
		//boo = appendAtGlobal(getElement("main"), obj, obj.parentNode);
		boo = appendAtGlobal(optDiv, obj, obj.parentNode);
		obj.setAttribute('data-x', 0);
		obj.setAttribute('data-y', 0);
		obj.style.transform = "none";
		obj.classList.remove("option-selected");
		id = (obj.id);
		
		// nno changes
		obj.style.WebkitTransform = "none";
		
		$("#"+ id).animate({left:obj.xpos, top:obj.ypos},200,function (){			
			addMarkup(obj);
			});					
		//console.log("On eND-----------");
		filledCount--;
		checkSubmit();
		boo && refreshBoxAnim(getElement(boo));;
		
} 
 
  

function dragMoveListener (event) {
	event.target.style.transform = "none";
	//console.log("******* dragMoveListener ******", event.target);
    var target = event.target,
        // keep the dragged position in the data-x/data-y attributes
        x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
        y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
		
//console.log(target.getAttribute('data-x'),"-----",target.getAttribute('data-y'));
    // translate the element
    target.style.webkitTransform =
    target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';
	  
    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
	
	target.style.zIndex = "200";
  }

  // this is used later in the resizing and gesture demos
  window.dragMoveListener = dragMoveListener;
  
interact('.dropzone').dropzone({
  // only accept elements matching this CSS selector
  accept: '.yes-drop',
  // Require a 75% element overlap for a drop to be possible
  overlap: 0.25,

  // listen for drop related events:

  ondropactivate: function (event) {
	//console.log("******* ondropactivate ******",event.target);
    // add active dropzone feedback
    event.target.classList.add('drop-active');
  },
  
  ondragenter: function (event) {
	 
    var draggableElement = event.relatedTarget,
        dropzoneElement = event.target;
	draggableElement.onTarget = true;
	//console.log("******* ondragenter ******",draggableElement.onTarget); 
    // feedback the possibility of a drop
	//dropzoneElement.classList.add('drop-target');
    draggableElement.classList.add('can-drop');
    //draggableElement.textContent = 'Dragged in';
  },
  
  ondragleave: function (event) {
    //remove the drop feedback style
	
	event.relatedTarget.onTarget = false;
	//console.log("******* ondragleave ******", onTarget);
	if(event.relatedTarget.owner){
		event.relatedTarget.owner = null;
		event.target.guest = null;
	}
	//console.log(event.target.id,"*******************")
	
    event.target.classList.remove('drop-target');
    event.relatedTarget.classList.remove('can-drop');
    //event.relatedTarget.textContent = 'Dragged out';
  },
  
  ondrop: function (event) {
    //event.relatedTarget.innerHTML = 'Dropped';
	
	
	//dropZoneAct = event.target;
	console.log("onDrop: @@@@@@@@@@@@@@@@@@@@@@@",onTarget,"--", event.target);
	// let numberofDrop=[]
	// numberofDrop.push(onTarget)
	// console.log(numberofDrop);
	onContainer(event);
	//setPositionOfDragable(event.target, event.relatedTarget);
  },
  
  ondropdeactivate: function (event) {
    // remove active dropzone feedback
	console.log("******* ondropdeactivate ******",event.target);
    event.target.classList.remove('drop-active');
    event.target.classList.remove('drop-target');
	
	//onContainer(event.target);
  }
  
});



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