var PlaceValue = {};
var Utils = {};
Utils.path = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, label="", scoreFlag = false;

$(document).ready(function () {
    $(".se-pre-con").fadeOut("slow");
    setTimeout(function () {
        PlaceValue.init();
        PlaceValue.imgSource();
    });
}, 200);
 
PlaceValue.init = function () {
    document.getElementById("home").style.display = "none";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("finalPage").style.display = "none";
}

PlaceValue.imgSource = function () {
    document.body.style.backgroundImage = Utils.path + "url('images/Cover.jpg')";
    document.getElementById("home").src = Utils.path + "images/Home.png";
    document.getElementById("logo").src = Utils.path + "images/logo.png";
    document.getElementById("playbutton").src = Utils.path + "images/Play.png";
    document.getElementById("check").src = Utils.path + "images/Check.png";
    document.getElementById("next").src = Utils.path + "images/Next.png";
    document.getElementById("monkey").src = Utils.path + "images/Monkey_01.png";
    document.getElementById("replatbtn").src = Utils.path + "images/replay.png";
    document.getElementById("creditbtn").src = Utils.path + "images/Credits.png";
    document.getElementById("sound").src = Utils.path + "images/Sound.png";
}

PlaceValue.play = function () {
    document.body.style.backgroundImage = Utils.path + "url('images/FullBG.jpg')";
    document.getElementById("home").style.display = "block";
    document.getElementById("gamePage").style.display = "block";
    document.getElementById("playbutton").style.display = "none";
    document.getElementById("finalPage").style.display = "none";
    document.getElementById("gridNumbers").innerHTML = "";
    document.getElementById("que").innerHTML="";
    PlaceValue.initVariables();
    PlaceValue.populate();
    PlaceValue.generateQue();
    PlaceValue.playInstruction();
}
PlaceValue.initVariables = function () {
    PlaceValue.ansCount = 0;    //count no of shapes
    PlaceValue.colorFlag = false;   //to check shape is colored or not 
    PlaceValue.imageCountArray = [];    // array for shape count
    PlaceValue.factorCountArray = [];    // array for factors count
    PlaceValue.queCount = 0;    //que count
    PlaceValue.rNo = 0;   
    PlaceValue.ansClicked = false;
    PlaceValue.ansChecked = false;
    PlaceValue.denominatorArray = [];
    PlaceValue.numeratorArray = [];
    PlaceValue.randomDenominator=0;
    PlaceValue.sampleArray = [];
    PlaceValue.mainDenominatorArray = [4,5,6];  //multiple of this number for denominator
    PlaceValue.attemptCnt=0;
    PlaceValue.divCnt=0;    //number of divs count
}
PlaceValue.populate = function () {
    PlaceValue.numArray = [];
    PlaceValue.factorNumArray=[];
    for (var j = 0; j < 3; j++)   //find three main Factors from mainDenominatorArray=[4,5,6,7]
    {
        var mainDenon = Math.floor(Math.random() * (PlaceValue.mainDenominatorArray.length-1));
        PlaceValue.randomDenominator = PlaceValue.mainDenominatorArray[mainDenon];
        PlaceValue.mainDenominatorArray.splice(mainDenon, 1);
        PlaceValue.numArray.push(PlaceValue.randomDenominator);
        var factorRandNo=Math.floor(Math.random() * PlaceValue.randomDenominator)+1;
        PlaceValue.factorNumArray.push(factorRandNo);
    }
    console.log(PlaceValue.numArray);
  //  PlaceValue.numArray.sort(function(a,b){return b-a});
    for(var l=0;l< PlaceValue.numArray.length;l++)
    {
        PlaceValue.imageCountArray=[];
        var factorArray=[];
        for (var i = 1; i<5; i++)
        {
            var Dnum = PlaceValue.numArray[l];
            var Fnum = PlaceValue.factorNumArray[l];
            Dnum = Dnum * i;
            Fnum = Fnum * i;
            if(l==1)
            {
                if(i!=3)
                {
                    PlaceValue.imageCountArray.push(Dnum);
                    factorArray.push(Fnum);
                }
            }
            else
            {
                PlaceValue.imageCountArray.push(Dnum);
                factorArray.push(Fnum);
            }            
        }
        PlaceValue.sampleArray[l]=PlaceValue.imageCountArray;
        PlaceValue.factorCountArray[l]=factorArray;
    }
    PlaceValue.denomenators=[];
    for (var k = 0; k < 3; k++)
    {
        var denom=[];
        var nemerator=[];
        for(var i=0;i<3;i++)
        {
            var rNo=0;
            rNo = Math.floor(Math.random() * PlaceValue.sampleArray[k].length);
            while(PlaceValue.denomenators.includes( PlaceValue.sampleArray[k][rNo]))
                rNo = Math.floor(Math.random() * PlaceValue.sampleArray[k].length);
            PlaceValue.denomenators.push( PlaceValue.sampleArray[k][rNo]);
            denom.push( PlaceValue.sampleArray[k][rNo]);
            nemerator.push( PlaceValue.factorCountArray[k][rNo]);
        }       
        if(k==0)
        {
            denom.sort(function(a,b){return(a-b)});
            nemerator.sort(function(a,b){return(a-b)});
            PlaceValue.denominatorArray=PlaceValue.denominatorArray.concat(denom);
            PlaceValue.numeratorArray=PlaceValue.numeratorArray.concat(nemerator);
        }
        else if(k==1)
        {
            denom.sort(function(a,b){return(b-a)});
            nemerator.sort(function(a,b){return(b-a)});
            PlaceValue.denominatorArray=PlaceValue.denominatorArray.concat(denom);
            PlaceValue.numeratorArray=PlaceValue.numeratorArray.concat(nemerator);
        }
        else
        {
            PlaceValue.denominatorArray=PlaceValue.denominatorArray.concat(denom);
            PlaceValue.numeratorArray=PlaceValue.numeratorArray.concat(nemerator);
        }
    }
    console.log(PlaceValue.denominatorArray);
    console.log(PlaceValue.numeratorArray);  
}
PlaceValue.generateQue = function () {
    PlaceValue.ansClicked = false;
    PlaceValue.ansChecked = false;
    $("#check").css({ 'pointer-events': 'none' });
    PlaceValue.createGrid();
    if(PlaceValue.queCount==6  || PlaceValue.queCount==3)
        document.getElementById("que").innerHTML="";
    PlaceValue.createSpan();
}
PlaceValue.createSpan = function () {   //question
    d = new Date();  //date object
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();  //to get the current date
    var outerDiv = document.createElement("div");
    outerDiv.setAttribute("id", "outerDivQ" + PlaceValue.queCount);
    outerDiv.setAttribute("class", "nopadding col-sm-2 col-lg-2 col-md-2 col-xs-2");
    document.getElementById("que").appendChild(outerDiv);
    for (var i = 0; i < 2; i++)
    {
        var innerDiv = document.createElement("div");
        innerDiv.setAttribute("id", "innerDivQ" + i +""+PlaceValue.queCount);
        innerDiv.setAttribute("class", "nopadding spanStyle col-sm-6 col-lg-6 col-md-6 col-xs-6");
        document.getElementById("outerDivQ" + PlaceValue.queCount).appendChild(innerDiv);
        if(i==1)
        {
            for (var j = 0; j < 2; j++)
            {
                var queDiv = document.createElement("div");
                queDiv.setAttribute("id", "queDiv" + j +""+PlaceValue.queCount);
                queDiv.setAttribute("class", "nopadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
                document.getElementById("innerDivQ" + i +""+PlaceValue.queCount).appendChild(queDiv);
                if(j==0)
                {
                    $( "#queDiv" + j +""+PlaceValue.queCount).data("numData" ,PlaceValue.numeratorArray[PlaceValue.queCount]);
                    if(PlaceValue.queCount==0 || PlaceValue.queCount==3 || PlaceValue.queCount==6)
                        $( "#queDiv" + j +""+PlaceValue.queCount).text(PlaceValue.numeratorArray[PlaceValue.queCount]);
                    else
                        document.getElementById( "queDiv" + j +""+PlaceValue.queCount).innerHTML="?";
                    document.getElementById( "queDiv" + j +""+PlaceValue.queCount).style.borderBottom = "3px solid black";
                }
                else
                    document.getElementById( "queDiv" + j +""+PlaceValue.queCount).innerHTML = PlaceValue.denominatorArray[PlaceValue.queCount];
            }
        }
        else
        {
            if(PlaceValue.queCount!=0 && PlaceValue.queCount!=3 && PlaceValue.queCount!=6)
            {
                document.getElementById("innerDivQ" + i +""+PlaceValue.queCount).innerHTML="=";
                $("#innerDivQ" + i +""+PlaceValue.queCount).css({"margin-top":"3vh"});
            }
        }
    } 
}
PlaceValue.createGrid = function () {
    var shapesArray = ["circle","diamond","hexagone","star","triangle"];
    var rNo = Math.floor(Math.random() * shapesArray.length);
    PlaceValue.shape = shapesArray[rNo];  
    PlaceValue.colorFlag = false;
    var noOfShapes = PlaceValue.denominatorArray[PlaceValue.queCount];
    PlaceValue.starCount = noOfShapes;
    var k=PlaceValue.denominatorArray[PlaceValue.queCount]/PlaceValue.numArray[PlaceValue.divCnt];
    for (var i = 0; i < k; i++) {   //
        var outerDiv = document.createElement("div");
        outerDiv.setAttribute("id", "outerDiv" + (i + 1));
        outerDiv.setAttribute("class", "nopadding outerDivClass col-sm-12 col-lg-12 col-md-12 col-xs-12 ");
        document.getElementById("gridNumbers").appendChild(outerDiv);
        for (var j = 0; j <PlaceValue.numArray[PlaceValue.divCnt]; j++) {
            var innerDiv = document.createElement("div");
            innerDiv.setAttribute("id", "innerDiv" + i + "" + j);
            innerDiv.setAttribute("class", "nopadding innerDivClass col-sm-2 col-lg-2 col-md-2 col-xs-2");
            document.getElementById("outerDiv" + (i + 1)).appendChild(innerDiv);
            innerDiv.setAttribute("data", "on");

            starImg = document.createElement("img");
            starImg.setAttribute("id", "canvas" + i + "" + j);
            starImg.setAttribute("class", "nopadding col-sm-5 col-lg-5 col-md-5 col-xs-5  col-sm-offset-5 col-lg-offset-5 col-md-offset-5 col-xs-offset-5");
            starImg.setAttribute("onclick", "PlaceValue.changeColor(this.id)");
            document.getElementById("innerDiv" + i + "" + j).appendChild(starImg);
            document.getElementById("canvas" + i + "" + j).src = Utils.path + "images/"+PlaceValue.shape+""+".png";
        }
    }
}
PlaceValue.changeColor = function (object) {
    document.getElementById("audio").pause();
    clearInterval(PlaceValue.setTime);
    PlaceValue.ansClicked = true;
    $("#check").css({ 'pointer-events': 'auto' });
    var Data = document.getElementById(object).getAttribute("data");
    if (Data == "off") {
        PlaceValue.colorFlag = false;
        document.getElementById(object).setAttribute("data", "on");
        PlaceValue.ansCount--;
        document.getElementById(object).src = Utils.path + "images/"+PlaceValue.shape+""+".png";
    }
    else {
        PlaceValue.colorFlag = true;
        document.getElementById(object).setAttribute("data", "off");
        PlaceValue.ansCount++;
        document.getElementById(object).src = Utils.path + "images/"+PlaceValue.shape+""+"_slected.png";
    }
    //document.getElementById(object).style.pointerEvents="none";
    PlaceValue.colorFlag = false;
}

PlaceValue.checkAns = function () {
    document.getElementById("audio").pause();
    PlaceValue.attemptCnt++;
    if (PlaceValue.ansCount > 0) {
       
        var ans = PlaceValue.starCount *  PlaceValue.numeratorArray[PlaceValue.queCount] / PlaceValue.denominatorArray[PlaceValue.queCount];
        var ans1 = Math.round(ans);
        console.log(ans1);
        if (ans1 == PlaceValue.ansCount) {
            PlaceValue.ansChecked = true;
            PlaceValue.ansCount = 0;
           // scoredMarks = 10;
            document.getElementById("audio").src = Utils.path + 'sounds/Instructions/Right_answer__Aditi.mp3';
            document.getElementById("queDiv0"+PlaceValue.queCount).innerHTML=PlaceValue.numeratorArray[PlaceValue.queCount];
            document.getElementById("monkey").src = Utils.path + "images/Monkey_correct-ANS.png";
            $("#next").css({ 'pointer-events': 'none' });
            if (PlaceValue.setTimeToQue) {
                clearTimeout(PlaceValue.setTimeToQue);
                PlaceValue.setTimeToQue = null;
            }
            PlaceValue.setTimeToQue = setTimeout(function () {
                $("#next").css({ 'pointer-events': 'auto' });
                document.getElementById("monkey").src = Utils.path + "images/Monkey_01.png";
                PlaceValue.nextQue();
            }, 1500);
        }
        else {
           // scoredMarks = 0;
            document.getElementById("audio").src = Utils.path + 'sounds/Instructions/wrong_answer!_Aditi.mp3';
            document.getElementById("monkey").src = Utils.path + "images/Monkey_wrong-ANS.png";
            if (PlaceValue.wrongTimer) {
                clearTimeout(PlaceValue.wrongTimer);
                PlaceValue.wrongTimer = null;
            }
            PlaceValue.wrongTimer = setTimeout(function () {
                document.getElementById("monkey").src = Utils.path + "images/Monkey_01.png";
            }, 1500);
        }
        document.getElementById("audio").play();
    }
}
PlaceValue.nextQue = function () {
    if(PlaceValue.queCount==2 || PlaceValue.queCount==5)
        PlaceValue.divCnt++;
    PlaceValue.queCount++;
    document.getElementById("audio").pause();
    clearInterval(PlaceValue.setTimeToQue);
    clearTimeout(PlaceValue.wrongTimer);
    document.getElementById("monkey").src = Utils.path + "images/Monkey_01.png";
    if (PlaceValue.attemptCnt==1 && PlaceValue.ansChecked)
        scoredMarks = 10;
    else
        scoredMarks = 0;
    if (!PlaceValue.ansClicked)
        scoredMarks = -1;
    PlaceValue.scoreFunction();
    if (PlaceValue.queCount == 9) {
        document.getElementById("gamePage").style.display = "none";
        document.getElementById("finalPage").style.display = "block";
        PlaceValue.gameOver();
    }
    else {
        PlaceValue.ansCount = 0;
        PlaceValue.attemptCnt=0;
        PlaceValue.imageCountArray = [];
       // document.getElementById("que").innerHTML = "";
        document.getElementById("gridNumbers").innerHTML = "";
        PlaceValue.generateQue();
    }
}
PlaceValue.scoreFunction = function ()		//score Function
{
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
    }
}
PlaceValue.gameOver = function () {
    document.getElementById("audio").pause();
    clearInterval(PlaceValue.noResponseTimer);
    document.body.style.backgroundImage = Utils.path + "url('images/lastBG.png')";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("finalPage").style.display = "block";
    document.getElementById("acknowledgementDiv").innerHTML = "";
    document.getElementById('gameOver').innerHTML = PlaceValue.hardcodedData.message2;
    for (i = 0; i < Object.keys(PlaceValue.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(PlaceValue.AcknowledgementPageData)[i] + " : " + Object.values(PlaceValue.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 = PlaceValue.hardcodedData['createdOn'];
    acknowledgementDiv.appendChild(div);
    document.getElementById("acknowledgementDiv").style.display = "none";
}
PlaceValue.playAgain = function ()		//replay
{
    PlaceValue.play();
}
PlaceValue.returnback = function ()			//return to previous page (reload)
{
    document.getElementById("audio").pause();
    if (PlaceValue.ansClicked) {
        if (!PlaceValue.ansChecked)
            scoredMarks = 0;
        PlaceValue.scoreFunction();
    }
    location.reload(true);
}
PlaceValue.showCredits = function ()		//credits
{
    $("#acknowledgementDiv").show();
}
PlaceValue.playInstruction=function()
{
    document.getElementById("audio").src = Utils.path + 'sounds/Instructions/instruction.mp3';
    document.getElementById("audio").play();
}