//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 = 0,
    correctCnt = 0,
    nounCnt = 0,
    pronounCnt = 0,
    adjectiveCnt = 0,
    dropCnt = 0;
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 6 unique words
Grammar.randomLevel = 0; //word level
Grammar.levelName = false; //false for learn & true for practice
var wordTypeArr = []; //type of words-noun pronoun ,adjective
gameType = "Words";
correctWordArr = [];
//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 + ")";
    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/Next.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");
}
Grammar.playGame = function() {
    //$("#soundImage").hide();
    Grammar.playInstruction();
    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.showQuestion = function() //populate words & Show it on screen
    {
        var spanEle, wordCnt = 6,
            boxWordCntArr = [],
            comma;
        correctWordArr = [];
        nounCnt = 0, pronounCnt = 0, adjectiveCnt = 0;
        Grammar.skipFlag = true;
        Grammar.attemptFlag = false;
        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 = [];
        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++;
        }
        for (var i = 0; i < Grammar.wordsArr.length; i++) {
            spanEle = document.createElement("span");
            spanEle.setAttribute("class", "zIndexClass");
            $(spanEle).text(Grammar.wordsArr[i].word + " ");
            comma = document.createElement('span');
            $(comma).text(", ");
            document.getElementById("questionDiv").appendChild(spanEle);
            if (i != Grammar.wordsArr.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) {
                        document.getElementById('playSound').pause();
                        $(ui.helper).addClass("ui-draggable-helper");
                    },
					// containment:'#gamePage'
                });
            }
        }
        boxWordCntArr.push(nounCnt)
        boxWordCntArr.push(pronounCnt)
        boxWordCntArr.push(adjectiveCnt)
        Grammar.createDivs(boxWordCntArr);
    }

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.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", "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);

                    //$(row).addClass('borderBottomCls');
                    //$(row).text(Grammar.typeArr[i].word);
                } 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);
                        if (Grammar.levelName)
                            $(wordEle).droppable({ drop: dropElement, dragover: allowDrop });
                        else
                            $(wordEle).droppable({ drop: onDrop, 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
    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) {
        $(this).children().remove();
        dropCnt--;
    }
    $(this).append(ui.draggable.clone());
    //$(this).children().css({ "position": "relative", "top": "5vh" });
    if (dropCnt == Grammar.wordsArr.length)
        $("#checkImg").css("visibility", "visible");
}

Grammar.checkAnswer = function() {
    var duplicateDropELe0 = [],
        duplicateDropELe1 = [],
        duplicateDropELe2 = [];
    correctCnt = 0;
    correctWordArr = [];
    Grammar.skipFlag = false;
    Grammar.checkFlag = true;
    Grammar.attemptFlag = false;
    wrongCnt++;
    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 < Grammar.wordsArr.length; k++) //find sentence
            {
                if ($($($($("#classificationDiv").children()[i]).children()[1]).children()[j]).children().text().trim() == Grammar.wordsArr[k].word) {
                    wordType = Grammar.wordsArr[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 == Grammar.wordsArr.length) {
        //Grammar.attemptFlag = false;
        randomSound = Math.floor(Math.random() * (Grammar.correctAns.length));
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/Right_answer__Aditi.mp3';
        $("#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();
        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];
        $("#character").prop('src', Utils.Path + "images/skin/Graphic_Wrong-ANS.png");
        document.getElementById('playSound').play();

    }
    if (wrongCnt == 2 || correctCnt == Grammar.wordsArr.length) {
        $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $("#nextDiv").addClass("blink_me");
        $("#gamePage").css("pointer-events", "none");
    }
}

function onDrop(event, ui) {
    var wordType;
    Grammar.attemptFlag = true;
    Grammar.skipFlag = false;
    for (var i = 0; i < Grammar.wordsArr.length; i++) //find word 
    {
        if ($(ui.draggable).text().trim() == Grammar.wordsArr[i].word) {
            wordType = Grammar.wordsArr[i].type; //get type of word
            break;
        }
    }
    if (wordType == $(this).data("data")) //check word dropped in correct box 
    {
        correctCnt++;
        if (wordType == Grammar.typeArr[0].data) //decrease counter accordingly
            nounCnt--
            else if (wordType == Grammar.typeArr[1].data)
                pronounCnt--
                else
                    adjectiveCnt--
                    $(this).append(ui.draggable.clone());
        $(ui.draggable).draggable("disable");
        $(ui.draggable).css("opacity", "0.5");
        var mybr = document.createElement('br');
        $(this).append(mybr);
        $(ui.draggable).draggable("option", "revert", false);
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Grammar.correctAns;
        document.getElementById('playSound').play();
        if (correctCnt == Grammar.wordsArr.length) //check total length
        {
            if (Grammar.nextBounce) {
				clearTimeout(Grammar.nextBounce);
				Grammar.nextBounce = null;
			}
			Grammar.nextBounce = setTimeout(function() {
                $("#gamePage,#checkDiv,#soundDiv").css("pointer-events", "none");
                $("#nextDiv").addClass("blink_me");
            }, 500);
        }
    } else {
        $(ui.draggable).draggable("option", "revert", true);
        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
    document.getElementById('playSound').pause();
    clearTimeout(Grammar.nextBounce);
    Grammar.skipedQ++;
    $("#gamePage,#checkDiv,#soundDiv").css("pointer-events", "auto");
    $("#nextDiv").removeClass("blink_me");
    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 (correctWordArr.length > 0) {
            for (var i = 0; i < correctWordArr.length; i++) {
                console.log(correctWordArr[i], Grammar.data[0].list.length, gameType);
            }
        }
        //console.log(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word, 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);
                }
            }

        }

    }

}
Grammar.showCredit = function() {
    $("#acknowledgementDiv").show();
}

function allowDrop(event) {
    event.preventDefault();
}
Grammar.showWords = function(showAnswerArr, i) { //show words in respective boxes
    for (var j = 0; j < 3; j++) {
        if (showAnswerArr[i].type == Grammar.typeArr[j].data) {
            $("#column" + j).children()[1].append(spanEle)
            var mybr = document.createElement('br');
            $("#column" + j).children()[1].append(mybr);
            break;
        }
    }
}