var PlaceValue = {};
var Utils = {};
Utils.path = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, label="", scoreFlag = false;
PlaceValue.seconds=0;
$(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/BG.png')";
  //  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/Skip.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/Next.png";
}

PlaceValue.play = function () {
    document.body.style.backgroundImage = Utils.path + "url('images/FullBG.jpg')";
    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.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.spliceQueArray = [];
    PlaceValue.queArray = [];
    PlaceValue.numArray1=[];
    PlaceValue.randomDenominator=0;
    PlaceValue.sampleArray = [];
    PlaceValue.mainDenominatorArray = [4,5,6,7];  //multiple of this number for denominator
    PlaceValue.attemptCnt=0;
    PlaceValue.attemptFlag=false;
    PlaceValue.divCnt=0;    //number of divs count
    PlaceValue.seconds=0;
    PlaceValue.total_No_of_Questions=5;
    PlaceValue.correctCounter=0;
}
PlaceValue.populate = function () {
    PlaceValue.numArray = [];
    PlaceValue.factorNumArray=[];
    for (var j = 0; j < 2; j++)
    {
        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);
   //laceValue.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 < 2; k++)
    {
        var denom=[];
        var nemerator=[];
        var limit=3
        if(k==1)
            var limit=2
        for(var i=0;i<limit;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
        {
            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);
        }
    }
    console.log(PlaceValue.denominatorArray);
    console.log(PlaceValue.numeratorArray);
    for(var i=0;i<PlaceValue.numeratorArray.length;i++)
        PlaceValue.spliceQueArray.push(i);
    console.log(PlaceValue.spliceQueArray);
    PlaceValue.populateQueArray();
}
PlaceValue.populateQueArray = function () { //PlaceValue.queArray
    PlaceValue.queArray = [];
    var dummyNumeratorArray=["?","?","?","?","?"];
    dummyNumeratorArray[0]=PlaceValue.numeratorArray[0];
    dummyNumeratorArray[3]=PlaceValue.numeratorArray[3];
   // console.log(dummyNumeratorArray);
    t1 = []
    mid = 3
    end = 1
    for(i=0; i < mid; i++)
    {
    for(j=0; j < end; j++)
        t1.push([dummyNumeratorArray[j],PlaceValue.denominatorArray[j]])
    end++
    PlaceValue.queArray.push(t1)
    t1 = []
    }
    t2 = []
    end2 = 4
    for(i = mid; i<5; i++)
    {
    for(j=mid; j<end; j++)
       t1.push([dummyNumeratorArray[j],PlaceValue.denominatorArray[j]])
    end++
    PlaceValue.queArray.push(t1)
    t1 = []
    }
    console.log(PlaceValue.queArray)
   // PlaceValue.numArray=[6,6,6,5,5];
    for(var i=0;i<PlaceValue.numeratorArray.length;i++)
    {
        var j=0;
        if(i>=3)
            j=1;
        PlaceValue.numArray1.push(PlaceValue.numArray[j]);
    }
    console.log(PlaceValue.numArray1);
}
PlaceValue.generateQue = function () {
    PlaceValue.ansClicked = false;
    PlaceValue.ansChecked = false;
    scoreFlag = false;
    $("#check").css({ 'pointer-events': 'none' });
    PlaceValue.createGrid();
    document.getElementById("que").innerHTML="";
    PlaceValue.createSpan();
   
}
PlaceValue.createSpan = function () {   // show question
    PlaceValue.startTimer();
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    for(var m=0;m<PlaceValue.queArray[PlaceValue.queCount].length;m++)
    {
    var outerDiv = document.createElement("div");
    outerDiv.setAttribute("id", "outerDivQ" + m);
    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 +""+m);
        innerDiv.setAttribute("class", "nopadding spanStyle col-sm-6 col-lg-6 col-md-6 col-xs-6");
        document.getElementById("outerDivQ" + m).appendChild(innerDiv);
        if(i==0)    // for = sign
        {
            if(m!=0 && m!=3)
            {
                document.getElementById("innerDivQ" + i +""+m).innerHTML="=";
                $("#innerDivQ" + i +""+m).css({"margin-top":"3vh"});
            }
        }
        else    //for que num and denom
        {
            for (var j = 0; j < 2; j++)
            {
                var queDiv = document.createElement("div");
                queDiv.setAttribute("id", "queDiv" + j +""+m);
                queDiv.setAttribute("class", "nopadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
                document.getElementById("innerDivQ" + i +""+m).appendChild(queDiv);
                if(j==0)
                {
                    $( "#queDiv" + j +""+m).data("numData" ,PlaceValue.queArray[PlaceValue.queCount][m][0]);
                    $( "#queDiv" + j +""+m).text(PlaceValue.queArray[PlaceValue.queCount][m][0]);
                    document.getElementById( "queDiv" + j +""+m).style.borderBottom = "3px solid black";
                }
                else
                    document.getElementById( "queDiv" + j +""+m).innerHTML = PlaceValue.queArray[PlaceValue.queCount][m][1];
            }
        }
    }
}
}
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 m=PlaceValue.queArray[PlaceValue.queCount].length-1;
    var noOfShapes =PlaceValue.queArray[PlaceValue.queCount][m][1];
    PlaceValue.starCount = noOfShapes;
    var k=PlaceValue.queArray[PlaceValue.queCount][m][1]/PlaceValue.numArray1[PlaceValue.queCount];
    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.numArray1[PlaceValue.queCount]; 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);
    clearInterval(PlaceValue.noResponseTimer);
    clearTimeout(PlaceValue.timeOut);
    PlaceValue.seconds=0;
    PlaceValue.startTimer();
    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";
    }
    PlaceValue.colorFlag = false;
}

PlaceValue.checkAns = function () {
    clearInterval(PlaceValue.noResponseTimer);
    clearTimeout(PlaceValue.timeOut);
    document.getElementById("audio").pause();
    scoreFlag = true;
    if (PlaceValue.ansCount > 0) {
        var m=PlaceValue.queArray[PlaceValue.queCount].length-1;
        var ans =PlaceValue.numeratorArray[PlaceValue.spliceQueArray[PlaceValue.queCount]];
        var ans1 = Math.round(ans);
        console.log(ans1);
        if (ans1 == PlaceValue.ansCount) {
            PlaceValue.ansChecked = true;
            PlaceValue.ansCount = 0;
            scoredMarks = 10;
            PlaceValue.correctCounter++;
            document.getElementById("audio").src = Utils.path + 'sounds/Instructions/Right_answer__Aditi.mp3';
            document.getElementById("monkey").src = Utils.path + "images/Monkey_correct-ANS.png";
            $("#next").css({ 'pointer-events': 'none' });
        }
        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";
        }
        document.getElementById("audio").play();
        var k=PlaceValue.queArray[PlaceValue.queCount].length-1;
        document.getElementById("queDiv0"+k).innerHTML=ans1;
       
       /*  if(PlaceValue.ansClicked)
        {
        PlaceValue.numArray1.splice(PlaceValue.queCount,1);
        PlaceValue.queArray.splice(PlaceValue.queCount,1);//numArray1
        PlaceValue.spliceQueArray.splice(PlaceValue.queCount,1);
        }
        console.log(PlaceValue.spliceQueArray); */
        PlaceValue.scoreFunction();
        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);
    }
}
PlaceValue.nextQue = function () {
    document.getElementById("audio").pause();
    clearInterval(PlaceValue.noResponseTimer);
    clearTimeout(PlaceValue.timeOut);
    clearInterval(PlaceValue.setTimeToQue);
    clearTimeout(PlaceValue.wrongTimer);
    var m=PlaceValue.queArray[PlaceValue.queCount].length-1;
    var ans =PlaceValue.numeratorArray[PlaceValue.spliceQueArray[PlaceValue.queCount]];
    var ans1 = Math.round(ans);
   
    if(PlaceValue.ansClicked)
    {
        if(PlaceValue.spliceQueArray[PlaceValue.queCount]==1)
        {
            PlaceValue.queArray[PlaceValue.queCount+1][m][0]=ans1;
        }
    PlaceValue.numArray1.splice(PlaceValue.queCount,1);
    PlaceValue.queArray.splice(PlaceValue.queCount,1);//numArray1
    PlaceValue.spliceQueArray.splice(PlaceValue.queCount,1);
    }
    else if(scoreFlag!=true)
    {
        PlaceValue.queCount++;
    }
    console.log(PlaceValue.spliceQueArray);
    document.getElementById("monkey").src = Utils.path + "images/Monkey_01.png";
   
    if(PlaceValue.queArray.length==0)
    {
        PlaceValue.gameOver();
    }
    else if(PlaceValue.queCount==PlaceValue.queArray.length)
    {
        clearInterval(PlaceValue.noResponseTimer);
        clearTimeout(PlaceValue.timeOut);
        document.getElementById("responseBoxDiv").style.display="block";
        document.getElementById("No").innerHTML=PlaceValue.modalData.no;
        document.getElementById("Yes").innerHTML=PlaceValue.modalData.yes;
        document.getElementById("questionMsg").innerHTML=PlaceValue.modalData.responseMsg;
    }
    else
    {
        PlaceValue.ansCount = 0;
        PlaceValue.attemptCnt=0;
        PlaceValue.divCnt=0;
        PlaceValue.imageCountArray = [];
        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);
    clearTimeout(PlaceValue.timeOut);
    $("#creditDiv").addClass("blink_me");
	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("responseBoxDiv").style.display="none";
    document.getElementById("widget").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.createStars();
	PlaceValue.giveStars();
}
PlaceValue.showSkippedQuestions=function()
{
	document.getElementById("responseBoxDiv").style.display="none";
    PlaceValue.ansCount=0;
    PlaceValue.queCount=0;
    PlaceValue.imageCountArray=[];
    document.getElementById("que").innerHTML="";
    document.getElementById("gridNumbers").innerHTML="";
    PlaceValue.generateQue();
}
//function which creates star divs
PlaceValue.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);
	}
};

PlaceValue.giveStars=function()
{
	var fractionVar,i,temp; 
	var numberOfStars=0;
	ans=PlaceValue.total_No_of_Questions/5;
	temp=PlaceValue.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(PlaceValue.correctCounter,PlaceValue.total_No_of_Questions,"1");
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(PlaceValue.correctCounter,PlaceValue.total_No_of_Questions,"1");
};
PlaceValue.startTimer=function()
{
	if(PlaceValue.noResponseTimer)
	{
		clearInterval(PlaceValue.noResponseTimer);
		PlaceValue.noResponseTimer=null;
		PlaceValue.seconds=0;
	}	
	PlaceValue.noResponseTimer=setInterval(function() 
	{
		PlaceValue.seconds++;
		if(PlaceValue.seconds>=5)
		{
			document.getElementById("audio").src=Utils.path+"sounds/instructions/please_ans_the_ques.mp3";
			document.getElementById("audio").play(); 
			clearInterval(PlaceValue.noResponseTimer);
			if(PlaceValue.timeOut)
			{
				clearTimeout(PlaceValue.timeOut);
				PlaceValue.timeOut=null;
			}
				PlaceValue.timeOut=setTimeout(function()
			{
				PlaceValue.seconds=0;
				PlaceValue.startTimer();
			},2000);
		}
	},1000);
};
PlaceValue.goNext=function()
{
	clearInterval(PlaceValue.skipTimer);
	if(Utils.mobileDeviceFlag)
        Android.GotoNextGame();
    else
        location.reload();
}

function getDuration(src) {
	var duration = 0;
	//if (ShowMe.soundFlag) {
	$('#audio').on("loadedmetadata", function () {
		duration = $('#audio').prop('duration');
		$('#audio').unbind("loadedmetadata");
		PlaceValue.playNextSound(duration);
	});
	$('#audio').prop('src', src);
}
