//22Aug 2019
var Aksharkhel = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0,
    wrongCnt = 0,
    correctCnt = 0,
    attemptCnt = 0,
    type = "word";
Aksharkhel.marks = 0;
Aksharkhel.attemptFlag = false;
Aksharkhel.skipFlag = true;
Aksharkhel.levelName = false; //false for learn & true for practice
Aksharkhel.hideShowHelp = false; //help toggle  button
Aksharkhel.takeHelp = false;
Aksharkhel.goBackFlag = "instruction";
$(document).ready(function () {
    $('title').text(Aksharkhel.GameName)
    $(".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("Aksharkhel");  */
    setTimeout(function() {
        Aksharkhel.init();
        if (Aksharkhel.hardCodedData['languageFont'] != null)
            setFontFamilyForLang("fonts/" + Aksharkhel.hardCodedData['languageFont']);
    }, 200);
});

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");
}

//runs @onload of body.sets the homepage of game. 
Aksharkhel.init = function() {
    Aksharkhel.setAllImage();
    if (Utils.mobileDeviceFlag)
        Aksharkhel.levelName = Android.isPractice();
    if (Aksharkhel.levelName)
        $("#helpImg").css("visibility", "hidden");
    else
        $("#helpImg").css("visibility", "visible");
    Aksharkhel.initializeVariables();
    $("#home").css("visibility", "hidden");
    $("#gamePage,#resultDiv").hide();
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/" + Aksharkhel.hardCodedData.coverImage + ")";
    $("#quesInstruction").text(Aksharkhel.hardCodedData.instruct);
    Aksharkhel.createAcknowledgement();
}

Aksharkhel.initializeVariables = function() {
    Aksharkhel.noOfKanaMatra = 0;
    Aksharkhel.wordArray = []; //splitted word
    Aksharkhel.numOfQuestion = 0; //number of questions Cnt
    correctCnt = 0;
    Aksharkhel.dataArray = []; //Random 5 unique question
    Aksharkhel.loadmetaDataFlag = false;
    Aksharkhel.attemptFlag = false;
}

Aksharkhel.createAcknowledgement = function() {
        var i = 0,
            div;
        $("#acknowledgementDiv").empty();
        for (i = 0; i < Object.keys(Aksharkhel.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(Aksharkhel.AcknowledgementPageData)[i] + " : " + Object.values(Aksharkhel.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 = Aksharkhel.hardCodedData['createdDate'];
        div.style.marginBottom = "2vh";
        acknowledgementDiv.appendChild(div);
    }
    //sets Images	
Aksharkhel.setAllImage = function() {
    $("#homeLogo").prop('src', Utils.Path + "images/skin/Home_button.png");
    $("#logo").prop('src', Utils.Path + "images/skin/logo.png");
    $("#play").prop('src', Utils.Path + "images/skin/playButton.png");
    $("#nextBtnImg").prop('src', Utils.Path + "images/skin/playButton.png");
    $("#next").prop('src', Utils.Path + "images/skin/Next_button.png");
    $("#sound").prop('src', Utils.Path + "images/skin/Sound_button.png");
    $("#replay").prop('src', Utils.Path + "images/skin/playAgain.png");
    $("#creditImg").prop('src', Utils.Path + "images/skin/credit.png");
    $("#checkImg").prop('src', Utils.Path + "images/skin/Done.png");
    $("#clearImg").prop('src', Utils.Path + "images/skin/playAgain.png");
    $("#imageAndLetter").css("backgroundImage", "url(" + Utils.Path + "images/skin/Top_image.png)");
    $("#outerDiv").css("backgroundImage", "url(" + Utils.Path + "images/skin/Bottom_image.png)");
    $("#letterOuterDiv").css("backgroundImage", "url(" + Utils.Path + "images/skin/Image_box.png");
    $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
}

//onclick of play button
Aksharkhel.startGame = function() {
    Aksharkhel.goBackFlag = "reload";
    Aksharkhel.hideShowHelp = false;

    $("#playButton,#gamePage,#resultDiv").hide();
    document.getElementById("playSound").pause();
    $("#letterDiv").removeClass('zoomIn');
    $("#home").css("visibility", "visible");
    $("#quesInstruction").css("visibility", "hidden");
    $("#nextDiv").removeClass("bounceCls");
    $(".opacityCls,#soundDiv,#helpDiv").css({ 'opacity': '1', 'pointer-events': 'auto' });
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Bg.png)";
    document.getElementById("options").innerHTML = "";
    Aksharkhel.showInstruction();
    Aksharkhel.createOptionDivs();
}
Aksharkhel.playInstruction = function() {
        document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + Aksharkhel.hardCodedData.instructionSound;
        document.getElementById("playSound").play();
    }
    //shows the instuction page
Aksharkhel.showInstruction = function() {
    $("#instructionDiv").show();
    Aksharkhel.playInstruction();
    $('#heading').text(Aksharkhel.hardCodedData.heading);
    document.getElementById('text').innerHTML = Aksharkhel.hardCodedData.instructions[0];
}

//create matra divs
Aksharkhel.createOptionDivs = function() {
    var matra, matraRow, cnt = 5,
        matraCnt = 0;

    parentDiv = document.getElementById("options");
    for (var i = 0; i < 3; i++) {
        matraRow = document.createElement("div");
        matraRow.setAttribute("id", "matraRow" + i);
        matraRow.setAttribute("class", "zeroPadding col-sm-11 col-lg-11 col-md-11 col-xs-11");
        $(matraRow).css({ 'display': 'flex', 'justify-content': 'center' });
        $("#matraDiv").append(matraRow);
        if (i != 0)
            cnt = 4;
        for (var j = 0; j < cnt; j++) {
            if (matraCnt < Aksharkhel.KanaMatraArr.length) {
                optionDiv = document.createElement('span');
                optionDiv.setAttribute('id', 'optionDiv' + matraCnt);
                optionDiv.setAttribute('class', 'optionDiv zeroPadding col-sm-2 col-lg-2 col-md-2 col-xs-2');
                optionDiv.setAttribute("onclick", "Aksharkhel.makeWord(this.id)");
                optionDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/blank_button.png";

                optionSpan = document.createElement('span');
                optionSpan.setAttribute('id', 'optionSpan' + matraCnt);
                optionSpan.setAttribute('class', 'optionSpan');
                optionSpan.innerHTML = Aksharkhel.KanaMatraArr[matraCnt];
                matraRow.append(optionDiv);
                optionDiv.append(optionSpan);
                matraCnt++;
            }
        }
        parentDiv.append(matraRow);
    }
}

//resets the gamepage.
Aksharkhel.resetAll = function() {
        Aksharkhel.splitArray = [];
        correctCnt = 0;
        Aksharkhel.numOfQuestion = 0;
        Aksharkhel.takeHelp = false;
        Aksharkhel.goBackFlag = "instruction";
        document.getElementById("playSound").pause();
        document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Bg.png)";
        $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
        $("#home,#quesInstruction").css("visibility", "visible");
        $("#resultDiv,#playButton").hide();
        $("#gamePage").show();
        $("#helpDiv").removeClass('pulse_me');
        if (Aksharkhel.skipFlag == false)
            Aksharkhel.marks += scoredMarks;
        //document.getElementById("scoreSpan").innerHTML = Aksharkhel.hardCodedData.marks + Aksharkhel.marks;
        Aksharkhel.marks = 0;
        document.getElementById("instructionDiv").style.display = "none";
        $("#acknowledgementDiv").css("visibility", "hidden");
        Aksharkhel.createArray();
        Aksharkhel.playGame();
    }
    //creates array 5 unique indexes for setting the question images.
Aksharkhel.createArray = function() {
    var i, rNo;
    Aksharkhel.dataArray = [];
    for (i = 0; i < 5; i++) {
        rNo = Math.floor(Math.random() * (Aksharkhel.Data.length));
        if (Aksharkhel.dataArray.includes(Aksharkhel.Data[rNo])) {
            i--;
            continue;
        } else
            Aksharkhel.dataArray.push(Aksharkhel.Data[rNo]);
    }
}

//runs @ onclick of next button on homepage sets gamepage of game.  
Aksharkhel.playGame = function() {
        var d;
        Aksharkhel.attemptFlag = false;
        Aksharkhel.skipFlag = true;
        $("#instructDiv").css("visibility", "visible");
        clearTimeout(Aksharkhel.nextQuestionTimeout);
        d = new Date();
        startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        Aksharkhel.numOfQuestion++;
        //document.getElementById("scoreSpan").innerHTML = Aksharkhel.hardCodedData.marks + Aksharkhel.marks;
        if (Aksharkhel.numOfQuestion > 5) {

            Aksharkhel.endGame();
        } else {

            Aksharkhel.noOfKanaMatra = 0;
            scoredMarks = 0;
            wrongCnt = 0;
            attemptCnt = 0;
            $(".optionDiv").css("pointer-events", "none");
            $("#soundDiv").css("pointer-events", "auto");
            //document.getElementById("options").style.pointerEvents = "auto";
            $("#nextDiv").css("visibility", "visible");
            Aksharkhel.setQuestion();
            Aksharkhel.playSound();
        }
    }
    //runs @ onclick of sound button, plays the sound of image. 	
Aksharkhel.playSound = function() {
        document.getElementById("playSound").src = Utils.Path + "sounds/" + Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].Sounds;
        document.getElementById("playSound").play();
    }
    //displays the score.
Aksharkhel.endGame = function() {
        Aksharkhel.goBackFlag = "reload";
        document.getElementById("playSound").pause();
        $("#gamePage").hide();
        $("#resultDiv,#replay").show();
        $("#quesInstruction").css("visibility", "hidden");
        $(".optionDiv").css("pointer-events", "auto");
        document.getElementById("final").innerHTML = Aksharkhel.hardCodedData.word;
        //document.getElementById("score").innerHTML = Aksharkhel.hardCodedData.marks + Aksharkhel.marks;
    }
    //called from Aksharkhel.playgame and  Aksharkhel.reset function.creates dynamic divs for the images
Aksharkhel.setQuestion = function() {
    var word, spanDiv, span, i, j;
    word = Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word;
    console.log(word);
    Aksharkhel.wordArray = word.split("");

    for (i = 0; i < Aksharkhel.wordArray.length; i++) {
        if (Aksharkhel.KanaMatraArr.includes(Aksharkhel.wordArray[i])) {
            Aksharkhel.wordArray.splice(i, 1); //word without kanamatra.
            i--;
            Aksharkhel.noOfKanaMatra++;
        }
        if (i > 0 && ((Aksharkhel.wordArray[i - 1] == "ज" && Aksharkhel.wordArray[i] == "्" && Aksharkhel.wordArray[i + 1] == "ञ") || (Aksharkhel.wordArray[i - 1] == "क" && Aksharkhel.wordArray[i] == "्" && Aksharkhel.wordArray[i + 1] == "ष") || (Aksharkhel.wordArray[i - 1] == "त" && Aksharkhel.wordArray[i] == "्" && Aksharkhel.wordArray[i + 1] == "र"))) {
            Aksharkhel.wordArray[i - 1] = Aksharkhel.wordArray[i - 1] + Aksharkhel.wordArray[i] + Aksharkhel.wordArray[i + 1];
            Aksharkhel.wordArray.splice(i, 2);
            i -= 2;
        }
    }
    Aksharkhel.splitArray = word.split("");
    for (i = 0; i < Aksharkhel.splitArray.length; i++) {
        if (Aksharkhel.KanaMatraArr.includes(Aksharkhel.splitArray[i])) {
            Aksharkhel.splitArray[i - 1] = Aksharkhel.splitArray[i - 1] + Aksharkhel.splitArray[i];
            if (Aksharkhel.splitArray[i] == "्" || Aksharkhel.splitArray[i] == "ँ")
                Aksharkhel.indexMain = [i];
            Aksharkhel.splitArray.splice(i, 1); //word with kanamatra. 
            i--;
        }
        if (i > 0 && ((Aksharkhel.splitArray[i - 1] == "ज" && Aksharkhel.splitArray[i] == "्" && Aksharkhel.splitArray[i + 1] == "ञ") || (Aksharkhel.splitArray[i - 1] == "क" && Aksharkhel.splitArray[i] == "्" && Aksharkhel.splitArray[i + 1] == "ष") || (Aksharkhel.splitArray[i - 1] == "त" && Aksharkhel.splitArray[i] == "्" && Aksharkhel.splitArray[i + 1] == "र"))) {
            Aksharkhel.splitArray[i - 1] = Aksharkhel.splitArray[i - 1] + Aksharkhel.splitArray[i] + Aksharkhel.splitArray[i + 1];
            Aksharkhel.splitArray.splice(i, 2);
            i--;
            //break;
        }
    }
    spanDiv = document.getElementById("letterDiv");
    $("#letterDiv").empty();
    for (j = 0; j < Aksharkhel.wordArray.length; j++) {
        span = document.createElement("SPAN");
        span.setAttribute("id", "span" + j);
        span.setAttribute("class", "wordSpan");
        span.innerHTML = Aksharkhel.wordArray[j];
        span.setAttribute("onclick", "Aksharkhel.getLetter(this.id);");
        spanDiv.appendChild(span);
    }
}

//Runs @ onclick of letter displayed on typewriter.stores the clicked letter.
Aksharkhel.getLetter = function(letter) {
        Aksharkhel.attemptFlag = true;
        Aksharkhel.skipFlag = false;

        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
        document.getElementById('playSound').play();
        Aksharkhel.letterDiv = document.getElementById(letter);
        $(".wordSpan").css("color", "black");
        Aksharkhel.letterDiv.style.color = "#d42a78";
        $(".optionDiv").css("pointer-events", "auto");
    }
    //Runs @ onclick of letter from option 
Aksharkhel.makeWord = function(letterId) {
    Aksharkhel.attemptFlag = true;
    Aksharkhel.skipFlag = false;
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
    document.getElementById('playSound').play();
    //$("#" + Aksharkhel.letterDiv.id).append($("#" + letterId).children().text())
    $("#" + Aksharkhel.letterDiv.id).text($("#" + Aksharkhel.letterDiv.id).text().split('')[0]);
    $("#" + Aksharkhel.letterDiv.id).text($("#" + Aksharkhel.letterDiv.id).text().concat($("#" + letterId).children().text()));
}

Aksharkhel.checkAnswer = function(letterId) {
        var randomSound;
        Aksharkhel.attemptFlag = true;
        Aksharkhel.skipFlag = false;
        Aksharkhel.letterDiv = '';
        if (wrongCnt == 0)
            scoredMarks = 10;
        else if (wrongCnt == 1)
            scoredMarks = 5;
        if (Aksharkhel.takeHelp) {
            scoredMarks = 0;
            wrongCnt = 0;
        }
        if ($("#letterDiv").children().text() == Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word) {
            correctCnt++;
            attemptCnt++;
            Aksharkhel.attemptFlag = false;
            $("#letterDiv").children().css({ 'color': 'green', 'pointer-events': 'none' });
            $(".opacityCls,#helpDiv").css({ 'opacity': '0.5', 'pointer-events': 'none' });
            $(".optionDiv,.wordSpan").css("pointer-events", "none");
            randomSound = Math.floor(Math.random() * (Aksharkhel.correctAns.length));
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Aksharkhel.correctAns[randomSound];
            document.getElementById('playSound').play();
            $("#nextDiv").addClass("bounceCls");
            if (Aksharkhel.skipFlag == false)
                Aksharkhel.marks += scoredMarks;
            //document.getElementById("scoreSpan").innerHTML = Aksharkhel.hardCodedData.marks + Aksharkhel.marks;
            console.log(Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word, Aksharkhel.Data.length, type);
            if (Utils.mobileDeviceFlag)
                Android.addLearntData(Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word, Aksharkhel.Data.length, type);
            Aksharkhel.calculateScore();
        } else {
            wrongCnt++;
            scoredMarks = 0;
            $("#letterDiv").children().css({ 'color': 'red' });
            $(".optionDiv,.wordSpan").css("pointer-events", "none");
            setTimeout(function() {
                $("#letterDiv").children().css({ 'color': 'black' });
                if (wrongCnt != 2)
                    $(".optionDiv,.wordSpan").css("pointer-events", "auto");
            }, 1000);
            randomSound = Math.floor(Math.random() * (Aksharkhel.wrongAns.length));
            if (wrongCnt == 2)
                document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
            else
                document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Aksharkhel.wrongAns[randomSound];
            document.getElementById('playSound').play();
        }
        if (wrongCnt == 2 || attemptCnt == 1) {
            $(".opacityCls,#soundDiv").css({ 'opacity': '0.5', 'pointer-events': 'none' });
            $("span").css("pointer-events", "none");
            $("#nextDiv").addClass("bounceCls");
        }
    }
    //runs when user clicks next button wijthout attempting question.
Aksharkhel.showNextQuestion = function() {
    $("#letterDiv").removeClass('zoomIn');
    Aksharkhel.letterDiv = '';
    document.getElementById("playSound").pause();
    $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
    $(".opacityCls,#soundDiv,#helpDiv").css({ 'opacity': '1', 'pointer-events': 'auto' });
    $(".optionDiv,.wordSpan").css("pointer-events", "none");
    $("#nextDiv").removeClass("bounceCls");
    $("#helpDiv").removeClass('pulse_me');
    Aksharkhel.hideShowHelp = false;
    Aksharkhel.takeHelp = false;
    if (Aksharkhel.attemptFlag) {
        scoredMarks = 0;
        Aksharkhel.attemptFlag = false;
        Aksharkhel.calculateScore();
    }
    if (Aksharkhel.skipFlag) {
        scoredMarks = -1;
        Aksharkhel.calculateScore();
    }
    wrongCnt = 0;
    attemptCnt = 0;
    Aksharkhel.playGame();
}
Aksharkhel.clearWord = function() {
        $(".optionDiv").css("pointer-events", "none");
        for (j = 0; j < Aksharkhel.wordArray.length; j++)
            $("#span" + j).text(Aksharkhel.wordArray[j]);
        $(".wordSpan").css('color', 'black');
    }
    //displays acknowledgement.
Aksharkhel.showAcknowlwdgement = function() {
    $("#acknowledgementDiv").css("visibility", "visible");
}
Aksharkhel.calculateScore = function() {
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word);
}
Aksharkhel.callHome = function() {
    if (Aksharkhel.attemptFlag) {
        scoredMarks = 0;
        Aksharkhel.attemptFlag = false;
        Aksharkhel.calculateScore();
    }
    if (Aksharkhel.goBackFlag == "instruction") {
        Aksharkhel.initializeVariables();
        Aksharkhel.startGame();
    } else
        location.reload(true);
}
Aksharkhel.showHelp = function() {
    $("#helpDiv").css({ 'pointer-events': 'auto' });
    document.getElementById("playSound").pause();
    $("#robotImg1,#robotImg2").prop('src', Utils.Path + "images/skin/roboStand.png");
    $("#helpDiv").removeClass('pulse_me');
    if (Aksharkhel.hideShowHelp == false) {
        Aksharkhel.hideShowHelp = true;
        Aksharkhel.takeHelp = true;
        $("#helpDiv").addClass('pulse_me');
        //$("#helpDiv").css({ 'opacity': '0.5' });
        $("#helpImg").prop('src', Utils.Path + "images/skin/hideHelp.png");
        $("#letterDiv").children().css({ 'color': 'black' });
        Aksharkhel.attemptFlag = true;
        Aksharkhel.skipFlag = false;
        //$("#nextDiv").addClass("blink_me");
        $("#letterDiv").addClass('animated zoomIn');
        //$("#letterDiv").css('color', 'blue');
        $(".wordSpan").css({ 'pointer-events': 'none' });
        $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        for (var i = 0; i < $("#letterDiv").children().length; i++) {
            $("#" + $("#letterDiv").children()[i].id).text(Aksharkhel.splitArray[i]);
        }
        //$("#letterDiv").text(Aksharkhel.dataArray[Aksharkhel.numOfQuestion - 1].word);
    } else if (Aksharkhel.hideShowHelp == true) {
        Aksharkhel.hideShowHelp = false;
        document.getElementById('playSound').pause();
        $("#helpImg").prop('src', Utils.Path + "images/skin/help.png");
        for (var i = 0; i < $("#letterDiv").children().length; i++) {
            $("#" + $("#letterDiv").children()[i].id).text(Aksharkhel.wordArray[i]);
        }
        $("#helpDiv").css({ 'opacity': '1' });
        $(".wordSpan").css({ 'pointer-events': 'auto' });
        $(".opacityCls,#soundDiv").css({ 'opacity': '1', 'pointer-events': 'auto' });
        $("#letterDiv").removeClass('animated zoomIn');
    }
}