//22Aug 2019
var Aksharkhel = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0,
    correctCnt = 0,
    quesCnt = 0,
    modalCnt = 5,
    type = "word";
Aksharkhel.marks = 0;
Aksharkhel.skipFlag = true;
Aksharkhel.seconds = 0;
$(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.hardcoded['languageFont'] != null)
            setFontFamilyForLang("fonts/" + Aksharkhel.hardcoded['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();
    $("#Yes").text(Aksharkhel.hardcoded.yes);
    $("#No").text(Aksharkhel.hardcoded.no);
    if (Utils.mobileDeviceFlag)
        Aksharkhel.levelName = Android.isPractice();
    Aksharkhel.initializeVariables();
    $("#gamePage,#endPage").hide();
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/" + Aksharkhel.hardcoded.coverImage + ")";
    Aksharkhel.createStars();
    $("#quesInstruction").text(Aksharkhel.hardcoded.instruct);
}
Aksharkhel.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", "zeroPadding 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 zeroPadding 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");
};
Aksharkhel.initializeVariables = function() {
        Aksharkhel.noOfKanaMatra = 0;
        Aksharkhel.wordArray = []; //splitted word
        correctCnt = 0;
        Aksharkhel.dataArray = []; //Random 5 unique question
        Aksharkhel.totalQuestions = 5;
        Aksharkhel.loadmetaDataFlag = false;
    }
    //sets Images	
Aksharkhel.setAllImage = function() {
    $("#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/Skip.png");
    $("#sound").prop('src', Utils.Path + "images/skin/Sound_button.png");
    $("#checkImg").prop('src', Utils.Path + "images/skin/Done.png");
    $("#clearImg").prop('src', Utils.Path + "images/skin/playAgain.png");
    $("#nextGameImage").prop('src', Utils.Path + "images/skin/Next_button.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");
}

//onclick of play button
Aksharkhel.startGame = function() {
    $("#playButton,#gamePage,#widget").hide();
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Bg.png)";
    Aksharkhel.showInstruction();
    Aksharkhel.createOptionDivs();
}
Aksharkhel.playInstruction = function() {
        document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + Aksharkhel.hardcoded.instructionSound;
        document.getElementById("playSound").play();
    }
    //shows the instuction page
Aksharkhel.showInstruction = function() {
    $("#instructionDiv").show();
    Aksharkhel.playInstruction();
    $('#heading').text(Aksharkhel.hardcoded.heading);
    document.getElementById('text').innerHTML = Aksharkhel.hardcoded.instructions[0];
}

//create matra divs
Aksharkhel.createOptionDivs = function() {
    var 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;
        document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Bg.png)";
        $("#gamePage").show();
        $("#quesInstruction").css("visibility", "visible");
        $("#playButton,#instructionDiv").hide();
        if (Aksharkhel.skipFlag == false)
            Aksharkhel.marks += scoredMarks;
        Aksharkhel.marks = 0;
        $("#acknowledgementDiv").css("visibility", "hidden");
        Aksharkhel.dataArray = populate(Aksharkhel.Data, Aksharkhel.dataArray, 5);
        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.skipFlag = true;
        clearInterval(Aksharkhel.noResponseTimer);
        document.getElementById('playSound').pause();
        d = new Date();
        startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        Aksharkhel.noOfKanaMatra = 0;
        scoredMarks = 0;
        $(".optionDiv").css("pointer-events", "none");
        //document.getElementById("options").style.pointerEvents = "auto";
        $("#soundDiv").css("pointer-events", "auto");
        $("#nextDiv").css("visibility", "visible");
        Aksharkhel.setQuestion();
        Aksharkhel.playSound();
        Aksharkhel.startTimer();
    }
    //runs @ onclick of sound button, plays the sound of image. 	
Aksharkhel.playSound = function() {
        clearInterval(Aksharkhel.noResponseTimer);
        document.getElementById("playSound").src = Utils.Path + "sounds/" + Aksharkhel.dataArray[quesCnt].Sounds;
        document.getElementById("playSound").play();
        Aksharkhel.startTimer();
    }
    //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[quesCnt].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.indexMain = [i];
            Aksharkhel.splitArray.splice(i, 1); //word with kanamatra. 
        }
        if (i > 0 && 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);
            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);
    }
    questionId = Aksharkhel.dataArray[quesCnt].questionId;
}

//Runs @ onclick of letter displayed on typewriter.stores the clicked letter.
Aksharkhel.getLetter = function(letter) {
        //Aksharkhel.skipFlag = false;
        clearInterval(Aksharkhel.noResponseTimer);
        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");
        Aksharkhel.startTimer();
    }
    //Runs @ onclick of letter from option checks whether the initial letter of image and cliked letter are same.
Aksharkhel.makeWord = function(letterId) {
    //Aksharkhel.skipFlag = false;
    clearInterval(Aksharkhel.noResponseTimer);
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/ting.mp3';
    document.getElementById('playSound').play();
    $("#" + Aksharkhel.letterDiv.id).text($("#" + Aksharkhel.letterDiv.id).text().split('')[0]);
    $("#" + Aksharkhel.letterDiv.id).text($("#" + Aksharkhel.letterDiv.id).text().concat($("#" + letterId).children().text()));
    Aksharkhel.startTimer();
}
Aksharkhel.startTimer = function() { //5 second timer (No responce Sound)
    if (Aksharkhel.noResponseTimer) {
        clearInterval(Aksharkhel.noResponseTimer);
        Aksharkhel.noResponseTimer = null;
        Aksharkhel.seconds = 0;
    }
    Aksharkhel.noResponseTimer = setInterval(function() {
        Aksharkhel.seconds++;
        if (Aksharkhel.seconds >= 7) {
            document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + Aksharkhel.hardcoded.noResponce;
            document.getElementById("playSound").play();
            $(".pointerClass").css("pointer-events", "auto");
            clearInterval(Aksharkhel.noResponseTimer)
            if (Aksharkhel.timeOut) {
                clearTimeout(Aksharkhel.timeOut);
                Aksharkhel.timeOut = null;
            }
            Aksharkhel.timeOut = setTimeout(function() {
                Aksharkhel.seconds = 0;
                Aksharkhel.startTimer();
            }, 2000);
        }
    }, 1000);
}
Aksharkhel.checkAnswer = function(letterId) {
    var randomSound;
    Aksharkhel.skipFlag = false;
    clearInterval(Aksharkhel.noResponseTimer);
    clearTimeout(Aksharkhel.timeOut);
    document.getElementById('playSound').pause();
    $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
    $(".optionDiv,.wordSpan").css("pointer-events", "none");
    if ($("#letterDiv").children().text() == Aksharkhel.dataArray[quesCnt].word) {
        correctCnt++;
        scoredMarks = 10;

        $("#letterDiv").children().css({ 'color': 'green', '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();
        console.log(Aksharkhel.dataArray[quesCnt].word, Aksharkhel.Data.length, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(Aksharkhel.dataArray[quesCnt].word, Aksharkhel.Data.length, type);
        if (Aksharkhel.skipFlag == false)
            Aksharkhel.marks += scoredMarks;

    } else {
        scoredMarks = 0;
        $("#letterDiv").children().css({ 'color': 'red' });
        $(".optionDiv,.wordSpan").css("pointer-events", "none");
        setTimeout(function() {
            $("#letterDiv").children().css({ 'color': 'black' });
        }, 1500);
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Aksharkhel.wrongAns[0];
        document.getElementById('playSound').play();
    }

    Aksharkhel.calculateScore();
    Aksharkhel.dataArray.splice(quesCnt, 1);
    if (Aksharkhel.nextQ) {
        clearTimeout(Aksharkhel.nextQ);
        Aksharkhel.nextQ = null;
    }
    Aksharkhel.nextQ = setTimeout(function() {
        $(".opacityCls").css({ 'opacity': '0.5', 'pointer-events': 'none' });
        $("span").css("pointer-events", "none");
        Aksharkhel.showNextQuestion();
    }, 1500);
}

Aksharkhel.clearWord = function() {
        clearInterval(Aksharkhel.noResponseTimer);
        document.getElementById('playSound').pause();
        $(".optionDiv").css("pointer-events", "none");
        for (j = 0; j < Aksharkhel.wordArray.length; j++)
            $("#span" + j).text(Aksharkhel.wordArray[j]);
        $(".wordSpan").css('color', 'black');

        Aksharkhel.startTimer();
    }
    //runs when user clicks next button wijthout attempting question.
Aksharkhel.showNextQuestion = function() {
    clearTimeout(Aksharkhel.timeOut);
    clearTimeout(Aksharkhel.nextQ);
    clearInterval(Aksharkhel.noResponseTimer);
    document.getElementById('playSound').pause();
    $(".opacityCls").css({ 'opacity': '1', 'pointer-events': 'auto' });
    if (Aksharkhel.skipFlag)
        quesCnt++;
    $("#gamePage").css("pointer-events", "auto");
    if (Aksharkhel.dataArray.length == 0)
        Aksharkhel.lastPage();
    else if (quesCnt == Aksharkhel.dataArray.length) {
        $('#responseBoxDiv').show();
        $('#confiramtionText').text(Aksharkhel.hardcoded.message);
    } else
        Aksharkhel.playGame();
}
Aksharkhel.showNext = function(element) { //onclick of Yes/No modal option
    if ($(element).text() == Aksharkhel.hardcoded.no)
        Aksharkhel.lastPage();
    else
        Aksharkhel.showRemaining();
}
Aksharkhel.lastPage = function() { //show last page
    clearInterval(Aksharkhel.noResponseTimer);
    clearTimeout(Aksharkhel.timeOut);
    document.getElementById('playSound').pause();
    $('#endPage,#widget').show();
    $("#quesInstruction").css("visibility", "hidden");
    $('#responseBoxDiv,#gamePage').hide();
    $("#message").text(Aksharkhel.hardcoded.word);
    $("#message").css("visibility", "visible");
    Aksharkhel.giveStars();
    console.log(correctCnt, modalCnt); //total cnt
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(correctCnt, modalCnt, "6");
}
Aksharkhel.giveStars = function() { //calculates stars
    var i, numberOfStars = correctCnt;
    for (i = 1; i <= numberOfStars; i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
    $("#starDiv").css("visibility", "visible");
    if (correctCnt != 0) {
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + 'Star' + correctCnt + '.mp3';
        document.getElementById('playSound').play();
    }
};
Aksharkhel.showRemaining = function() { //show remaining questions
    quesCnt = 0;
    Aksharkhel.checkFlag = false;
    showRemainingFlag = true;
    $('#responseBoxDiv').hide();
    $('#gamePage').show();
    $("#soundDiv").css("visibility", "visible");
    Aksharkhel.playGame();
}

Aksharkhel.calculateScore = function() {
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Aksharkhel.dataArray[quesCnt].word);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Aksharkhel.dataArray[quesCnt].word);
}
Aksharkhel.nextGame = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}