/*  
/  @author Nityanand Ojha
*/

var grade = 1;

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: "#99ffff" };
var storageArr = [];
var tempAttempt = 0;
var _main;
var _rubricTxt;
var _quesTxt;
var srialNo;
var option;
var audio;
var animDiv;
var count = 1;
var interval;
var submitBtn;
var answerBtn;
var checkSol;

var qNo = 0;
var optionBackground;
var dropZoneAct = null;
var allDone = [];
var numDropzone = 0;

var introDelay = 1000;
var introVid;
var sourceOGG = ""
var sourceMP3 = ""
var sourceWEBM = ""
var sourceMP4 = ""

//////// G for grammer, V for vocabulary..........
var introType = "";
var scoreDisp;
var finalScore = 0;
var Status;
var introVid;
var SCO;
startIntro()

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

    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";
            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;
            titleText.style.width = "712px";
            titleText.style.top = "400px";
            titleText.style.left = "205px";
            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:
            //feedbackVid.init();
            feedbackAnim()
            introVid.removeEventListener("ended", onEnd);
            $(titleText).animate({ opacity: 0 }, 1);
            $(introVid).animate({ opacity: 0 }, 1, dragAndDrop);
            document.getElementById("main").style.backgroundImage = "url('../__images/image/" + spriteOBJ.background + "')";
            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() {
    _main = getElement("main");

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

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

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

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


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

function 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 = document.getElementById("submitBtn");
    checkSol = createTag("div");
    checkSol.setAttribute("id", "checkSolution");
    _main.appendChild(checkSol);

    answerBtn = createTag("div");
    answerBtn.setAttribute("id", "answer");
    answerBtn.innerHTML = "ANSWER";
    checkSol.appendChild(answerBtn);





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




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


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

    answerBtn.addEventListener("click", onSolutionClick);

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

    _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");
    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;
    document.body.appendChild(_rubricTxt);
    _rubricTxt.style.position = "absolute";

    _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, 1150) + "px";

    soundComplete();

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

function resetActivity(e) {

    finalScore = 0;
    scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
    // e.target.removeEventListener("click", resetActivity);
    // e.target.classList.add("inactive");

    resetDragables();
    removePreviousOnpre();
	addQuestion(qNo);
    enableObj(getElement("nextBtn"));
    // addQuestion(--qNo);
    // addQuestion(0);
    allDone = [];
    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: [] });
    }
    ResetBtn.style.pointerEvents = "none";
    ResetBtn.style.opacity = 0.5;
}
function addScorm() {
    /* rajji.style.visibility = "visible";
    rajji.addEventListener("click", resetActivity); */
    // try{
    // 	if(SCO.connection.isActive){
    // 		return
    // 	}
    // }catch(err){
    // 	console.log("SCO ERROR: ", err);
    // }
    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)
    }

    if (status !== "completed") {
        finalScore = SCO.get("cmi.core.score.raw") || 0;
        finalScore = parseInt(finalScore);
        scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
        console.log("FINAL : ", finalScore);
        if (storageArr.length == finalScore) {
            SCO.set("cmi.core.lesson_status ", "passed");
        }
    } else {
        finalScore = SCO.get("cmi.core.score.raw") || 0;
        finalScore = parseInt(finalScore);
        scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
        // console.log("visible",rajji,ResetBtn);
        ResetBtn.style.visibility = "visible";
        ResetBtn.addEventListener("click", resetActivity);

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

    if (lmsData.length) {
        storageArr = JSON.parse(lmsData) || storageArr;
        console.log(storageArr);
        // handlingDoneQues();
        // try {
        // 	handlingDoneQues();
        // } catch (err) {
        // 	console.log("ERR: ", err);
        // }

    }
    saveData();
    console.log("DATA: ", lmsData);
}
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.play();
    audio.addEventListener("ended", rubComplete);
}


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

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/5";
    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 = 622 + "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) {
            console.log(qNo, " dddddddddddddddddddd ", 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();
    if (data.optionArr.length > 1) {
        addNumbering(indx);
    }

    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.id = "op" + i;
        option.owner = null;
        option.isDone = false;
        option.wCount = 0;
        //option.style.border = '1px solid red'

        option.style.cursor = "pointer";
        option.style.height = 46 + "px";
        //		option.style.lineHeight = 46+"px";

        option.classList.add("draggable");
        option.classList.add("yes-drop")

        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 arrangeSentence() {
    var drpZoneCnt = -1;
    var drpnum;
    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 = tempH + "px";
                opt.setAttribute("id", ("dropZone" + drpZoneCnt));
                opt.classList.add("dropzone");
                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) + (n * (indentation / 2)) + 15 + "px";

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

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

    }

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

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

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

}

function addNumbering(indx) {
    srialNo.style.position = "absolute";
    srialNo.innerHTML = (indx + 1);
    srialNo.style.fontSize = quesfntSize + "px";
    srialNo.style.fontFamily = fontFace1;
    optDiv.appendChild(srialNo);
    srialNo.style.border = "3px solid #F29B34";
    srialNo.style.width = quesfntSize + 5 + "px";
    srialNo.style.borderRadius = "50%";

    //srialNo.style.top = optDv.offsetTop+"px";
    srialNo.style.left = -(srialNo.offsetWidth + 15) + "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 = 100 + "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 = 100 + "px";

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

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

    var chkAns = new checkAnswer(qNo);

    if (chkAns.done()) {
        console.log("correct")
        storageArr[qNo].quesDone = "true";
        setTimeout(addNextQuestion, 4000);
        finalScore++;
        scoreDisp.innerHTML = finalScore + "/" + storageArr.length;
        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);

        }
    } 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);
        if(storageArr[qNo].attempt >= attempt){
			storageArr[qNo].quesDone = "true";
		}
    }

    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 - 1 == 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");
    }
    let tempInc = 0;

    for (var i = 0; i < storageArr.length; i++) {
        if(storageArr[i].ans.length === 1){
           tempInc++; 
        }

        console.log(tempInc);

        if(tempInc === storageArr.length){
            console.log("rajji");
           SCO.set("cmi.core.lesson_status", "completed");
			SCO.save(); 
        }
    }
    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 = [];

    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++;
                    } 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++;
        }
    }

    //console.log(storageArr[indx].drpZoneAttempt," storageArr[indx].attempt");	
    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;
    }
    saveData()
    // let tempInc=0
	// for (var i = 0; i < storageArr.length; i++) {
    //     if(storageArr[i].quesDone== "true"){
    //        tempInc++; 
    //     }

    //     console.log(tempInc);

    //     if(tempInc === storageArr.length){
    //         SCO.set("cmi.core.lesson_status", "completed");
	// 		SCO.save();           
    //     }
	// }
}

function addNextQuestion() {
 
    disableObj(nextBtn);
    enableObj(getElement("preBtn"));

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


    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 getDragablePos(indx, obj) {
    var iid = obj.id;
    var cnt = 0;

    for (var i = 0; i < data.quesArr[indx].length; i++) {
        for (var j = 0; j < data.quesArr[indx][i].ans.length; j++) {
            if (data.quesArr[indx][i].ans[j] == iid) {
                return document.getElementById("dropZone" + cnt);
            }
            cnt++;
        }
    }
}

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

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

    }

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

    }

}

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";
            cDragable.style.pointerEvents = "none";
            setColor(cDragable, "#009900");

            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;
        // nno changes
        cDragable.style.position = "absolute";
        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 ........");
    dropZoneAct = null;

    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() {
     dropZoneAct = null;
    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.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;
            }
            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 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)
        getOp.style.pointerEvents = "auto";
    }
}

function playAnimation() {
    if (count < 72) {
        count++;
        animDiv.src = "Assets/activityComplete/actComp_" + count + ".png";
    } else {
        clearInterval(interval);
    }
}

function checkAllDone() {
    var _d = true;

    for (var i = 0; i < data.quesArr.length; i++) {
        if (storageArr[i].quesDone == "false") {
            _d = false;
            break;
        }
    }

    return _d;
}

function makeAnimationSpace() {
    // if( SCO.get("cmi.core.lesson_status") == "complete"){
    //     return;
    // }
console.log("rajji2");
    if (qNo) {
        enableObj(preBtn);
    }

    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);
    // setTimeout(function () {
    //     completedDelay();
    //     // Set SCORM status to "completed" here
    //     if (typeof SCO !== 'undefined') {
    //         SCO.set("cmi.core.lesson_status", "completed");
    //         SCO.save();
    //     }
    // }, 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*********==============================//

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
    onend: function (event) {
        /* var textEl = event.target.querySelector('p');
	
      textEl && (textEl.textContent =
        'moved a distance of '
        + (Math.sqrt(event.dx * event.dx +
                     event.dy * event.dy)|0) + 'px');*/
    }
});

function dragMoveListener(event) {
    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) {
        // add active dropzone feedback
        if (event.target.isDone == false) {
            event.target.classList.add('drop-active');
        }
    },

    ondragenter: function (event) {
        var draggableElement = event.relatedTarget,
            dropzoneElement = event.target;

        if (event.target.isDone == false) {
            dropzoneElement.classList.add('drop-target');
        }
        draggableElement.classList.add('can-drop');
        //draggableElement.textContent = 'Dragged in';
    },

    ondragleave: function (event) {
        //remove the drop feedback style

        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';
        console.log("onDrop: @@@@@@@@@@@@@@@@@@@@@@@")

        dropZoneAct = event.target;
        setPositionOfDragable(event.target, event.relatedTarget);
    },

    ondropdeactivate: function (event) {
        // remove active dropzone feedback
        event.target.classList.remove('drop-active');
        event.target.classList.remove('drop-target');

        sendToBack(event.relatedTarget, event.target);
    }

});

function sendToBack(dragable, dropzone) {

    if (dragable.owner == null) {
        _main.appendChild(dragable);
        dragable.style.left = dragable.xx;
        dragable.style.top = dragable.yy;
        dragable.removeAttribute("data-x");
        dragable.removeAttribute("data-y");
        dragable.style.transform = "none";

        // nno changes
        dragable.style.position = "absolute";
        dragable.style.WebkitTransform = "none";
        dropZoneAct = null;
    }

    for (var i = 0; i < numDropzone + 1; i++) {

        if (document.getElementById("dropZone" + i).childNodes.length > 0) {
            if (document.getElementById("dropZone" + i).isDone == false) {
                enableBTN();
                break;
            }
        } else {
            //console.log(dropzone.wCount," 44444444444444 ",dropzone.id)
            console.log("44444444444444")
            disableBTN();
            answerBtn.style.pointerEvents = "auto";
            answerBtn.style.opacity = 1;

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

            if (qNo) {
                enableObj(preBtn);
            }

        }
    }

}

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);
        // nno changes
        dropzone.guest.style.position = 'absolute';
        dropzone.guest.owner = null;
        dropzone.guest = null;
    }

    if (dropZoneAct != null && dropzone.isDone == false) {
        // nno changes		
        console.log("guest: 2@@@@+");
        dragable.removeAttribute("data-x");
        dragable.removeAttribute("data-y");
        dragable.style.transform = "none";
        dragable.style.WebkitTransform = "none";
        dragable.style.removeProperty("position");
        dragable.style.removeProperty("left");
        dragable.style.removeProperty("top");
        dropzone.appendChild(dragable);

        dragable.owner = dropzone;
        dropzone.guest = dragable;
        dropZoneAct = null;
    }


    for (var i = 0; i < numDropzone + 1; i++) {
        if (document.getElementById("dropZone" + i).childNodes.length > 0) {
            console.log("333333333333")
            if (document.getElementById("dropZone" + i).isDone == false) {
                enableBTN();
            }
            break;
        } else {
            disableBTN();
            answerBtn.style.pointerEvents = "auto";
            answerBtn.style.opacity = 1;
        }
    }

}

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();
    //audio.addEventListener("ended", soundCompleteAfterfeedback);
}

function soundCompleteAfterfeedback(e) {
    //answerBtn.style.pointerEvents = "auto";
    //answerBtn.style.opacity = 1;
    //audio.removeEventListener("ended", soundCompleteAfterfeedback);
}

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


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

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

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