// 12th may 2025
var JumbleTumble = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = "",
    level = 1,
    label = "";
var firstAttempt = true,
    finalMarks = 0;
var totalJsonQueCount, wordType = "sentence",
    ansWord;
JumbleTumble.isPracticeFlag = false;
JumbleTumble.scoreFlag = false;
JumbleTumble.soundFlag = false;
JumbleTumble.helpFlag = false;
JumbleTumble.helpTakenFlag = false;

JumbleTumble.init = function () {
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
        Utils.mobileDeviceFlag = true;
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/" + JumbleTumble.hardCodedData.cover_page + ")";
    $("#coverPage").show();
    $("#gamePage").hide();
    $("#endPage").hide();
    //$("#home").show();
    totalJsonQueCount = JumbleTumble.wordData.length;
    JumbleTumble.setVariables();
    JumbleTumble.setImages();
    JumbleTumble.createAcknowledgementDivs();
    if (Utils.mobileDeviceFlag) {
        JumbleTumble.isPracticeFlag = Android.isPractice();
    }
    if (JumbleTumble.isPracticeFlag) {
        $("#help").css("visibility", "hidden");
    } else {
        $("#help").css("visibility", "visible");
    }
setFontFamilyForLang("fonts/NotoSansKannada-Regular.ttf");

}

setFontFamilyForLang = function (fontFilePath) {
	var newStyle = "<style>" +
		"@font-face { " +
		"font-family: 'CustomFontFamily';" +
		"src: url('" + fontFilePath + "') format('truetype');" +
		"} </style>";
	$("head").append(newStyle);
	$("body").css("font-family", "CustomFontFamily");
}
// global variables
JumbleTumble.setVariables = function () {
    JumbleTumble.questionIndex;
    JumbleTumble.textStringArray;
    JumbleTumble.attemptCtr = 0;
    JumbleTumble.questionCtr = 0;
}

//set all images
JumbleTumble.setImages = function () {
    var str = "images/leaf2.png";
    document.getElementById("home").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("nextBtn").src = Utils.Path + "images/skin/Next.png";
    document.getElementById("helpBtn").src = Utils.Path + "images/skin/Help.png";
    document.getElementById("logo").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("playImage").src = Utils.Path + "images/skin/Play.png";
    document.getElementById("checkAns").src = Utils.Path + "images/skin/Done.png";
    document.getElementById("replayImg").src = Utils.Path + "images/skin/playAgain.png";
    document.getElementById("creditImg").src = Utils.Path + "images/skin/credit.png";
    document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy.png";
    document.getElementById("soundBtn").src = Utils.Path + "images/skin/Sound.png";
    document.getElementById("gameOver").innerHTML = JumbleTumble.hardCodedData.gameOver;
    document.getElementById("bottomDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/Unit-for-buttons.png";
}

//start game
JumbleTumble.playGame = function () {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Inside_page.jpg";
    $("#playBtnDiv").hide();
    $("#gamePage").show();
    $("#home").show();
    JumbleTumble.getQuestion();
}

// get question index and call JumbleTumble.generateSpans()
JumbleTumble.getQuestion = function () {
    var d;
    JumbleTumble.questionCtr++;
    JumbleTumble.questionIndex = (Math.floor(Math.random() * JumbleTumble.wordData.length));
    questionId = JumbleTumble.wordData[JumbleTumble.questionIndex].questionId;
    ansWord = JumbleTumble.wordData[JumbleTumble.questionIndex].sentence;
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    JumbleTumble.generateSpans();
    if (JumbleTumble.soundFlag == false) {
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/instruction.mp3";
        document.getElementById("playSound").play();
        JumbleTumble.soundFlag = true;
    }

}

//generate span for each word
JumbleTumble.generateSpans = function () {
    var sentenceString, textShuffleArray, i = 0,
        innrDiv, spanParent, frogImg, randomNo = 1,
        spans, str;

    //load all words of sentence from json as array
    sentenceString = JumbleTumble.wordData[JumbleTumble.questionIndex].sentence;
    JumbleTumble.textStringArray = sentenceString.split(" ");
    console.log(JumbleTumble.textStringArray);
    // remove "।" from last
    tempStr = JumbleTumble.textStringArray[(JumbleTumble.textStringArray.length) - 1];
    console.log(tempStr);
    if (tempStr == ".")
        JumbleTumble.textStringArray.pop();
    else if (tempStr[(tempStr.length) - 1] == ".") {
        tempStr = tempStr.slice(0, (tempStr.length) - 1);
        JumbleTumble.textStringArray[(JumbleTumble.textStringArray.length) - 1] = tempStr;
    }

    // copy array for changes
    textShuffleArray = JumbleTumble.textStringArray.slice();

    // shuffle
    textShuffleArray = JumbleTumble.shuffleArray(textShuffleArray);
    spanParent = document.createElement('div');
    spanParent.setAttribute("id", "Maindiv");
    spanParent.setAttribute("class", "noPadding divParent col-xs-12 col-sm-12 col-md-12 col-lg-12");
    spanParent.style.backgroundImage = "url(" + Utils.Path + "images/skin/Unit-for-sentence.png)";
    //create span and set sentence
    for (i = 0; i <= textShuffleArray.length; i++) {
        div = document.createElement('div');
        div.setAttribute("id", "div" + (i + 1));
        div.setAttribute("class", "noPadding parentSpan");
        spans = document.createElement('span');
        spans.setAttribute("id", "span" + (i + 1))
        if (i != textShuffleArray.length) {
            spans.setAttribute("class", "spanClass dragedElement");
            spans.innerHTML = textShuffleArray[i];
            $(div).droppable({
                accept: ".dragedElement",
                drop: JumbleTumble.dragDropText
            });
        } else {
            spans.setAttribute("class", "spanClass");
            spans.innerHTML = "."
        }
        spanParent.appendChild(div);
        div.appendChild(spans);
    }
    sentenceDiv.appendChild(spanParent);
    $(".dragedElement").draggable({
        revert: "invalid",
        helper: 'clone',
        start: function (event, ui) {
            document.getElementById("playSound").pause();
        }
    });
}

//drag drop function
JumbleTumble.dragDropText = function (event, ui) {
    var dragId, dropId;
    dragId = ui.draggable.prop("id")
    dropId = event.target.id;
    var x = $("#" + dragId).parent().get(0).id;
    var y = $("#" + dropId).children().get(0).id;
    var z = $("#" + x).children().get(0).id;
    $("#" + x).append($("#" + y));
    $("#" + dropId).append($("#" + z));
}


// check answer
JumbleTumble.checkAnswerString = function () {
    var i = 0,
        j = 0,
        spanID, sentenceString = "";
    $(".spanClass").css("pointer-events", "none");
    JumbleTumble.attemptCtr++;
    for (i = 0; i < JumbleTumble.textStringArray.length; i++) //JumbleTumble.textStringArray contains answer string
    {
        spanID = $("#div" + (i + 1)).children().get(0).id;
        if (sentenceString != "")
            sentenceString = sentenceString + " ";
        sentenceString = sentenceString + $("#" + spanID).html();
        // if($("#"+spanID).html()==JumbleTumble.textStringArray[i])
        // 	continue;
        // else
        // 	break;
    }
    // for (j = 0; j < JumbleTumble.wordData[JumbleTumble.questionIndex].sentenceNodes.length; j++) {
    //     if (sentenceString.search(JumbleTumble.wordData[JumbleTumble.questionIndex].sentenceNodes[j]) != -1)
    //         continue;
    //     else
    //         break;
    // }
    sentenceString=sentenceString + "."
    if (sentenceString == JumbleTumble.wordData[JumbleTumble.questionIndex].sentence) {
        $("#next").addClass("blink_me");
        $("#next").addClass("blink_me");

        //JumbleTumble.correctWrongModalShow("That is correct...", 2000);
        document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy_correct-ANS.png";
        setTimeout(function () {
            document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy.png";
        }, 2000);
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/thats_right.mp3";
        $("#checkBtnDiv").css("pointer-events", "none");
        $("#soundBtn").css("pointer-events", "none");
        $("#helpBtn").css("pointer-events", "none");
        if (JumbleTumble.attemptCtr == 1)
            scoredMarks = 10;
        else if (JumbleTumble.attemptCtr == 2)
            scoredMarks = 5;
        else
            scoredMarks = 0;
        if (!JumbleTumble.scoreFlag) {
            JumbleTumble.scoreFlag = true;
            console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
            if (Utils.mobileDeviceFlag)
                Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
            if (scoredMarks)
                if (Utils.mobileDeviceFlag)
                    Android.addLearntData(ansWord, totalJsonQueCount, wordType);
        } // setTimeout(function () {
        // 	JumbleTumble.nextQuestion();
        // }, 2000);
    } else {
        if (JumbleTumble.attemptCtr == 1) {
            document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Try_again.mp3";
            //JumbleTumble.correctWrongModalShow("Look carefully...", 2000);
            document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy_Wrong-ANS.png";
            setTimeout(function () {
                document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy.png";
                $(".spanClass").css("pointer-events", "auto");
            }, 2000);
        } else {

            document.getElementById("playSound").src = Utils.Path + "sounds/instructions/wrongSoundAksharkhadi.mp3";
            //JumbleTumble.correctWrongModalShow("That is wrong", 2000);
            document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy_Wrong-ANS.png";
            setTimeout(function () {
                document.getElementById("boyImg").src = Utils.Path + "images/skin/Boy.png";
                $(".spanClass").css("pointer-events", "auto");
            }, 2000);
            scoredMarks = 0;
            $("#next").addClass("blink_me");

            if (!(JumbleTumble.helpTakenFlag)) {
                $("#checkBtnDiv").css("pointer-events", "none");
                $("#soundBtn").css("pointer-events", "none");
            }
            //$("#checkBtnDiv").css("pointer-events", "none");
            //$("#soundBtn").css("pointer-events", "none");
            // setTimeout(function () {
            // 	JumbleTumble.nextQuestion();
            // }, 2000);
        }
    }
    document.getElementById("playSound").play();
    // if you want to change question after attempt uncomment the following lines
    // $("#sentenceDiv").html("")
    // JumbleTumble.setVariables();
    // JumbleTumble.getQuestion();
}

// shuffle words array
JumbleTumble.shuffleArray = function (array) {
    var i = 0,
        randomNum1, randomNum2, temp;
    for (i = 0; i < 5; i++) {
        randomNum1 = (Math.floor(Math.random() * array.length));
        randomNum2 = (Math.floor(Math.random() * array.length));
        temp = array[randomNum1];
        array[randomNum1] = array[randomNum2];
        array[randomNum2] = temp;
    }
    return array;
}

// help btn click 
JumbleTumble.help = function () {
    JumbleTumble.helpTakenFlag = true;
    if (!(JumbleTumble.helpFlag)) {
        JumbleTumble.helpFlag = true;
        scoredMarks = 0;
        JumbleTumble.attemptCtr++;
        $("#checkBtnDiv").css("pointer-events", "none");
        $(".spanClass").css("pointer-events", "none");
        document.getElementById("helpBtn").src = Utils.Path + "images/skin/Hide-Help.png";
        for (i = 0; i < JumbleTumble.textStringArray.length; i++) {
            spanID = $("#div" + (i + 1)).children().get(0).id;
            $("#" + spanID).html(JumbleTumble.textStringArray[i])
        }
    } else {
        JumbleTumble.helpFlag = false;
        $("#checkBtnDiv").css("pointer-events", "auto");
        document.getElementById("helpBtn").src = Utils.Path + "images/skin/Help.png";
        $(".spanClass").css("pointer-events", "auto");
        $("#soundBtn").css("pointer-events", "auto");
        textShuffleArray = JumbleTumble.textStringArray.slice();
        textShuffleArray = JumbleTumble.shuffleArray(textShuffleArray);
        for (i = 0; i < JumbleTumble.textStringArray.length; i++) {
            spanID = $("#div" + (i + 1)).children().get(0).id;
            $("#" + spanID).html(textShuffleArray[i])
        }

    }
}
//runs @ onclick of next button.
JumbleTumble.onNextClick = function () {
    if (!JumbleTumble.attemptCtr) {
        scoredMarks = -1;
    }
    JumbleTumble.nextQuestion();

}

//next question
JumbleTumble.nextQuestion = function () {
    JumbleTumble.helpTakenFlag = false;
    $("#next").removeClass("blink_me");
    $("#soundBtn").css("pointer-events", "auto");
    $(".spanClass").css("pointer-events", "auto");
    $("#checkBtnDiv").css("pointer-events", "auto");
    $("#helpBtn").css("pointer-events", "auto");
    document.getElementById("playSound").pause();
    document.getElementById("helpBtn").src = Utils.Path + "images/skin/Help.png";
    JumbleTumble.helpFlag = false;
    JumbleTumble.attemptCtr = 0;
    if (!JumbleTumble.scoreFlag) {
        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    }
    JumbleTumble.scoreFlag = false;
    if (JumbleTumble.questionCtr < 5) {
        $("#checkBtnDiv").css('visibility', 'visible');
        $("#sentenceDiv").html("");
        //JumbleTumble.setVariables();
        JumbleTumble.getQuestion();
    } else {
        $("#endPage").show();
        $("#gamePage").hide();
    }
}
JumbleTumble.playAgain = function () {
    $("#endPage").hide();
    $("#gamePage").show();
    $("#checkBtnDiv").css('visibility', 'visible');
    $("#sentenceDiv").html("");
    $("#acknowledgementDiv").hide();
    JumbleTumble.setVariables();
    JumbleTumble.getQuestion();
}
//show modal for correct wrong msg, it takes two values as message string(str) and duration 
JumbleTumble.correctWrongModalShow = function (str, duration) {
    $("#answerText").html(str);
    $("#correctWrongModal").show();
    setTimeout(function () {
        $("#correctWrongModal").hide();
    }, duration);
}

JumbleTumble.createAcknowledgementDivs = function () {
    var i = 0,
        div;
    for (i = 0; i < Object.keys(JumbleTumble.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(JumbleTumble.AcknowledgementPageData)[i] + " : " + Object.values(JumbleTumble.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = JumbleTumble.hardCodedData['createdOn'];
    div.style.marginBottom = "2vh";
    acknowledgementDiv.appendChild(div);
}

JumbleTumble.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();

}
// home btn click
JumbleTumble.homeClickFun = function () {
    if (JumbleTumble.attemptCtr) {
        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    }
    location.reload();
}

JumbleTumble.playInstruction = function () {
    document.getElementById("playSound").src = Utils.Path + "sounds/instructions/instruction.mp3";
    document.getElementById("playSound").play();
}