//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 = [];
Tom_N_Jerry.scoreArr = [];
$(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();
        Tom_N_Jerry.initializeVar();
        Tom_N_Jerry.createHardcodeddivs();
    }, 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' + ")");
    $("#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");
    $("#nextImg,#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");
    $("#creditImg").prop("src", Utils.Path + "images/skin/credits.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 = 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,#homeImg").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.generateBtn('operationBtn');
    Tom_N_Jerry.populateQue();
}
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.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.discardNumber = function (ele) {        //generate new option from 2 3 5 7
    $($('.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.multNumber = function (element) {                //multiply the number
    firstNumCnt++;
    Tom_N_Jerry.hideFlag = false;
    Tom_N_Jerry.attemptFlag = true;
    Tom_N_Jerry.skipFlag = false;
    $($('.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.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;
    $($('.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;
        $($('.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;
    Tom_N_Jerry.attemptFlag = 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)
        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();
    Tom_N_Jerry.calculateScore();
    $("#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.createHardcodeddivs = function () {
    var ackDiv;
    for (var i = 0; i < Object.keys(Tom_N_Jerry.acknowledgementData).length; i++) {
        ackDiv = document.createElement("div");
        ackDiv.setAttribute("id", "ack" + i);
        ackDiv.setAttribute("class", "noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
        ackDiv.innerHTML = Object.keys(Tom_N_Jerry.acknowledgementData)[i] + " : " + Object.values(Tom_N_Jerry.acknowledgementData)[i];
        document.getElementById("acknowledgementDiv").appendChild(ackDiv);
    }
    div = document.createElement('div');
    div.className = "noPadding fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = Tom_N_Jerry.hardcoded['createdOn'];
    document.getElementById("acknowledgementDiv").appendChild(div);
}
Tom_N_Jerry.showModal = function (flag) {
    $('.modal').show();
	document.getElementById('playSound').pause();
    $('.limitMsg,.numberMsg').text('');
    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");
    $("#nextDiv").addClass('bounceCls');
}
Tom_N_Jerry.nextQuestion = function () {
    document.getElementById('playSound').pause();
    if (Tom_N_Jerry.attemptFlag) {
        scoredMarks = 0;
        Tom_N_Jerry.calculateScore();
    }
    if (Tom_N_Jerry.skipFlag) {
        scoredMarks = -1;
        Tom_N_Jerry.calculateScore();
    }
    quesCnt++;
    $(".modal").hide();
    $("#gamePage").css("pointer-events", "auto");
    $($('.discardBtn').children()[0]).css('pointer-events', 'auto');
    $("#nextDiv").removeClass('bounceCls');
    clearTimeout(Tom_N_Jerry.nextTimer);
    if (quesCnt == 5) {
        $('#endPage').show();
        $('#widgetDiv,#gamePage').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);
        }

    }
    else
        Tom_N_Jerry.showQuestion();
}
Tom_N_Jerry.showCredits = function () {
    $('#acknowledgementDiv').show();
}
Tom_N_Jerry.callHome = function () {
    if (Tom_N_Jerry.attemptFlag) {
        scoredMarks = 0;
        Tom_N_Jerry.calculateScore();
    }
    location.reload(true);
}
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]);
}