//16th sept 2019
var Muhanware = {};
var Utils = {};
Utils.Path = '';
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 0,
    resId = 0,
    label = "",
    scoreFlag = false;
Utils.mobileDeviceFlag = false;
var word = "",
    totalNos = 0,
    type = "word";

$(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;
    setTimeout(function() {
        Muhanware.setImages();

        if (Muhanware.hardCodedData['languageFont'] != null)
            setFontFamilyForLang("fonts/" + Muhanware.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");
}

//set all images
Muhanware.setImages = function() {
    document.getElementById('home').src = Utils.Path + "images/home.png";
    document.getElementById('logo').src = Utils.Path + "images/logo.png";
    document.getElementById('playImage').src = Utils.Path + "images/Play.png";
    document.getElementById('next').src = Utils.Path + "images/Skip_Muhanware.png";
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/Cover.jpg" + ")";
    document.getElementById('help').src = Utils.Path + "images/Help.png";
    document.getElementById("replatbtn").src = Utils.Path + "images/playAgain.png";
    document.getElementById("creditbtn").src = Utils.Path + "images/Next.png";
    document.getElementById('questionBoard').style.backgroundImage = "url(" + Utils.Path + "images/board.png" + ")";
    document.getElementById('gamePage').style.display = 'none';
}
Muhanware.initializeVariables = function() {
        Muhanware.optionArr = []; //Array for four options
        Muhanware.queArr = []; //array for 5 questions
        Muhanware.wrongAnsDiv;
        Muhanware.queCnt = 0;
        Muhanware.nextQueTimer = 0;
        Muhanware.ansClicked = false;
        Muhanware.correctCounter = 0;
        Muhanware.total_No_of_Questions = 5;
        Muhanware.seconds = 0;
    }
    //onclick play button to start game or display que page
Muhanware.playGame = function() {
        Muhanware.initializeVariables();
        $("#help").hide();
        $("#home").hide();
        $("#replatbtn").hide();

        document.body.style.backgroundImage = "url(" + Utils.Path + "images/Inside_page_02.jpg" + ")";
        document.getElementById('coverPage').style.display = 'none';
        document.getElementById('gamePage').style.display = 'block';
        document.getElementById('homeDiv').style.visibility = 'visible';
        document.getElementById("finalPage").style.display = "none";
        getUniqueValArr(Muhanware.data, Muhanware.queArr, 5);
        console.log(Muhanware.queArr);
        Muhanware.wrongAnsDivFn();
        Muhanware.showQuestion();
        Muhanware.createOptions();
        Muhanware.changeOptions();
    }
    //when ans is right or wrong to set img dynamic div was created
Muhanware.wrongAnsDivFn = function() {
        Muhanware.wrongAnsDiv = document.createElement("div");
        Muhanware.wrongAnsDiv.setAttribute("id", "wAnsDiv");
        Muhanware.wrongAnsDiv.setAttribute("class", "frogImgStyle col-xs-6 col-sm-6 col-md-6 col-lg-6");
        var wrongAnsImg = document.createElement("img");
        wrongAnsImg.setAttribute("id", "wAnsImg");
        wrongAnsImg.setAttribute("class", "img-responsive nopadding col-xs-10 col-sm-10 col-md-10 col-lg-10");
        Muhanware.wrongAnsDiv.appendChild(wrongAnsImg);
    }
    //to display que and four options
Muhanware.showQuestion = function() {
        $(".options").css({ "pointer-events": "auto" }); //pointer event auto to check again ans
        Muhanware.ansClicked = false;
        scoreFlag = false;
        totalMarks = 10;
        questionId = parseInt(Muhanware.queArr[Muhanware.queCnt].questionId);
        word = Muhanware.queArr[Muhanware.queCnt].options;
        totalNos = Muhanware.data.length;
        d = new Date(); //date object
        startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); //to get the current date
        document.getElementById('frogImg').src = Utils.Path + "images/Frog_Correct-ANS_01.png";

        document.getElementById('queText').innerHTML = Muhanware.queArr[Muhanware.queCnt].phrase;
        Muhanware.optionArr.push(Muhanware.queArr[Muhanware.queCnt]);
        getUniqueValArr(Muhanware.data, Muhanware.optionArr, 3);
        shuffle(Muhanware.optionArr);
        Muhanware.changeOptions();
        Muhanware.startTimer();
        //console.log(Muhanware.optionArr);
    }
    //create dynamic div for create options
Muhanware.createOptions = function() {
        var div, span;
        var row = 2,
            col = 2;
        document.getElementById("optionsDiv").innerHTML = "";
        var indexDiv = document.getElementById('optionsDiv');
        for (var j = 0; j < row; j++) {
            parentDiv = document.createElement('div');
            parentDiv.setAttribute('class', 'nopadding col-xs-12 col-sm-12 col-lg-12 col-md-12 col-xs-offset-0 col-sm-offset-0 col-lg-offset-0 col-md-offset-0');
            parentDiv.setAttribute('id', 'parentDiv' + (j));
            indexDiv.appendChild(parentDiv);

            for (var i = 0; i < col; i++) {
                outerDiv = document.createElement('div');
                outerDiv.setAttribute('class', 'helpClass parentClass nopadding col-xs-6 col-sm-6 col-lg-6 col-md-6 col-xs-offset-0 col-sm-offset-0 col-lg-offset-0 col-md-offset-0');
                outerDiv.setAttribute('id', 'outerOption' + (j) + "" + (i));
                parentDiv.appendChild(outerDiv);

                div = document.createElement('div');
                div.setAttribute('class', 'nopadding text-center options col-xs-6 col-sm-6 col-lg-6 col-md-6 col-xs-offset-0 col-sm-offset-0 col-lg-offset-0 col-md-offset-0');
                div.setAttribute('id', 'option' + (j) + "" + (i));
                outerDiv.appendChild(div);
                document.getElementById('option' + (j) + "" + (i)).style.backgroundImage = "url(" + Utils.Path + "images/Leaf_01.png" + ")";
                $('#option' + (j) + "" + (1)).addClass("intro");

                span = document.createElement('span');
                span.setAttribute('id', 'span' + (j) + "" + (i));
                span.setAttribute('class', 'spanElements');

                div.setAttribute('onclick', 'Muhanware.checkAnswer(this.id)');
                div.appendChild(span);
            }
        }
    }
    //function for change the options when next que will display
Muhanware.changeOptions = function() {
        var optionsIndex = 0;
        $('.spanElements').css({ "visibility": "visible" });
        $('.options').css({ "visibility": "visible" });
        for (var j = 0; j < Muhanware.optionArr.length / 2; j++) {
            for (var i = 0; i < Muhanware.optionArr.length / 2; i++) {
                $("#option" + j + "" + i).prop('value', Muhanware.optionArr[optionsIndex].options);
                $("#span" + j + "" + i).text(Muhanware.optionArr[optionsIndex].options);
                optionsIndex++;
            }
        }
    }
    //on click option div check ans is right or wrong
Muhanware.checkAnswer = function(eleId) {
        //Muhanware.attemptCnt++;
        Muhanware.ansClicked = true;
        scoreFlag = true;
        $(".frogImgStyle").remove();
        clearInterval(Muhanware.noResponseTimer); //remove frog image from div
        clearTimeout(Muhanware.returnBackFrog); //clear frog movement time out
        $(".options").css({ "pointer-events": "none" }); //other div's pointer event none
        $("#help").css({ "pointer-events": "none" }); //help buttons's pointer event none
        $("#next").css({ "pointer-events": "none" }); //next buttons's pointer event none
        $('.spanElements').css({ "visibility": "visible" });
        if ($("#" + eleId).hasClass("intro")) //to check intro class add to div or not
            document.getElementById('frogImg').src = Utils.Path + "images/Frog_Jumping.png";
        else
            document.getElementById('frogImg').src = Utils.Path + "images/Frog_Jumping_01.png";
        $("#frogDiv").css({ "z-index": "10" });

        var x = $("#frogImg").offset();
        $("#frogImg").animate({
            top: $("#" + eleId).offset().top - x.top - 100,
            left: $("#" + eleId).offset().left - x.left,
        }, 500, function() {

            //check ans
            $('#frogDiv').css({ "visibility": "hidden" });
            var divId = $("#" + eleId).parent().prop("id");
            $('#' + divId).prepend(Muhanware.wrongAnsDiv);

            if ($('#' + eleId).prop('value') == Muhanware.queArr[Muhanware.queCnt].options) {
                Muhanware.moveFrog(true); //if ans is right
                Muhanware.correctCounter++;
            } else {
                Muhanware.moveFrog(false); //if ans is wrong
            }
            document.getElementById("audio").play();

            console.log(Muhanware.queArr);
            if (Muhanware.nextQueTimer) {
                clearTimeout(Muhanware.nextQueTimer);
                Muhanware.nextQueTimer = null;
            }
            Muhanware.nextQueTimer = setTimeout(function() {

                Muhanware.nextQue();
            }, 2000);

        });

    }
    //after checking ans right or wrong change frog position and image and sound
Muhanware.moveFrog = function(actionFlag) {
        if (actionFlag) {
            console.log(word, totalNos, type);
            if (Utils.mobileDeviceFlag) {
                Android.addLearntData(word, totalNos, type);
            }
            document.getElementById("wAnsDiv").style.marginLeft = "14vw";
            document.getElementById("wAnsDiv").style.marginTop = "-2vw";
            document.getElementById("wAnsImg").src = Utils.Path + "images/Frog_Correct-ANS_01.png";
            document.getElementById("audio").src = Utils.Path + 'sounds/Instructions/Correct3.mp3';

            $(".options").css({ "pointer-events": "none" }); //other div's pointer event none
            $("#help").css({ "pointer-events": "none" });
            $("#next").css({ "pointer-events": "auto" });

            scoredMarks = 10;
            Muhanware.scoreFunction();
            //Muhanware.ansClicked=false;	

        } else {
            scoredMarks = 0;
            Muhanware.scoreFunction();
            $(".options").css({ "pointer-events": "none" }); //other div's pointer event none

            document.getElementById("audio").src = Utils.Path + 'sounds/Instructions/Wrong3.mp3';
            document.getElementById("wAnsDiv").style.marginLeft = "3vw";
            document.getElementById("wAnsDiv").style.marginTop = "3vw";
            document.getElementById("wAnsImg").src = Utils.Path + "images/WrongANS.png";
        }
        Muhanware.queArr.splice(Muhanware.queCnt, 1);
    }
    //to display next que
Muhanware.nextQue = function() {
    clearInterval(Muhanware.noResponseTimer);
    clearTimeout(Muhanware.nextQueTimer);
    clearTimeout(Muhanware.returnBackFrog);
    console.log(Muhanware.queArr);
    $("#help").css({ "pointer-events": "auto" });
    $("#next").removeClass("blink_me");
    $(".frogImgStyle").remove();
    document.getElementById('audio').pause();
    $("#frogImg").remove();
    $(".parentClass").addClass('helpClass');
    $(".helpClass").removeClass("animated zoomOut");
    Muhanware.imgTag();

    Muhanware.optionArr = [];

    if (scoreFlag != true) {
        Muhanware.queCnt++;
    }
    if (Muhanware.queArr.length == 0) {
        Muhanware.gameOver();
    } else if (Muhanware.queCnt == Muhanware.queArr.length) {
        clearInterval(Muhanware.noResponseTimer);
        document.getElementById("responseBoxDiv").style.display = "block";
        document.getElementById("No").innerHTML = Muhanware.modalData.no;
        document.getElementById("Yes").innerHTML = Muhanware.modalData.yes;
        document.getElementById("questionMsg").innerHTML = Muhanware.modalData.responseMsg;
    } else {
        Muhanware.showQuestion();
    }
}

//display game over msg after solve all questions
Muhanware.gameOver = function() {
        clearInterval(Muhanware.noResponseTimer);
        document.getElementById("acknowledgementDiv").innerHTML = "";
        document.getElementById("gamePage").style.display = "none";
        document.getElementById("finalPage").style.display = "block";
        document.getElementById('gameOver').innerHTML = Muhanware.hardCodedData.gameOver;
        document.getElementById("responseBoxDiv").style.display = "none";

        for (var i = 0; i < Object.keys(Muhanware.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(Muhanware.AcknowledgementPageData)[i] + " : " + Object.values(Muhanware.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 = Muhanware.hardCodedData['createdOn'];
        acknowledgementDiv.appendChild(div);
        document.getElementById("acknowledgementDiv").style.display = "none";
        Muhanware.createStars();
        Muhanware.giveStars();
    }
    //show credits on click credit button
Muhanware.showCredits = function() {
        document.getElementById("acknowledgementDiv").style.display = "block";
    }
    //go to home or previous page
Muhanware.backToHome = function() {
        clearInterval(Muhanware.noResponseTimer);
        if (Muhanware.ansClicked) {
            scoredMarks = 0;
            Muhanware.ansClicked = false;
            Muhanware.scoreFunction();
        }
        location.reload(true); //true-Reloads the current page from the server,false-from cache

    }
    //create dynamic img tag for frog img 
Muhanware.imgTag = function() {

    $(".options").css({ "pointer-events": "auto" }); //pointer event auto to check again ans
    //$("#help").css({"pointer-events":"auto"}); 
    $("#next").css({ "pointer-events": "auto" });
    imgDiv = document.createElement('img');
    imgDiv.setAttribute('class', 'img-responsive nopadding col-sm-10 col-lg-10 col-md-10 col-xs-10 col-sm-offset-0 col-lg-offset-0 col-md-offset-0 col-xs-offset-0');
    imgDiv.setAttribute('id', 'frogImg');
    frogDiv.appendChild(imgDiv);
    document.getElementById('frogImg').src = Utils.Path + "images/Frog_Correct-ANS_01.png";
    $('#frogDiv').css({ "visibility": "visible" });
    $('#frogImg').css({ 'top': '', 'left': '' });
}

Muhanware.scoreFunction = function() //score Function
    {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        }
    }

Muhanware.showSkippedQuestions = function() {
    document.getElementById("responseBoxDiv").style.display = "none";
    Muhanware.queCnt = 0;
    Muhanware.showQuestion();
}

//function which creates star divs
Muhanware.createStars = function() {
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= Math.floor(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/star1.png");
        $(newDiv).append(newImage);
        $("#starsDiv").append(newDiv);
    }
};

Muhanware.giveStars = function() {
    var fractionVar, i, numberOfStars = 0,
        temp;
    ans = Muhanware.total_No_of_Questions / 5;
    temp = Muhanware.correctCounter / ans;
    numberOfStars = Math.floor(temp);
    temp = Math.round(temp);
    console.log(numberOfStars);
    console.log(temp);
    for (i = 1; i <= Math.floor(numberOfStars); i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/star2.png");
    /* if(temp>numberOfStars)
    document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/halfStar.png"); */
    $("#starsDiv").css("visibility", "visible");
    if (numberOfStars != 0) {
        document.getElementById("audio").src = Utils.Path + "sounds/Instructions/" + "Star" + numberOfStars + ".mp3";
        document.getElementById("audio").play();
    }
    console.log(Muhanware.correctCounter, Muhanware.total_No_of_Questions, Muhanware.testCode);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(Muhanware.correctCounter, Muhanware.total_No_of_Questions, Muhanware.testCode);
};

Muhanware.goNext = function() {
    clearInterval(Muhanware.skipTimer);
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}

Muhanware.startTimer = function() {
    if (Muhanware.noResponseTimer) {
        clearInterval(Muhanware.noResponseTimer);
        Muhanware.noResponseTimer = null;
        Muhanware.seconds = 0;
    }
    Muhanware.noResponseTimer = setInterval(function() {
        Muhanware.seconds++;
        if (Muhanware.seconds >= 7) {
            document.getElementById("audio").src = Utils.Path + "sounds/instructions/please_ans_the_ques.mp3";
            document.getElementById("audio").play();
            clearInterval(Muhanware.noResponseTimer);
            if (Muhanware.timeOut) {
                clearTimeout(Muhanware.timeOut);
                Muhanware.timeOut = null;
            }
            Muhanware.timeOut = setTimeout(function() {
                Muhanware.seconds = 0;
                Muhanware.startTimer();
            }, 2000);
        }
    }, 1000);
};