//1 Sept 2019
var Grammar = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    resId = 0,
    totalMarks = 10,
    wrongCnt = 0,
    correctCnt = 0,
    nounCnt = 0,
    pronounCnt = 0,
    adjectiveCnt = 0,
    dropCnt = 0,
    type = "sentence";
Grammar.skipedQ = 0;
Grammar.alreadyShownObject = []; //maintains unique question array
Grammar.tempArr = []; //json data
Grammar.skipFlag = true;
Grammar.attemptFlag = false;
Grammar.checkFlag = false;
Grammar.wordsArr = []; //get unique sentence
Grammar.randomLevel = 0; //sentence level
Grammar.splitSentenceArr = []; //splits sentence into words
Grammar.levelName = true; //false for learn & true for practice
gameType = "Sentence";
//function for loader
$(document).ready(function() {
    $(".se-pre-con").fadeOut("slow");
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
        Utils.mobileDeviceFlag = true;
    /* if(Utils.mobileDeviceFlag)
    	Utils.Path=Android.getMediaPath("Aksharkhadi");  */
    setTimeout(function() {
        $("#gamePage,#widgetDiv,#endPage,#homeImg").hide();
        $("#coverPage").show();

        Grammar.setImages();
    }, 300);
});
Grammar.setImages = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + Grammar.coverImage + ")";
    $("#homeImg").prop("src", Utils.Path + "images/skin/Home.png");
    $("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
    $("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
    $("#nextImage").prop("src", Utils.Path + "images/skin/Next.png");
    $("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
    $("#credit").prop("src", Utils.Path + "images/skin/credits.png");
    $("#checkImg").prop('src', Utils.Path + "images/skin/Done.png");
    $("#quesDivRope").prop('src', Utils.Path + "images/skin/Top-rop.png");
    $("#soundImage").prop('src', Utils.Path + "images/skin/Sound.png");
    $("#questionDiv").css('backgroundImage', "url(" + Utils.Path + "images/skin/Top-Box.png") + ")";
}
Grammar.playGame = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.jpg)";
    $("#homeImg,#gamePage,#widgetDiv,#classificationDiv").show();
    $("#coverPage").hide();
    if (Utils.mobileDeviceFlag)
        Grammar.levelName = Android.isPractice();
    if (Grammar.levelName)
        $("#checkImg").css("visibility", "visible");
    else
        $("#checkImg").css("visibility", "hidden");
    Grammar.showQuestion();
    Grammar.playInstruction();
}
Grammar.showQuestion = function() //populate words & sentences ,Show it on screen
    {
        var spanEle, randomSentence, boxWordCntArr = [],
            wordFoundFlag = false;
        Grammar.attemptFlag = false;
        Grammar.skipFlag = true;
        Grammar.checkFlag = false;
        $("#character").prop('src', Utils.Path + "images/skin/Graphic.png");
        nounCnt = 0, pronounCnt = 0, adjectiveCnt = 0, dropCnt = 0;
        $("#checkImg").css("visibility", "hidden");
        d = new Date();
        startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        $("#questionDiv,.rowClass,#classificationDiv").text('');
        Grammar.wordsArr = [];
        Grammar.splitSentenceArr = [];
        randomSentence = Math.floor(Math.random() * Grammar.data[Grammar.randomLevel].list.length);
        while ($.inArray(Grammar.data[Grammar.randomLevel].list[randomSentence].sentence, Grammar.alreadyShownObject) !== -1)
            randomSentence = Math.floor(Math.random() * Grammar.data[Grammar.randomLevel].list.length);
        Grammar.alreadyShownObject.push(Grammar.data[Grammar.randomLevel].list[randomSentence].sentence);
        Grammar.wordsArr.push(Grammar.data[Grammar.randomLevel].list[randomSentence]);
        Grammar.splitSentenceArr = Grammar.wordsArr[0].sentence.split(' ');
        totalMarks = Grammar.wordsArr[0].classification.length;
        for (var i = 0; i < Grammar.wordsArr[0].classification.length; i++) {
            if (Grammar.wordsArr[0].classification[i].type == Grammar.typeArr[0].data)
                nounCnt++;
            else if (Grammar.wordsArr[0].classification[i].type == Grammar.typeArr[1].data)
                pronounCnt++;
            else
                adjectiveCnt++;
        }
        loop1:
            for (var i = 0; i < Grammar.splitSentenceArr.length; i++) {
                wordFoundFlag = false;
                loop2:
                    for (var j = 0; j < Grammar.wordsArr[0].classification.length; j++) {
                        var wordArr = Grammar.wordsArr[0].classification[j].words.split(' ');
                        loop3:
                            for (var k = 0; k < wordArr.length; k++) {
                                var spanEle = document.createElement("span");
                                spanEle.setAttribute("class", "zIndexClass spanClass");
                                if (Grammar.splitSentenceArr[i] == wordArr[k]) {
                                    wordFoundFlag = true;
                                    if (wordArr.length == 2 && Grammar.splitSentenceArr[i + 1] == wordArr[k + 1]) {
                                        i++;
                                        break loop2;
                                    } else
                                        break loop2;
                                }
                            }
                    }
                if (wordFoundFlag)
                    $(spanEle).text(Grammar.wordsArr[0].classification[j].words + " ");
                else
                    $(spanEle).text(Grammar.splitSentenceArr[i] + " ");
                Grammar.makeDraggable($(spanEle))
                document.getElementById("questionDiv").appendChild(spanEle);
            }
        boxWordCntArr.push(nounCnt)
        boxWordCntArr.push(pronounCnt)
        boxWordCntArr.push(adjectiveCnt)
        Grammar.createDivs(boxWordCntArr);
        questionId = Grammar.wordsArr[0].sentenceId;
    }
Grammar.makeDraggable = function(element) {
    if (element.text() != "| ") {
        element.draggable({ //change line-height after dragging the element
            cursor: 'move',
            revert: 'invalid',
            helper: 'clone',
            start: function(e, ui) {
                $(ui.helper).addClass("ui-draggable-helper");
                //$(ui.helper).css("z-index", "1");
                //$(this).css("z-Index", 1);
            }
        });
    }
}
Grammar.createDivs = function(array) { //create Tabular Divs 
    var column, row, ropeDiv, cnt = 1;
    for (var i = 0; i < 3; i++) {
        if (array[i] != 0) {
            column = document.createElement("div");
            column.setAttribute("id", "column" + i);
            column.setAttribute("class", "noPadding col-lg-4 col-md-4 col-xs-4 col-sm-4");
            $("#classificationDiv").append(column);
            for (var j = 0; j < 2; j++) {
                row = document.createElement("div");
                row.setAttribute("id", "row" + i + j);
                row.setAttribute("class", "text-center bgClass col-lg-12 col-md-12 col-xs-12 col-sm-12");
                if (j == 0) {
                    $(row).addClass('borderBottomCls ');
                    $(row).text(Grammar.typeArr[i].word);
                    $(row).css('backgroundImage', "url(" + Utils.Path + "images/skin/Box-" + cnt + ".png") + ")";

                    ropeDiv = document.createElement("div");
                    ropeDiv.setAttribute("class", " col-lg-12 col-md-12 col-xs-12 col-sm-12");
                    $(ropeDiv).css({ "position": "relative", "top": "4vh" });

                    ropeImg = document.createElement("img");
                    ropeImg.setAttribute("id", "ropeImg" + i + j);
                    ropeImg.setAttribute("class", "img-responsive noPadding col-lg-4 col-md-4 col-xs-4 col-sm-4 col-sm-offset-4 col-lg-offset-4 col-md-offset-4 col-xs-offset-4");
                    ropeImg.setAttribute("src", Utils.Path + "images/skin/Middle-rop_0" + cnt + ".png");
                    $(ropeDiv).append(ropeImg);
                    $(column).append(ropeDiv);
                } else {
                    $(row).addClass('boxClass');
                    $(row).css('backgroundImage', "url(" + Utils.Path + "images/skin/unit-" + cnt + ".png") + ")";
                    for (var j = 0; j < array[i]; j++) {
                        wordEle = document.createElement("div");
                        wordEle.setAttribute("class", "rowClass col-lg-12 col-md-12 col-xs-12 col-sm-12");
                        //$(wordEle).css('backgroundImage', "url(" + Utils.Path + "images/skin/unit-" + cnt + ".png") + ")";
                        $(row).append(wordEle);
                        $(wordEle).data("data", Grammar.typeArr[i].data);
                        if (Grammar.levelName)
                            $(wordEle).droppable({ drop: dropElement, dragover: allowDrop });
                        else
                            $(wordEle).droppable({ drop: onDrop, dragover: allowDrop });
                    }
                }

                $(column).append(row);

            }
            cnt++;
        }
    }
    if ($("#classificationDiv").children().length == 2)
        $("#" + $("#classificationDiv").children()[0].id).prop("class", "noPadding col-lg-4 col-md-4 col-xs-4 col-sm-4 col-sm-offset-2 col-lg-offset-2 col-md-offset-2 col-xs-offset-2");
}
Grammar.playInstruction = function() { //play instruction
    clearInterval(Grammar.noResponseTimer);
    clearTimeout(Grammar.timeOut);
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Grammar.hardcoded.instruction;
    document.getElementById('playSound').play();
}

function dropElement(event, ui) {
    Grammar.attemptFlag = true;
    Grammar.skipFlag = false;
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
    document.getElementById('playSound').play();
    dropCnt++;
    $(this).css("color", "black");

    if ($(this).children().length != 0) {
        dropCnt--;
        $(this).children().remove();
    }
    $(this).append(ui.draggable.clone());
    //$(this).children().css({ "position": "relative", "top": "5vh" });
    if (dropCnt == Grammar.wordsArr[0].classification.length)
        $("#checkImg").css("visibility", "visible");
}
Grammar.checkAnswer = function() {
    correctCnt = 0;
    Grammar.skipFlag = false;
    Grammar.attemptFlag = false;
    Grammar.checkFlag = true;
    wrongCnt++;
    var randomSound;
    for (var i = 0; i < $("#classificationDiv").children().length; i++) {
        var wordType = null;
        for (var j = 0; j < $($($("#classificationDiv").children()[i]).children()[2]).children().length; j++) {
            for (var k = 0; k < Grammar.wordsArr[0].classification.length; k++) //find sentence
            {
                if ($($($($("#classificationDiv").children()[i]).children()[2]).children()[j]).children().text().trim() == Grammar.wordsArr[0].classification[k].words.trim()) {
                    wordType = Grammar.wordsArr[0].classification[k].type; //get type of sentence
                    break;
                }
            }
            if (wordType == $($($($($("#classificationDiv").children()[i]).children()[2]).children()[j])).data("data")) //check types
            {
                correctCnt++;
                $($($($($("#classificationDiv").children()[i]).children()[2]).children()[j])[0]).css("color", "#084c08");
                scoredMarks = correctCnt;
                if (correctCnt == Grammar.wordsArr[0].classification.length) //check total length
                {
                    //$("#correctWrongModal").show();

                    setTimeout(function() {
                        $("#correctWrongModal").hide();
                    }, 1500);
                }
            } else {

                $($($($($("#classificationDiv").children()[i]).children()[2]).children()[j])[0]).css("color", "#a00d0d");
            }

        }
    }
    if (correctCnt == Grammar.wordsArr[0].classification.length) {
        randomSound = Math.floor(Math.random() * (Grammar.correctAns.length));
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Grammar.correctAns[randomSound];
        document.getElementById('playSound').play();
        $("#character").prop('src', Utils.Path + "images/skin/Graphic_Correct-ANS.png");
        console.log(Grammar.wordsArr[0].sentence, Grammar.data[0].list.length, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(Grammar.wordsArr[0].sentence, Grammar.data[0].list.length, type);
    } else {
        randomSound = Math.floor(Math.random() * (Grammar.wrongAns.length));
        document.getElementById('playSound').pause();
        if (wrongCnt == 2)
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
        else
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Grammar.wrongAns[randomSound];
        document.getElementById('playSound').play();
        $("#character").prop('src', Utils.Path + "images/skin/Graphic_Wrong-ANS.png");
    }
    if (wrongCnt == 2 || correctCnt == Grammar.wordsArr[0].classification.length) {
        $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $("#nextDiv").addClass("bounceCls");
        if (Grammar.nextQ) {
            clearTimeout(Grammar.nextQ);
            Grammar.nextQ = null;
        }
        Grammar.nextQ = setTimeout(function() {
            //$("#correctWrongModal").hide();
            $("#gamePage").css("pointer-events", "none");


            //Grammar.nextQuestion();
        }, 1500);
    }

}

function onDrop(event, ui) {
    var wordType, randomSound;
    Grammar.attemptFlag = true;
    Grammar.skipFlag = false;
    for (var i = 0; i < Grammar.wordsArr[0].classification.length; i++) //find sentence
    {
        if ($(ui.draggable).text().trim() == Grammar.wordsArr[0].classification[i].words.trim()) {
            wordType = Grammar.wordsArr[0].classification[i].type; //get type of sentence
            break;
        }
    }
    if (wordType == $(this).data("data")) //check types
    {
        correctCnt++;
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/Excellent!_Aditi.mp3';
        document.getElementById('playSound').play();
        $("#character").prop('src', Utils.Path + "images/skin/Graphic_Correct-ANS.png");

        if (wordType == Grammar.typeArr[0].data)
            nounCnt--
            else if (wordType == Grammar.typeArr[1].data)
                pronounCnt--
                else
                    adjectiveCnt--

                    $(this).append(ui.draggable.clone());
            //$(this).children().css({ "position": "relative", "top": "5vh" });
        $(ui.draggable).draggable("disable");
        $(ui.draggable).css("opacity", "0.5");
        var mybr = document.createElement('br');
        $(this).append(mybr);
        $(ui.draggable).draggable("option", "revert", false);

        if (correctCnt == Grammar.wordsArr[0].classification.length) //check total length
        {
            //$("#correctWrongModal").show();
            $("#nextDiv").addClass("bounceCls");
            $("#character").prop('src', Utils.Path + "images/skin/Graphic_Correct-ANS.png");
            $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
            $("#gamePage").css("pointer-events", "none");
            setTimeout(function() {
                $("#correctWrongModal").hide();
            }, 1500);
        }
    } else {
        $(ui.draggable).draggable("option", "revert", true);
        $("#character").prop('src', Utils.Path + "images/skin/Graphic_Wrong-ANS.png");
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/Try_Again!_Aditi.MP3';
        document.getElementById('playSound').play();
    }
}
Grammar.nextQuestion = function() { //Loads Next Question
    Grammar.skipedQ++;
    $("#gamePage").css("pointer-events", "auto");
    $(".opacityCls").css({ 'opacity': '1', 'pointer-events': 'auto' });
    $("#nextDiv").removeClass("bounceCls");
    document.getElementById('playSound').pause();
    if (Grammar.attemptFlag == true && Grammar.checkFlag == false) {
        scoredMarks = 0;
        Grammar.attemptFlag = false;
        Grammar.calculateScore();
    }
    if (Grammar.skipFlag) {
        scoredMarks = -1;
        Grammar.calculateScore();
    }
    if (Grammar.checkFlag)
        Grammar.calculateScore();

    wrongCnt = 0;
    correctCnt = 0;
    clearTimeout(Grammar.nextQ);
    $(".rowClass").css("scrollTop", "0");
    if (Grammar.skipedQ == 5) {
        Grammar.checkFlag = false;
        document.getElementById('playSound').pause();
        $('#endPage').show();
        $("#acknowledgementDiv").text('');
        $('#gamePage,#acknowledgementDiv,#widgetDiv').hide();
        $("#message").text(Grammar.hardcoded.gameOver);
        $("#message").css("visibility", "visible");
        Grammar.createHardcodeddivs();
    } else
        Grammar.showQuestion();
}
Grammar.createHardcodeddivs = function() {
    var ackDiv;
    for (var i = 0; i < Object.keys(Grammar.acknowledgementData).length; i++) {
        ackDiv = document.createElement("div");
        ackDiv.setAttribute("id", "ack" + i);
        ackDiv.setAttribute("class", "noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
        ackDiv.innerHTML = Object.keys(Grammar.acknowledgementData)[i] + " : " + Object.values(Grammar.acknowledgementData)[i];
        document.getElementById("acknowledgementDiv").appendChild(ackDiv);
    }
    div = document.createElement('div');
    div.className = "noPadding fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = Grammar.hardcoded['createdOn'];
    document.getElementById("acknowledgementDiv").appendChild(div);
}
Grammar.callHome = function() {
    if (Grammar.attemptFlag == true && Grammar.checkFlag == false) {
        scoredMarks = 0;
        Grammar.attemptFlag = false;
        Grammar.calculateScore();
    }
    if (Grammar.checkFlag)
        Grammar.calculateScore();
    location.reload(true);
}
Grammar.playAgain = function() {
    $("#endPage").hide();
    $("#gamePage,#widgetDiv").show();
    $("#message").text('');
    Grammar.skipedQ = 0;
    wrongCnt = 0;
    correctCnt = 0;
    Grammar.alreadyShownObject = [];
    Grammar.showQuestion();
}
Grammar.calculateScore = function() {
    if (Grammar.levelName) {
        Grammar.attemptFlag = false;
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, gameType);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, gameType);
    }
}
Grammar.showCredit = function() {
    $("#acknowledgementDiv").show();
}

function allowDrop(event) {
    event.preventDefault();
}