//29th August 2019
var Composition = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    resId = 0,
    totalMarks = 10,
    wrongCnt = 0,
    totalLength = 0,
    correctCnt = 0,
    quesCnt = 0,
    type = "sentence";
Composition.questionArr = []; //5 question Array
Composition.quesSplitArr = []; //correct english text splitted array
Composition.skipFlag = true; //Q skipped flag
Composition.attemptFlag = false; //Q attempt flag
Composition.levelName = false; //false for learn & true for practice
Composition.hideShowHelp = false; //help toggle  button
Composition.takeHelp = false;
//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,#endpage,#homeImg,#widgetDiv,#robotDiv").hide();
        $("#playGame").addClass("animated rotateInUpLeft");
        $("#coverpage").show();
        Composition.setImages();
    }, 300);
});
Composition.setImages = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + Composition.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");
    $("#sound").prop('src', Utils.Path + "images/skin/Sound.png");
    $("#checkImg").prop('src', Utils.Path + "images/skin/check.png");
    $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
    $("#acknowledgementDiv").css("backgroundImage", "url(" + Utils.Path + "images/skin/text_box.png");
    $("#questionDiv").css("backgroundImage", "url(" + Utils.Path + "images/skin/text_box.png");
}
Composition.playGame = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
    $("#homeImg,#gamepage,#widgetDiv,#robotDiv").show();

    $("#coverpage").hide();
    if (Utils.mobileDeviceFlag)
        Composition.levelName = Android.isPractice();
    if (Composition.levelName)
        $("#helpImg").css("visibility", "hidden");
    else
        $("#helpImg").css("visibility", "visible");
    Composition.questionArr = populate(Composition.data, Composition.questionArr, 5);
    Composition.createOptionDivs(modalDiv);
    Composition.showSentence();
    Composition.playInstruction();
}
Composition.createOptionDivs = function(parentDiv) { //modal options
    var optionDiv;
    for (var i = 0; i < 3; i++) {
        optionDiv = document.createElement("div");
        optionDiv.setAttribute("id", 'optionDiv' + i);
        optionDiv.setAttribute("class", 'noPadding borderClass col-lg-12 col-md-12 col-xs-12 col-sm-12');
        optionDiv.setAttribute("onclick", 'Composition.setWord(this)');
        $(optionDiv).css("backgroundImage", "url(" + Utils.Path + "images/skin/option_box.png)");
        parentDiv.appendChild(optionDiv)
    }
}

Composition.showSentence = function() { //shows hindi & english text on screen
    $("#hindiTextDiv,#englishWrongTextDiv,#acknowledgementDiv").text('');
    $(".roboImg").hide();
    $("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
    $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
    $("#robotImg1").show();
    $("#helpDiv,#soundDiv,#checkDiv,#nextDiv").addClass("animated rotateInUpLeft");
    $("#message").css("visibility", "hidden");
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Composition.skipFlag = true;
    var engSentence = Composition.data[Composition.questionArr[quesCnt]].sentence.replace(' .', '.');
    Composition.quesSplitArr = engSentence.split(' ');
    Composition.hindiSplitArr = Composition.data[Composition.questionArr[quesCnt]].lang_sentence.split(' ');
    $("#englishWrongTextDiv").children().css("color", "white");
    Composition.createHindiSentence(hindiTextDiv, Composition.hindiSplitArr.length);
    Composition.createEnglishSentence(englishWrongTextDiv, Composition.quesSplitArr.length);
    if (Composition.showRobot) {
        Composition.showRobot = null;
        clearInterval(Composition.showRobot);
    }
    Composition.showRobot = setInterval(function() {
        var randomRobot = Math.floor(Math.random() * 2) + 1;
        $(".roboImg").hide();
        $("#robotImg" + randomRobot).show();
    }, 3000);

}

Composition.createHindiSentence = function(parentDiv, length) { //create hindi word span
    var span;
    for (var j = 0; j < length;) {
        var wordFoundFlag = false;
        span = document.createElement("span");
        for (var k = 0; k < Composition.data[Composition.questionArr[quesCnt]].list.length; k++) {
            var tempArr = [];
            tempArr = Composition.data[Composition.questionArr[quesCnt]].list[k].correctWord.trim().split(' ');
            if (tempArr.includes(Composition.hindiSplitArr[j])) {
                $(span).text(Composition.data[Composition.questionArr[quesCnt]].list[k].correctWord.trim() + " ");
                wordFoundFlag = true;
                j = j + tempArr.length;
                break;
            }
        }
        if (wordFoundFlag == false) {
            $(span).text(Composition.hindiSplitArr[j] + " ");
            $(span).data("value", Composition.hindiSplitArr[j]);
            j++;
        }
        parentDiv.appendChild(span);
    }
}
Composition.createEnglishSentence = function(parentDiv, length) { //create english word span
    var span, wCnt = 0,
        sentenceCnt = 0;
    loop1:
        for (var j = 0; j < length;) {
            var wordFoundFlag = false;
            wCnt = 0;
            span = document.createElement("span");
            span.setAttribute("id", 'span' + j);
            loop2:
                for (var k = sentenceCnt; k < Composition.data[Composition.questionArr[quesCnt]].list.length; k++) {
                    var tempArr = [];
                    var correctLang = Composition.data[Composition.questionArr[quesCnt]].list[k].correctLang.replace(' .', '.');
                    tempArr = correctLang.trim().split(' ');
                    loop3:
                        for (var i = 0; i < tempArr.length; i++) {
                            if (tempArr.includes(Composition.quesSplitArr[j])) {
                                wordFoundFlag = true;
                                wCnt++;
                                j++;
                            } else
                                wordFoundFlag = false;
                            if (wCnt == tempArr.length) {
                                var randomOption = Math.floor(Math.random() * Composition.data[Composition.questionArr[quesCnt]].list[k].option.length);
                                var option = Composition.data[Composition.questionArr[quesCnt]].list[k].option[randomOption].replace(' .', '.');
                                $(span).text(option.trim() + " ");
                                $(span).data("originalValue", option.trim());
                                var correctOption = Composition.data[Composition.questionArr[quesCnt]].list[k].correctLang.replace(' .', '.');
                                $(span).data("value", correctOption.trim());
                                wordFoundFlag = true;
                                span.setAttribute("onclick", "Composition.showOptions(this)");
                                $(span).css('color', 'cyan');
                                sentenceCnt++;
                                break loop2;
                            }
                        }
                }
            if (wordFoundFlag == false) {
                if (wCnt != 0)
                    j = j - wCnt;
                $(span).text(Composition.quesSplitArr[j] + " ");
                $(span).data("value", Composition.quesSplitArr[j]);
                $(span).data("originalValue", Composition.quesSplitArr[j]);
                $(span).data("colorValue", 'white');
                j++;
            }
            parentDiv.appendChild(span);
        }
    questionId = Composition.data[Composition.questionArr[quesCnt]].questionId;
}
Composition.showOptions = function(element) { //show options in modal 
    var optionArr = [],
        wordCnt = 0;
    $("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
    document.getElementById('playSound').play();
    Composition.attemptFlag = true;
    Composition.skipFlag = false;
    Composition.closeModal();
    optionArr.push($(element).data("value"));
    for (var i = 0; i < Composition.data[Composition.questionArr[quesCnt]].list.length; i++) {
        var correctOption = Composition.data[Composition.questionArr[quesCnt]].list[i].correctLang.replace(' .', '.');
        if ($(element).data("value") == correctOption.trim()) {
            for (var k = 0; k < $("#hindiTextDiv").children().length; k++) {
                if ($($("#hindiTextDiv").children()[k]).text().trim().includes(Composition.data[Composition.questionArr[quesCnt]].list[i].correctWord.trim())) {
                    $($("#hindiTextDiv").children()[k]).css('color', '#eff00f');
                    break;
                }
            }
            for (var j = 0; j < Composition.data[Composition.questionArr[quesCnt]].list[i].option.length; j++)
                optionArr.push(Composition.data[Composition.questionArr[quesCnt]].list[i].option[j].trim())
            break;
        }
    }
    shuffleArray(optionArr)
    for (var i = 0; i < 3; i++) {
        var opt = optionArr[wordCnt].replace(' .', '.');
        $('#optionDiv' + i).text(opt);
        wordCnt++;
    }
    if (Composition.showModal) {
        clearTimeout(Composition.showModal);
        Composition.showModal = null;
    }
    Composition.showModal = setTimeout(function() {
        $("#modalRoot").addClass("slideInDownCls");
        $("#modalRoot").show();
    }, 50);
    Composition.clickedWord = $(element);
    $(element).css('color', '#eff00f');
}
Composition.setWord = function(element) { //set selected option to sentence
    document.getElementById('playSound').pause();
    /* 	document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
    	document.getElementById('playSound').play(); */
    Composition.clickedWord.text($(element).text() + " ");
    $(".borderClass").css("color", "white");
    $(element).css("color", "yellow");
}
Composition.closeModal = function() { //close modal
    $("#modalRoot").removeClass("slideInDownCls");
    $(".modal").hide();
    $(".borderClass").css("color", "white");
    $(Composition.clickedWord).css('color', 'cyan');
    $("#hindiTextDiv").children().css("color", "white");
}
Composition.playInstruction = function() { // plays sound of instruction/options
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Composition.hardcoded.instruction;
    document.getElementById('playSound').play();
}
Composition.checkAnswer = function() { //check answer
    document.getElementById('playSound').pause();
    clearInterval(Composition.showRobot);
    Composition.closeModal();
    $("#helpDiv,#soundDiv,#checkDiv,#nextDiv").removeClass("animated rotateInUpLeft");
    $(".roboImg").hide();
    Composition.skipFlag = false;
    Composition.attemptFlag = true;
    if (wrongCnt == 0)
        scoredMarks = 10;
    else if (wrongCnt == 1)
        scoredMarks = 5;
    else if (wrongCnt == 2)
        scoredMarks = 1;
    else
        scoredMarks = 0;
    if (Composition.takeHelp) {
        scoredMarks = 0;
        wrongCnt = 0;
    }

    correctWordCntr = 0;
    for (var i = 0; i < Composition.quesSplitArr.length; i++) { //count total correct keywords
        if ($($("#englishWrongTextDiv").children()[i]).data("value") != null)
            if ($($("#englishWrongTextDiv").children()[i]).data("value") == $($("#englishWrongTextDiv").children()[i]).text().trim())
                correctWordCntr++;
            else {
                $($("#englishWrongTextDiv").children()[i]).css("color", "#790606");
            }
    }
    if (correctWordCntr == $("#englishWrongTextDiv").children().length) {
        correctCnt++;
        $("#englishWrongTextDiv").children().css({ "color": "#0bf50b", "pointer-events": "none" });
        //$("#helpDiv").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $(".opacityCls,#helpDiv").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $("#gamepage").css("pointer-events", "none");
        $("#nextDiv").addClass("bounceCls");
        $("#englishWrongTextDiv").addClass('animated zoomIn');
        document.getElementById('playSound').src = Utils.Path + 'sounds/' + Composition.data[Composition.questionArr[quesCnt]].sound;
        document.getElementById('playSound').play();

        $("#robotImg2").prop('src', Utils.Path + "images/skin/robo-happy.gif");
        $("#robotImg2").show();
        console.log(Composition.data[Composition.questionArr[quesCnt]].sentence, Composition.data.length, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(Composition.data[Composition.questionArr[quesCnt]].sentence, Composition.data.length, type);
        Composition.calculateScore();

    } else {
        wrongCnt++;
        var random = Math.floor(Math.random() * Composition.wrongAns.length)
        if (wrongCnt == 3) {
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
            $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
            $("#gamepage").css("pointer-events", "none");
            $("#nextDiv").addClass("bounceCls");
        } else
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Composition.wrongAns[random];
        document.getElementById('playSound').play();
        $("#robotImg1").prop('src', Utils.Path + "images/skin/robo-sad.gif");
        $("#robotImg1").show();
    }

}
Composition.nextQuestion = function() { //Loads Next Question
    clearTimeout(Composition.showModal);
    $(".opacityCls,#helpDiv").css({ 'opacity': '1', 'pointer-events': 'auto' });
    $("#gamepage").css("pointer-events", "auto");
    $("#helpDiv").removeClass('pulse_me');
    $("#modalRoot").hide();
    Composition.hideShowHelp = false;
    Composition.takeHelp = false;
    $("#helpDiv,#soundDiv,#checkDiv,#nextDiv").removeClass("animated rotateInUpLeft bounceCls");
    clearInterval(Composition.showRobot);
    if (Composition.attemptFlag) {
        scoredMarks = 0;
        Composition.attemptFlag = false;
        Composition.calculateScore();
    }
    if (Composition.skipFlag) {
        scoredMarks = -1;
        Composition.calculateScore();
    }
    wrongCnt = 0;
    correctCnt = 0;
    quesCnt++;
    document.getElementById('playSound').pause();
    $("#checkDiv").show();
    $("#englishWrongTextDiv").removeClass('animated zoomIn');
    $("#englishWrongTextDiv").css('box-shadow', 'none');
    clearTimeout(Composition.nextQTimer);
    if (quesCnt == 5) {
        document.getElementById('playSound').pause();
        $("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
        $('#endpage').show();
        $('#gamepage,#acknowledgementDiv,#widgetDiv').hide();
        $("#message").text(Composition.hardcoded.gameOver);
        $("#message").css("visibility", "visible");
        Composition.createHardcodeddivs();
    } else
        Composition.showSentence();
}
Composition.createHardcodeddivs = function() { //acknowledgement Divs
    var ackDiv;
    for (var i = 0; i < Object.keys(Composition.acknowledgementData).length; i++) {
        ackDiv = document.createElement("div");
        ackDiv.setAttribute("id", "ack" + i);
        ackDiv.setAttribute("class", "noPadding  text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
        ackDiv.innerHTML = Object.keys(Composition.acknowledgementData)[i] + " : " + Object.values(Composition.acknowledgementData)[i];
        document.getElementById("acknowledgementDiv").appendChild(ackDiv);
    }
    div = document.createElement('div');
    div.className = "noPadding fontClass  text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = Composition.hardcoded['createdOn'];
    document.getElementById("acknowledgementDiv").appendChild(div);
}
Composition.callHome = function() { //home click
    if (Composition.attemptFlag) {
        scoredMarks = 0;
        Composition.attemptFlag = false;
        Composition.calculateScore();
    }
    location.reload(true);
}
Composition.playAgain = function() { //plays game one more time
    Composition.resetAll();
    $(".borderClass").removeClass("slideInDownCls animated zoomIn");
    $("#modalRoot").removeClass("slideInDownCls");
    $("#message").css("visibility", "visible");
    $("#endpage").hide();
    $("#gamepage,#widgetDiv").show();
    Composition.questionArr = populate(Composition.data, Composition.questionArr, 5);
    Composition.showSentence();
}
Composition.resetAll = function() {
    wrongCnt = 0;
    correctCnt = 0;
    quesCnt = 0;
    Composition.questionArr = [];
    document.getElementById('playSound').pause();
    $("#helpDiv").removeClass('pulse_me');
    Composition.skipFlag = true;
    Composition.hideShowHelp = false;
    Composition.takeHelp = false;
    clearTimeout(Composition.nextQ);
}
Composition.calculateScore = function() {
    Composition.attemptFlag = false;
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Composition.data[Composition.questionArr[quesCnt]].sentence);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Composition.data[Composition.questionArr[quesCnt]].sentence);
}
Composition.showCredit = function() {
    $("#acknowledgementDiv").show();
}
Composition.showHelp = function() { //show correct answer
    $("#helpDiv").css({ 'pointer-events': 'auto' });
    Composition.closeModal();
    $("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
    $("#helpDiv").removeClass('pulse_me');
    if (Composition.hideShowHelp == false) {
        Composition.hideShowHelp = true;
        Composition.takeHelp = true;
        //$("#helpDiv").addClass('pulse_me');
        //$("#helpDiv").css({ 'opacity': '0.5' });
        $("#helpImg").prop('src', Utils.Path + "images/skin/hideHelp.png");
        $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $("#checkDiv").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $("#helpDiv,#soundDiv,#checkDiv,#nextDiv").removeClass("animated rotateInUpLeft");
        Composition.attemptFlag = true;
        Composition.skipFlag = false;
        $("#gamepage").css("pointer-events", "none");
        //$("#nextDiv").addClass("blink_me");
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/' + Composition.data[Composition.questionArr[quesCnt]].sound;
        document.getElementById('playSound').play();
        clearTimeout(Composition.nextQTimer);
        for (var i = 0; i < $("#englishWrongTextDiv").children().length; i++) {
            if ($($("#englishWrongTextDiv").children()[i]).data("value") != null)
                $($("#englishWrongTextDiv").children()[i]).text($($("#englishWrongTextDiv").children()[i]).data("value") + " ");
            $($("#englishWrongTextDiv").children()[i]).css({ 'pointer-events': 'none', 'color': '#0bf50b', 'font-weight': 'bold' });
        }
        $("#englishWrongTextDiv").addClass('animated zoomIn');
    } else if (Composition.hideShowHelp == true) {
        Composition.hideShowHelp = false;
        document.getElementById('playSound').pause();
        $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
        $("#helpDiv").css({ 'opacity': '1' });
        $(".opacityCls").css({ 'opacity': '1', 'pointer-events': 'auto' });
        $("#gamepage").css("pointer-events", "auto");
        $("#checkDiv").css({ 'opacity': '1', 'pointer-events': 'auto' });
        for (var i = 0; i < $("#englishWrongTextDiv").children().length; i++) {
            $($("#englishWrongTextDiv").children()[i]).text($($("#englishWrongTextDiv").children()[i]).data("originalValue") + " ");
            if ($($("#englishWrongTextDiv").children()[i]).data("colorValue") == 'white')
                $($("#englishWrongTextDiv").children()[i]).css({ 'pointer-events': 'auto', 'color': 'white', 'font-weight': 'bold' });
            else
                $($("#englishWrongTextDiv").children()[i]).css({ 'pointer-events': 'auto', 'color': 'cyan', 'font-weight': 'bold' });
        }
        $("#englishWrongTextDiv").removeClass('animated zoomIn');
    }
}