//6 Feb 2020
var Tom_N_Jerry = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 100, firstNumCnt = 0, quesCnt = 0, limit = 1000, randomOptionCnt = 0, prevAns = 0, finalAnswer = 0, leftCounter = 9, factorsArr = [], totalQ = 5;
Tom_N_Jerry.scoreArr = [];
Tom_N_Jerry.seconds = 0;
$(document).ready(function () {
	$('title').text(Tom_N_Jerry.gameTitle);
    $(".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,#homeImg,#endPage,.modal").hide();
        $("#coverPage").show();
		$("#discardDiv").text(Tom_N_Jerry.hardcoded.discardTxt);
        Tom_N_Jerry.setImages();
        $("#Yes").text(Tom_N_Jerry.hardcoded.yes);
        $("#No").text(Tom_N_Jerry.hardcoded.no);
        Tom_N_Jerry.initializeVar();
    }, 300);
});
Tom_N_Jerry.setImages = function () {
    document.body.style.backgroundImage = "url(" + Utils.Path + Tom_N_Jerry.coverImage + ")";
    $("#scoreDiv,.discardBtn").css("background-image", "url(" + Utils.Path + 'images/skin/commonBg.png' + ")");
    $("#questionDiv").css("background-image", "url(" + Utils.Path + 'images/skin/Frame.png' + ")");
    $(".finalAnswer").css("background-image", "url(" + Utils.Path + 'images/skin/frame_01.png' + ")");
    $("#option").css("background-image", "url(" + Utils.Path + 'images/skin/Clock.png' + ")");
    $(".factorDiv").css("background-image", "url(" + Utils.Path + 'images/skin/wall-unit.png' + ")");
    $("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
    $("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
    $("#nextImg").prop("src", Utils.Path + "images/skin/skip.png");
    $("#nextGameImage,#nextBtnImg").prop("src", Utils.Path + "images/skin/Next.png");
    $("#replayImg").prop("src", Utils.Path + "images/skin/Replay.png");
    $("#checkImg").prop("src", Utils.Path + "images/skin/check.png");
    //$("#soundImg").prop("src", Utils.Path + "images/skin/Sound.png");
	$("#tomImg").prop('src',Utils.Path+'images/skin/idle_Tom.png');
}
Tom_N_Jerry.initializeVar = function () {
    Tom_N_Jerry.showQueArr = [];                //5 unique Que
    Tom_N_Jerry.scoreArr = [];                  //score of 5 Questions
    quesCnt = firstNumCnt = correctCnt = 0;        //firstNumCnt->dont show X ÷ buttons for first Number
    Tom_N_Jerry.hideFlag = false;
    Tom_N_Jerry.skipFlag = true;
    Tom_N_Jerry.attemptFlag = false;
}
Tom_N_Jerry.showInstruction = function () {
	document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
    $("#coverPage").hide();
    $("#instructionDiv").show();
    $('.buttons').css('visibility', 'visible');
    $('#heading').text(Tom_N_Jerry.hardcoded.heading);
    document.getElementById('text').innerHTML = Tom_N_Jerry.hardcoded.instructionTxt;
}
Tom_N_Jerry.playGame = function () {
    Tom_N_Jerry.createStars();
    Tom_N_Jerry.generateBtn('operationBtn');
    Tom_N_Jerry.populateQue();
	Tom_N_Jerry.startTimer();
}
Tom_N_Jerry.createStars = function () {
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= 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/skin/star1.png");
        $(newDiv).append(newImage);
        $("#starDiv").append(newDiv);
    }
    $("#starDiv").css("visibility", "hidden");
};
Tom_N_Jerry.generateBtn = function (parentDiv) {        //create use,dont use,X ÷ buttons
    var btn, btnImg, opr = ['X', '÷'];
    for (let i = 0; i < 2; i++) {
        btn = document.createElement('div');
        $(btn).prop("class", "noPadding bgProperty col-lg-6 col-md-6 col-xs-6 col-sm-6");
        $(btn).data('opr', opr[i]);
        if (i == 0) {
            $(btn).click(function () { Tom_N_Jerry.multNumber(this) })   //mult number
            $(btn).css('background-image', Utils.Path + "url(images/skin/cross-unit.png)");
        }
        else {
            $(btn).click(function () { Tom_N_Jerry.divideNumber(this) })    //divide number
            $(btn).css('background-image', Utils.Path + "url(images/skin/Divide-unit.png)");
        }
        $("." + parentDiv).append(btn);
    }
}
Tom_N_Jerry.populateQue = function () {
    var numberArr = [2, 3, 5, 7];
    $("#gamePage,#homeImg,#option,.factorDiv").show();
    $('#questionDiv,.finalAnswer').css('visibility', 'visible');
    $("#coverPage,#endPage,#acknowledgementDiv,#instructionDiv").hide();
    $('.answer').text(Tom_N_Jerry.hardcoded.ansText);
    $('.scoreCls').text(Tom_N_Jerry.hardcoded.scoreText);
    for (var k = 0; k < 5; k++) {
        var finalNum = Tom_N_Jerry.calculateNumber(numberArr);
        while ($.inArray(finalNum, Tom_N_Jerry.showQueArr) != -1)
            var finalNum = Tom_N_Jerry.calculateNumber(numberArr);
        Tom_N_Jerry.showQueArr.push(finalNum);
    }
    Tom_N_Jerry.showQuestion();
}
Tom_N_Jerry.calculateNumber = function (numberArr) {    //calculate number question
    var mult = 1;
    while (mult < limit) {
        var rNo = Math.floor(Math.random() * numberArr.length);
        mult = mult * numberArr[rNo];
    }
    var finalNum = Math.floor(mult / numberArr[rNo]);
    return finalNum;
}
Tom_N_Jerry.showQuestion = function () {
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    factorsArr = [];
    var optionArr = [2, 3, 5, 7];
    Tom_N_Jerry.attemptFlag = false;
    Tom_N_Jerry.skipFlag = true;
    randomOptionCnt = 0;
	$("#tomImg").prop('src',Utils.Path+'images/skin/idle_Tom.png');
	$("#behindJerryImg,#walkingJerryImg").prop('src','');
	$("#walkingJerryImg").css('height','unset');
    $($('.operationBtn').children()[1]).css({ 'opacity': 0.5, 'pointer-events': 'none' });
    $('.finalAnswer').text(1);
    leftCounter = 9;
    scoredMarks = 0;
    $("#scoreDiv").text(scoredMarks);
    $("#question").text(Tom_N_Jerry.showQueArr[quesCnt]);
    $('.factorTxt').text('');
    if ($('.factorTxt').text() == '')
        firstNumCnt = 0;
    factorsArr = Tom_N_Jerry.getFactors(Tom_N_Jerry.showQueArr[quesCnt]);
    for (let i = 0; factorsArr.length < 10; i++) {
        var remainingOption = Math.floor(Math.random() * optionArr.length);
        factorsArr.push(optionArr[remainingOption]);
    }
    shuffleArray(factorsArr);
    Tom_N_Jerry.discardNumber();
    // Tom_N_Jerry.playInstruction();
}
Tom_N_Jerry.getFactors = function (num) {
    var factors = [], i;

    for (i = 2; i <= num; i++) {
        while ((num % i) === 0) {
            factors.push(i);
            num /= i;
        }
    }
    console.log(factors);
    return factors;
}
Tom_N_Jerry.startTimer = function () {						//5 second timer (No responce Sound)
    $("#nextImage").css({ "pointer-events": "auto" });
    if (Tom_N_Jerry.noResponseTimer) {
        clearInterval(Tom_N_Jerry.noResponseTimer);
        Tom_N_Jerry.noResponseTimer = null;
        Tom_N_Jerry.seconds = 0;
    }
    Tom_N_Jerry.noResponseTimer = setInterval(function () {
        Tom_N_Jerry.seconds++;
        if (Tom_N_Jerry.seconds >= 7) {
            document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + Tom_N_Jerry.hardcoded.noResponce;
            document.getElementById("playSound").play();
            $(".pointerClass").css("pointer-events", "auto");
            clearInterval(Tom_N_Jerry.noResponseTimer)
            if (Tom_N_Jerry.timeOut) {
                clearTimeout(Tom_N_Jerry.timeOut);
                Tom_N_Jerry.timeOut = null;
            }
            Tom_N_Jerry.timeOut = setTimeout(function () {
                Tom_N_Jerry.seconds = 0;
                Tom_N_Jerry.startTimer();
            }, 2000);
        }
    }, 1000);
}
Tom_N_Jerry.discardNumber = function (ele) {        //generate new option from 2 3 5 7
    clearTimeout(Tom_N_Jerry.timeOut);
    clearInterval(Tom_N_Jerry.noResponseTimer);
    document.getElementById('playSound').pause();
    $($('.discardBtn').children()[0]).css('pointer-events', 'auto');
    Tom_N_Jerry.hideFlag = false;
    if (ele != undefined) {
        Tom_N_Jerry.skipFlag = false;
        Tom_N_Jerry.attemptFlag = true;
    }

    randomOptionCnt++;
    $('.number').removeClass('animated zoomIn');
    if (randomOptionCnt <= 10) {
        $("#option").text(factorsArr[randomOptionCnt - 1]);
        $('.chances').text(Tom_N_Jerry.hardcoded.chancesLeft + leftCounter);
        leftCounter--;
        if (firstNumCnt != 1)
            Tom_N_Jerry.opacityBtn();
    }
    else                                            //limit of 10 exceeds
        Tom_N_Jerry.showModal('chancesExceed');
    Tom_N_Jerry.startTimer();
}
Tom_N_Jerry.multNumber = function (element) {                //multiply the number
    firstNumCnt++;
    Tom_N_Jerry.hideFlag = false;
    Tom_N_Jerry.attemptFlag = true;
    Tom_N_Jerry.skipFlag = false;
    clearTimeout(Tom_N_Jerry.timeOut);
    clearInterval(Tom_N_Jerry.noResponseTimer);
    document.getElementById('playSound').pause();
    $($('.discardBtn').children()[0]).css('pointer-events', 'auto');
    if (!Tom_N_Jerry.hideFlag || $(element).data('opr') == 'X') {
        if (randomOptionCnt <= 10) {
            if (firstNumCnt != 1)
                $(".factorTxt").append('X');
            $(".factorTxt").append('' + $('#option').text());
            Tom_N_Jerry.evaluateAns();
        }
        else
            Tom_N_Jerry.showModal("chancesExceed");               //limit of 10 exceeds
    }
    Tom_N_Jerry.startTimer();
}
Tom_N_Jerry.evaluateAns = function () {
    var str;
    prevAns = $('.finalAnswer').text();
    $('.finalAnswer').text(0);
    str = $(".factorTxt").text().trim().replace(/X/gi, '*');
    str = str.replace(/÷/gi, '/');
    $('.finalAnswer').text(eval(str));
    if (Number($(".finalAnswer").text()) > Number($("#question").text()))
        Tom_N_Jerry.showModal('numberExceed');                   //user answer > que
    else
        Tom_N_Jerry.discardNumber();
}
Tom_N_Jerry.divideNumber = function (element) {         //divide number & update in text box
    var opr;
    Tom_N_Jerry.attemptFlag = true;
    Tom_N_Jerry.skipFlag = false;
    clearTimeout(Tom_N_Jerry.timeOut);
    clearInterval(Tom_N_Jerry.noResponseTimer);
    document.getElementById('playSound').pause();
    $($('.discardBtn').children()[0]).css('pointer-events', 'auto');
    if ($(element).data('opr') == '÷')
        opr = '/';
    $(".finalAnswer").text(eval($(".finalAnswer").text() + opr + $("#option").text()));
    if (firstNumCnt != 1)
        $(".factorTxt").append('÷');
    $(".factorTxt").append('' + $('#option').text());
    if ($('.factorTxt').text() == '')
        firstNumCnt = 0;
    //}
    Tom_N_Jerry.discardNumber();
}
Tom_N_Jerry.opacityBtn = function () {         //    hide/show operator buttons
    if ($('.factorTxt').text().trim().length > 0 && ($(".finalAnswer").text() % $("#option").text()) == 0) {
        Tom_N_Jerry.hideFlag = true;
        //$($('.discardBtn').children()[0]).css('pointer-events', 'none');
        $($('.operationBtn').children()[1]).css({ 'opacity': 1, 'pointer-events': 'auto' });
    }
    else {
        Tom_N_Jerry.hideFlag = false;
        $($('.operationBtn').children()[1]).css({ 'opacity': 0.5, 'pointer-events': 'none' });
    }
}
Tom_N_Jerry.checkAnswer = function (flag) {
    Tom_N_Jerry.skipFlag = false;
    if (flag == 'numberExceed')
        finalAnswer = Number(prevAns);
    else
        finalAnswer = Number($('.finalAnswer').text().trim());

    var per = finalAnswer / Tom_N_Jerry.showQueArr[quesCnt] * 100;

    if (Tom_N_Jerry.showQueArr[quesCnt] == finalAnswer) {
        correctCnt++;
        scoredMarks = 100;
    }
    else if (per >= 90)
        scoredMarks = 90;
    else if ((per >= 70) && (per < 90))
        scoredMarks = 70;
    else if ((per >= 50) && (per < 70))
        scoredMarks = 50;
    else
        scoredMarks = 20;
		if(scoredMarks == 20){
		$("#tomImg").prop('src',Utils.Path+'images/skin/jumping_Tom.gif');
		$("#behindJerryImg").prop('src',Utils.Path+'images/skin/jerry_Hit.gif');
		document.getElementById('playSound').src=Utils.Path+'sounds/instruction/Jerry_Hits_Tom.mp3';
		}
		else
		{
			$("#tomImg").prop('src',Utils.Path+'images/skin/tom_Hit.gif');
			$("#walkingJerryImg").prop('src',Utils.Path+'images/skin/jerry.gif');
			document.getElementById('playSound').src=Utils.Path+'sounds/instruction/Tom_Hits_Jerry.mp3';
			setTimeout(function(){$("#walkingJerryImg").css('height','6vh');},500);
		}
		document.getElementById('playSound').play();
    $("#scoreDiv").text(scoredMarks);
    Tom_N_Jerry.scoreArr.push(scoredMarks);
}

Tom_N_Jerry.replayGame = function () {
    Tom_N_Jerry.initializeVar();
    Tom_N_Jerry.populateQue();
}
Tom_N_Jerry.showModal = function (flag) {
    $('#scoreCard').show();
    $('.limitMsg,.numberMsg').text('');
    Tom_N_Jerry.attemptFlag = true;
    clearTimeout(Tom_N_Jerry.timeOut);
    clearInterval(Tom_N_Jerry.noResponseTimer);
    document.getElementById('playSound').pause();
    Tom_N_Jerry.checkAnswer(flag);
    $('.modalAns').text(Tom_N_Jerry.hardcoded.yourAns + $('.finalAnswer').text());
    $('.modalScore').text(Tom_N_Jerry.hardcoded.yourScore + scoredMarks);
    if (flag == 'chancesExceed')
        $('.limitMsg').text(Tom_N_Jerry.hardcoded.exceedChance);
    else if (flag == 'numberExceed')
        $('.numberMsg').text(Tom_N_Jerry.hardcoded.exceedLimit);
    $("#gamePage").css("pointer-events", "none");
    $($('.discardBtn').children()[0]).css('pointer-events', 'none');
    $("#nextDiv").css("pointer-events", "auto");
    if (Tom_N_Jerry.nextQTimer) {
        clearTimeout(Tom_N_Jerry.nextQTimer);
        Tom_N_Jerry.nextQTimer = null;
    }
    Tom_N_Jerry.nextQTimer = setTimeout(function () {
        Tom_N_Jerry.nextQuestion();
    }, 1500);
}
Tom_N_Jerry.nextQuestion = function () {
    document.getElementById('playSound').pause();
    $("#scoreCard").hide();
    clearTimeout(Tom_N_Jerry.nextQTimer);
    clearTimeout(Tom_N_Jerry.instructionTimer);
    clearInterval(Tom_N_Jerry.noResponseTimer);
    clearTimeout(Tom_N_Jerry.timeOut);
    $("#gamePage").css("pointer-events", "auto");
    $($('.discardBtn').children()[0]).css('pointer-events', 'auto');
    clearTimeout(Tom_N_Jerry.nextTimer);
    if (Tom_N_Jerry.attemptFlag) {
        Tom_N_Jerry.calculateScore();
        Tom_N_Jerry.showQueArr.splice(quesCnt, 1);
    }

    if (Tom_N_Jerry.skipFlag)
        quesCnt++;
    if (Tom_N_Jerry.showQueArr.length == 0)
        Tom_N_Jerry.lastPage();
    else if (quesCnt == Tom_N_Jerry.showQueArr.length) {
        $('#responseBoxDiv').show();
        $('#questionMsg').text(Tom_N_Jerry.hardcoded.message);
    }
    else
        Tom_N_Jerry.showQuestion();
}
Tom_N_Jerry.showNext = function (element) {
    if ($(element).text() == Tom_N_Jerry.hardcoded.no)
        Tom_N_Jerry.lastPage();
    else
        Tom_N_Jerry.showRemaining();
}
Tom_N_Jerry.lastPage = function () {
    $('#endPage').show();
    $('#widgetDiv,#gamePage,#responseBoxDiv,#instructionDiv').hide();
    $('#questionDiv').css('visibility', 'hidden');
    $('.message').text(Tom_N_Jerry.hardcoded.gameOver);
    if (Tom_N_Jerry.scoreArr.length != 0)
        $('.highestScore').text(Tom_N_Jerry.hardcoded.highestScore + Math.max(...Tom_N_Jerry.scoreArr));
    else {
        if (scoredMarks == -1)
            scoredMarks = 0;
        $('.highestScore').text(Tom_N_Jerry.hardcoded.highestScore + scoredMarks);
    }
    Tom_N_Jerry.giveStars();
    console.log(correctCnt, totalQ);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(correctCnt, totalQ, "7");
}

Tom_N_Jerry.showRemaining = function () {
    quesCnt = 0;
    $('#responseBoxDiv').hide();
    $('#gamePage').show();
    Tom_N_Jerry.showQuestion();
}
Tom_N_Jerry.giveStars = function () {
    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();
    }
};
Tom_N_Jerry.calculateScore = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Tom_N_Jerry.showQueArr[quesCnt]);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Tom_N_Jerry.showQueArr[quesCnt]);
}
Tom_N_Jerry.nextGame = function () {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}