//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,
    totalLength = 5,
    correctCnt = 0,
    nounCnt = 0,
    pronounCnt = 0,
    adjectiveCnt = 0,
    dropCnt = 0,
    quesCnt = 0,
    modalCnt = 5,
    queCorrectCnt = 0;
Grammar.skipedQ = 0;
Grammar.alreadyShownObject = []; //maintains unique question array
Grammar.tempArr = []; //json data
Grammar.skipFlag = true;
Grammar.checkFlag = false;
Grammar.wordsArr = []; //get 6 unique words
Grammar.randomLevel = 0; //word level
var wordTypeArr = []; //type of words-noun pronoun ,adjective
gameType = "Words";
Grammar.questionArr = [];
correctWordArr = [];
showRemainingFlag = false;
Grammar.seconds = 0;
//function for loader
$(document).ready(function() {
	document.title=Grammar.acknowledgementData["Name of the Game "];
    $(".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 + ")";
    document.getElementById("questionDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/Strip.png)";
    $(".bgStyle").css({ "background-size": "100% 100%" });
    $("#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/Skip.png");
    $("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
    $("#credit").prop("src", Utils.Path + "images/skin/credits.png");
    $("#soundImage").prop('src', Utils.Path + "images/skin/Sound.png");
    $("#checkImg").prop('src', Utils.Path + "images/skin/Done.png");
    $("#nextGameImage").prop('src', Utils.Path + "images/skin/Next.png");
}
Grammar.playGame = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.jpg)";
    $("#homeImg,#gamePage,#widgetDiv,#classificationDiv").show();
    $("#coverPage").hide();
    Grammar.createStars();
    Grammar.showQuestion();
    Grammar.playInstruction();
}
Grammar.createStars = function() { //5 stars 
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= numberOfStars; i++) {
        newDiv = document.createElement("div");
        newDiv.setAttribute("id", "starDiv" + i);
        newDiv.setAttribute("class", "noPadding stars col-xs-2 col-md-2 col-lg-2 col-sm-2");

        newImage = document.createElement("img");
        newImage.setAttribute("id", "starImg" + i);
        newImage.setAttribute("class", "img-responsive noPadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
        newImage.setAttribute("src", Utils.Path + "images/skin/star1.png");
        $(newDiv).append(newImage);
        $("#starDiv").append(newDiv);
    }
    $("#starDiv").css("visibility", "hidden");
};
Grammar.showQuestion = function() //populate words & Show it on screen
    {
        var spanEle, wordCnt = 6,
            boxWordCntArr = [],
            comma;
        correctWordArr = [];
        nounCnt = 0, pronounCnt = 0, adjectiveCnt = 0;
        clearInterval(Grammar.noResponseTimer);
        document.getElementById('playSound').pause();
        Grammar.skipFlag = true;
        Grammar.checkFlag = false;
        dropCnt = 0;
        scoredMarks = 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 = [];
        wordTypeArr = [];
        if (showRemainingFlag == false) {
            for (var i = 0; i < wordCnt; i++) {

                Grammar.createUniqueWords();
                while ($.inArray(Grammar.data[Grammar.randomLevel].list[Grammar.randomWord].word, Grammar.alreadyShownObject) !== -1) {
                    wordTypeArr.pop();
                    Grammar.createUniqueWords();
                }
                Grammar.alreadyShownObject.push(Grammar.data[Grammar.randomLevel].list[Grammar.randomWord].word);
                Grammar.wordsArr.push(Grammar.data[Grammar.randomLevel].list[Grammar.randomWord]);

                totalMarks = Grammar.wordsArr.length;
                if (Grammar.wordsArr[i].type == Grammar.typeArr[0].data)
                    nounCnt++;
                else if (Grammar.wordsArr[i].type == Grammar.typeArr[1].data)
                    pronounCnt++;
                else
                    adjectiveCnt++;
            }
            Grammar.createWordSpan(Grammar.wordsArr);
        } else {
            Grammar.wordsArr.push(Grammar.questionArr[quesCnt])
            totalMarks = Grammar.wordsArr[0].length;
            for (var i = 0; i < wordCnt; i++) {

                if (Grammar.wordsArr[0][i].type == Grammar.typeArr[0].data)
                    nounCnt++;
                else if (Grammar.wordsArr[0][i].type == Grammar.typeArr[1].data)
                    pronounCnt++;
                else
                    adjectiveCnt++;
            }
            Grammar.createWordSpan(Grammar.wordsArr[0]);
        }

        boxWordCntArr.push(nounCnt)
        boxWordCntArr.push(pronounCnt)
        boxWordCntArr.push(adjectiveCnt)
        Grammar.createDivs(boxWordCntArr);
        Grammar.startTimer();
    }

Grammar.createUniqueWords = function() {
    Grammar.randomWord = Math.floor(Math.random() * Grammar.data[Grammar.randomLevel].list.length);
    wordTypeArr.push(Grammar.data[Grammar.randomLevel].list[Grammar.randomWord].type);
    var ncnt = pcnt = acnt = 0;
    for (var i = 0; i < wordTypeArr.length; i++) {
        if (wordTypeArr[i] == Grammar.typeArr[0].data)
            ncnt++;
        else if (wordTypeArr[i] == Grammar.typeArr[1].data)
            pcnt++;
        else
            acnt++;
    }
    if ((ncnt > 3)) {
        ncnt--;
        wordTypeArr.pop();
        Grammar.createUniqueWords();
    }
    if ((pcnt > 3)) {
        pcnt--;
        wordTypeArr.pop();
        Grammar.createUniqueWords();
    }
    if ((acnt > 3)) {
        acnt--;
        wordTypeArr.pop();
        Grammar.createUniqueWords();
    }
}
Grammar.createWordSpan = function(wordArr) {
    for (var i = 0; i < wordArr.length; i++) {
        spanEle = document.createElement("span");
        spanEle.setAttribute("class", "zIndexClass");
        $(spanEle).text(wordArr[i].word + " ");
        comma = document.createElement('span');
        $(comma).text(", ");
        document.getElementById("questionDiv").appendChild(spanEle);
        if (i != wordArr.length - 1)
            document.getElementById("questionDiv").appendChild(comma);
        if ($(spanEle).text() != "| ") {
            $(spanEle).draggable({ //change line-height after dragging the element
                cursor: 'move',
                revert: 'invalid',
                helper: 'clone',
                start: function(e, ui) {
                    $(ui.helper).addClass("ui-draggable-helper");
                    document.getElementById('playSound').pause();
                    clearInterval(Grammar.noResponseTimer);
                    clearTimeout(Grammar.timeOut);
                    Grammar.seconds = 0;
                    Grammar.startTimer();
                }
            });
        }
    }
}
Grammar.createDivs = function(array) { //create Tabular Divs 
    var column, row;
    for (var i = 0; i < 3; i++) {
        if (array[i] != 0) {
            column = document.createElement("div");
            column.setAttribute("id", "column" + i);
            column.setAttribute("class", "columnCls 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", "columnCls text-center col-lg-10 col-md-10 col-xs-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
                if (j == 0) {
                    typeImg = document.createElement("img");
                    typeImg.setAttribute("id", "typeImg" + i + "" + j);
                    typeImg.setAttribute("class", "img-responsive noPadding col-xs-4 col-sm-4 col-lg-4 col-md-4 col-sm-offset-4 col-lg-offset-4 col-md-offset-4 col-xs-offset-4");
                    $(row).append(typeImg);
                } else {
                    $(row).addClass('boxClass');
                    for (var j = 0; j < array[i]; j++) {
                        wordEle = document.createElement("div");
                        wordEle.setAttribute("id", "wordEle" + i + "" + j);
                        wordEle.setAttribute("class", "rowClass col-lg-12 col-md-12 col-xs-12 col-sm-12");
                        $(row).append(wordEle);
                        $(wordEle).data("data", Grammar.typeArr[i].data);
                        $(wordEle).droppable({ drop: dropElement, dragover: allowDrop });
                    }
                }
                $(column).append(row);
            }
        }
    }
    if ($("#classificationDiv").children().length == 2)
        $("#" + $("#classificationDiv").children()[0].id).prop("class", "columnCls 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");
    document.getElementById("row01").style.backgroundImage = "url(" + Utils.Path + "images/skin/contener0.png)";
    document.getElementById("row11").style.backgroundImage = "url(" + Utils.Path + "images/skin/contener1.png)";
    $("#typeImg00").prop('src', Utils.Path + "images/skin/Boy.png");
    $("#typeImg10").prop('src', Utils.Path + "images/skin/Girl.png");
}
Grammar.playInstruction = function() { //play instruction
    Grammar.seconds = 0;
    clearInterval(Grammar.noResponseTimer);
    clearTimeout(Grammar.timeOut);
    getDuration(Utils.Path + 'sounds/instruction/' + Grammar.hardcoded.instruction);
}

function getDuration(src) {
    var duration = 0;
    //if (ShowMe.soundFlag) {
    $('#playSound').on("loadedmetadata", function() {
        duration = $('#playSound').prop('duration');
        $('#playSound').unbind("loadedmetadata");
        Grammar.playNextSound(duration);
    });
    $('#playSound').prop('src', src);
}
Grammar.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('playSound').play();
        if (Grammar.instructionTimer) {
            clearTimeout(Grammar.instructionTimer);
            Grammar.instructionTimer = null;
        }
        Grammar.instructionTimer = setTimeout(function() {
            Grammar.startTimer();
        }, duration * 1000);
    }

function dropElement(event, ui) {
    var condition;
    Grammar.attemptFlag = true;
    clearInterval(Grammar.noResponseTimer);
    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) {
        $(this).children().remove();
        dropCnt--;
    }
    $(this).append(ui.draggable.clone());
    if (showRemainingFlag == false)
        condition = Grammar.wordsArr.length;
    else
        condition = Grammar.wordsArr[0].length;
    if (dropCnt == condition)
        $("#checkImg").css("visibility", "visible");
    Grammar.startTimer();
}
Grammar.startTimer = function() { //5 second timer (No responce Sound)
    $("#nextImage").css({ "pointer-events": "auto" });
    if (Grammar.noResponseTimer) {
        clearInterval(Grammar.noResponseTimer);
        Grammar.noResponseTimer = null;
        Grammar.seconds = 0;
    }
    Grammar.noResponseTimer = setInterval(function() {
        Grammar.seconds++;
        if (Grammar.seconds >= 7) {
            document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + Grammar.hardcoded.noResponce;
            document.getElementById("playSound").play();
            $(".pointerClass").css("pointer-events", "auto");
            clearInterval(Grammar.noResponseTimer)
            if (Grammar.timeOut) {
                clearTimeout(Grammar.timeOut);
                Grammar.timeOut = null;
            }
            Grammar.timeOut = setTimeout(function() {
                Grammar.seconds = 0;
                Grammar.startTimer();
            }, 2000);
        }
    }, 1000);
}
Grammar.checkAnswer = function() {
    var duplicateDropELe0 = [],
        duplicateDropELe1 = [],
        duplicateDropELe2 = [],
        tempWordArr;
    correctCnt = 0;
    correctWordArr = [];
    Grammar.skipFlag = false;
    Grammar.checkFlag = true;
    clearTimeout(Grammar.timeOut);
    clearTimeout(Grammar.nextQ);
    clearInterval(Grammar.noResponseTimer)
    wrongCnt++;
    if (showRemainingFlag)
        tempWordArr = Grammar.wordsArr[0];
    else
        tempWordArr = Grammar.wordsArr;
    for (var i = 0; i < $("#classificationDiv").children().length; i++) {
        var wordType = null;
        duplicateFlag = false;
        for (var j = 0; j < $($($("#classificationDiv").children()[i]).children()[1]).children().length; j++) {
            for (var k = 0; k < tempWordArr.length; k++) //find sentence
            {
                if ($($($($("#classificationDiv").children()[i]).children()[1]).children()[j]).children().text().trim() == tempWordArr[k].word) {
                    wordType = tempWordArr[k].type; //get type of sentence
                    break;
                }
            }
            if ($.inArray($($($($("#classificationDiv").children()[i]).children()[1]).children()[j]).children().text().trim(), eval("duplicateDropELe" + i)) == -1) {
                eval("duplicateDropELe" + i).push($($($($("#classificationDiv").children()[i]).children()[1]).children()[j]).children().text().trim());
                duplicateFlag = false;
            } else
                duplicateFlag = true;
            if ((duplicateFlag != true) && (wordType == $($($($($("#classificationDiv").children()[i]).children()[1]).children()[j])).data("data"))) //check types
            {
                correctCnt++;
                $($($($($("#classificationDiv").children()[i]).children()[1]).children()[j])[0]).css("color", "green");
                correctWordArr.push(Grammar.wordsArr[k].word);
                scoredMarks = correctCnt;
            } else
                $($($($($("#classificationDiv").children()[i]).children()[1]).children()[j])[0]).css("color", "red");
        }
    }
    if (correctCnt == tempWordArr.length) {
        queCorrectCnt++;
        randomSound = Math.floor(Math.random() * (Grammar.correctAns.length));
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Grammar.correctAns[randomSound];
        $("#character").prop('src', Utils.Path + "images/skin/Graphic_Correct-ANS.png");
        document.getElementById('playSound').play();
        //Grammar.calculateScore();
    } else {
        randomSound = Math.floor(Math.random() * (Grammar.wrongAns.length));
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
        document.getElementById('playSound').play();

    }
    Grammar.calculateScore();
    Grammar.questionArr.splice(quesCnt, 1);
    $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
    modalCnt--;
    if (Grammar.nextQ) {
        clearTimeout(Grammar.nextQ);
        Grammar.nextQ = null;
    }
    Grammar.nextQ = setTimeout(function() {
        $("#correctWrongModal").hide();
        $("#gamePage,#checkDiv,#soundDiv").css("pointer-events", "none");
        $("#nextDiv").addClass("blink_me");
        Grammar.nextQuestion();
    }, 1500);

}
Grammar.nextQuestion = function() { //Loads Next Question

    Grammar.skipedQ++;
    correctCnt = 0;
    clearTimeout(Grammar.timeOut);
    clearTimeout(Grammar.nextQ);
    clearInterval(Grammar.noResponseTimer)
    document.getElementById('playSound').pause();
    $(".opacityCls").css({ 'opacity': '1', 'pointer-events': 'auto' });
    if (Grammar.checkFlag == false && showRemainingFlag == false)
        Grammar.questionArr.push(Grammar.wordsArr);
    if (Grammar.skipFlag)
        quesCnt++;
    $("#gamePage,#checkDiv,#soundDiv").css("pointer-events", "auto");
    $("#nextDiv").removeClass("blink_me");
    clearTimeout(Grammar.nextQ);
    $(".rowClass").css("scrollTop", "0");
    if (modalCnt == 0)
        Grammar.lastPage();
    else if (quesCnt == modalCnt) {
        $('#responseBoxDiv').show();
        $('#confiramtionText').text(Grammar.hardcoded.responseMsg);
        $('#Yes').text(Grammar.hardcoded.yes);
        $('#No').text(Grammar.hardcoded.no);
    } else
        Grammar.showQuestion();
}
Grammar.showNext = function(element) { //onclick of Yes/No modal option
    if ($(element).text() == Grammar.hardcoded.no)
        Grammar.lastPage();
    else
        Grammar.showRemaining();
}
Grammar.lastPage = function() { //show last page
    clearInterval(Grammar.noResponseTimer);
    clearTimeout(Grammar.timeOut);
    document.getElementById('playSound').pause();
    $('#endPage').show();
    $('#responseBoxDiv,#gamepage,#widgetDiv').hide();
    $("#message").text(Grammar.hardcoded.gameOver);
    $("#message").css("visibility", "visible");
    Grammar.giveStars();
    console.log(queCorrectCnt, totalLength);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(queCorrectCnt, totalLength, "2");
}
Grammar.giveStars = function() { //calculates stars
    var i, numberOfStars = queCorrectCnt;
    for (i = 1; i <= numberOfStars; i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
    $("#starDiv").css("visibility", "visible");
    if (queCorrectCnt != 0) {
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + 'Star' + queCorrectCnt + '.mp3';
        document.getElementById('playSound').play();
    }
};
Grammar.showRemaining = function() { //show remaining questions
    quesCnt = 0;
    Grammar.checkFlag = false;
    showRemainingFlag = true;
    $('#responseBoxDiv').hide();
    $('#gamepage').show();
    $("#soundDiv").css("visibility", "visible");
    Grammar.showQuestion();
}

Grammar.calculateScore = function() {
    Grammar.attemptFlag = false;
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, gameType);
    if (correctWordArr.length > 0) {
        for (var i = 0; i < correctWordArr.length; i++) {
            console.log(correctWordArr[i], Grammar.data[0].list.length, gameType);
        }
    }
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, gameType);
        if (correctWordArr.length > 0) {
            for (var i = 0; i < correctWordArr.length; i++) {
                Android.addLearntData(correctWordArr[i], Grammar.data[0].list.length, gameType);
            }
        }
    }

}

function allowDrop(event) {
    event.preventDefault();
}
Grammar.nextGame = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}