//namespace
var Fraction = {};
var Utils = {};
Utils.Path = " ";
var resId = 0, questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, label =null, level = 1, scoreFlag = false,ansFlag = false,randomArray=[];
$(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;
    /* if (Utils.mobileDeviceFlag)
        Utils.Path = Android.getMediaPath("Fraction Equivalent"); */
    setTimeout(function () { Fraction.Initilize(); }, 200);
});
 Fraction.Initilize = function () {
	document.title = Fraction.hardcoded.gameName;
    Fraction.setImages(); //function that set all the images 
    document.getElementById("homeDiv").style.visibility = "hidden";
    document.getElementById("widget").style.display = "none";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("endPage").style.display = "none";
    document.body.style.backgroundImage = "url('images/skin/Cover.jpg')";
    $("#playImage").addClass("pulse");
    Fraction.variableInitilization(); //function to declare and initilize all images
    Fraction.createAcknowledgementDivs(); //function to create acknowledgement Div
}
Fraction.setImages = function () {
    document.getElementById("homeImg").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("logoImg").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("playImage").src = Utils.Path + "images/skin/Play.png";
    document.getElementById("soundImage").src = Utils.Path + "images/skin/Sound.png";
    document.getElementById("nextImage").src = Utils.Path + "images/skin/Next.png";
    document.getElementById("creditImg").src = Utils.Path + "images/skin/Credits.png";
    document.getElementById("playagain").src = Utils.Path + "images/skin/Replay.png";
    document.getElementById("headingSpanId").innerHTML = Fraction.hardcoded.title;
 	document.getElementById("bookId").style.backgroundImage  = Utils.Path+"url('images/skin/Books.png')";
    document.getElementById("canvasDivId").style.backgroundImage  = Utils.Path+"url('images/skin/clock.png')";
    document.getElementById("canvasDivId2").style.backgroundImage  = Utils.Path+"url('images/skin/clock.png')";
	document.getElementById("correctWrongImage2").src = Utils.Path+"images/skin/Doll_1.png";
}
Fraction.variableInitilization = function () {
    Fraction.numOfSection = 0;  //used to divide the circle into number of part
    Fraction.numOfColorPart = 0;//used to color the number of part
    Fraction.arc = 0;//used to calculate the angle according to num of section
    Fraction.angle = 0;
    Fraction.optionArray = [];  //used to store array
    Fraction.mainOptionArray = []; //store option pair(numarator and denomrator)
    Fraction.quesCount = 0;//number of attempts
    Fraction.Answer = 0; //answer of the question
    Fraction.correctImgTimerId = 0;//timer for the correct image after correct ans
    Fraction.wrongImgTimerID = 0;//timer for rhe wrong image
    Fraction.ansCount = 0;//used for count correct ans
    Fraction.rightAns = 0;
    Fraction.autoNextTimerID = 0;
    Fraction.flag = false;
    Fraction.ctx; //varible to get context of the canvas
    Fraction.radius;
    Fraction.x; //x cordinate for where to start canvas horizontally
    Fraction.y; // y cordinate for where to start canvas vertically
    Fraction.reducedNumerator=0;
    Fraction.reducedDenominator =0 ;
}
Fraction.startGame = function () {
    Fraction.playInstruction();
    document.getElementById("coverPage").style.display = "none";
    document.getElementById("homeDiv").style.visibility = "visible";
    document.getElementById("widget").style.display = "block";
    document.getElementById("gamePage").style.display = "block";
    document.body.style.backgroundImage = Utils.Path+"url('images/skin/Game-bg.png')";
 
    Fraction.createCanvas();
    Fraction.drawCircle();
}
Fraction.createCanvas = function () {//function to create canvas and optioDiv
   var  width = canvasDivId.offsetWidth;
   var  height = canvasDivId.offsetHeight;
    canvasTag = document.createElement("canvas");
    canvasTag.setAttribute("id", "canvasId");
    canvasTag.setAttribute("width",width);
    canvasTag.setAttribute("height",height);
    document.getElementById("canvasDivId").appendChild(canvasTag);
    var canvasElement = document.getElementById("canvasId");
    Fraction.ctx = canvasElement.getContext('2d');
    canvasElement.style.width = "99%";
    canvasElement.style.height = "101%"; 
    Fraction.radius = (canvasElement.width/2.7), Fraction.x = (canvasElement.width / 2.25), Fraction.y = (canvasElement.height / 2);
    for (var i = 0; i < 4; i++) {  //create Div for the option
        optionDiv = document.createElement("div");
        optionDiv.setAttribute("id", "optionDivID" + i);
        optionDiv.setAttribute("class", "nopadding optionDivClass col-sm-3 col-xs-3 col-md-3");
        optionDiv.setAttribute("onclick", "Fraction.checkAnswer(this.id)");
	    document.getElementById("innerOptionDivId").appendChild(optionDiv);
		document.getElementById("optionDivID"+i).style.backgroundImage = 'url('+"images/skin/Cube_"+i+".png"+')';
	    numartorDiv = document.createElement("div"); //div for numerator value of option
        numartorDiv.setAttribute("id", "numaratorID" + i);
        numartorDiv.setAttribute("class", "nopadding numartorDivlass col-sm-5 col-xs-5 col-lg-5 col-md-5 col-sm-offset-3 col-xs-offset-3 col-lg-offset-3 col-md-offset-3");
        optionDiv.appendChild(numartorDiv);
	    DenomratorDiv = document.createElement("div");//div for denomator value of option
        DenomratorDiv.setAttribute("id", "denomratorID" + i);
        DenomratorDiv.setAttribute("class", "nopadding denomratorDivClass col-sm-5 col-xs-5 col-lg-5 col-md-5 col-sm-offset-3 col-xs-offset-3 col-lg-offset-3 col-md-offset-3");
        optionDiv.appendChild(DenomratorDiv);
	}
}
Fraction.drawCircle = function () {//function to draw and divide circle
    d = new Date();  //date object
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();  //to get the current date 
    scoreFlag = false;
    Fraction.calculateSection();
    Fraction.calculateOption();
    Fraction.ctx.beginPath();
    Fraction.ctx.arc(Fraction.x, Fraction.y, Fraction.radius, 0, 2 * Math.PI);
    Fraction.ctx.closePath();
    for (var i = 0; i < Fraction.numOfSection; i++) {
        Fraction.arc = Math.PI * 2 / Fraction.numOfSection;
        Fraction.angle = -(0 + Fraction.arc * i);
        if (i < Fraction.numOfColorPart)
            Fraction.ctx.fillStyle = "darkblue";
        else
            Fraction.ctx.fillStyle = "white";
        Fraction.ctx.beginPath();
        Fraction.ctx.lineTo(Fraction.x, Fraction.y);
        Fraction.ctx.arc(Fraction.x, Fraction.y, Fraction.radius, Fraction.angle, Fraction.angle + Fraction.arc, false);
        Fraction.ctx.arc(Fraction.x, Fraction.y, 1, Fraction.angle + Fraction.arc, Fraction.angle, true);
        Fraction.ctx.fill();
        Fraction.ctx.lineWidth = 2;
        Fraction.ctx.strokeStyle = "black";
        Fraction.ctx.stroke();
    }
}
Fraction.calculateSection = function () {//calculate random num to divide the circle
    Fraction.numOfSection = Math.floor(Math.random() * 10) + 1;
    Fraction.numOfColorPart = Math.floor(Math.random() * Fraction.numOfSection - 1) + 1;
     if (Fraction.numOfSection <= 2 || Fraction.numOfColorPart <= 0) {
        Fraction.calculateSection();
     }
}
Fraction.findHCF = function(){
    var factArr1=[],factArr2 = [];

    for(var i = 1; i <=  Fraction.numOfSection/2;i++){
            if( Fraction.numOfSection % i == 0)
                 factArr1.push(i);
    }
    for(var i = 1; i <=Fraction.numOfColorPart ;i++){
        if( Fraction.numOfColorPart % i == 0)
        factArr2.push(i);
    }
    factArr2.reverse();
   var found = factArr2.find( val => factArr1.includes(val) );
   Fraction.reducedNumerator = Fraction.numOfColorPart / found ;
   Fraction.reducedDenominator = Fraction.numOfSection / found;
   Fraction.optionArray.push(Fraction.reducedNumerator);
   Fraction.optionArray.push( Fraction.reducedDenominator );
    randomArray.push(Fraction.reducedNumerator);
     randomArray.push(Fraction.reducedDenominator);
   Fraction.mainOptionArray.push(Fraction.optionArray);
   Fraction.optionArray = [] ;
}
Fraction.calculateOption = function () {//function to calculate option 
   var temp1 , temp2;
    if ((Fraction.numOfColorPart % 2 == 0) && (Fraction.numOfSection % 2 == 0)) {
        Fraction.findHCF();
    }
    else{
          Fraction.findHCF();
          Fraction.option1 = Fraction.numOfColorPart*2;
          temp1 =Fraction.option1;
          Fraction.option1 = Fraction.numOfColorPart;
         Fraction.numOfColorPart = temp1;
      
        Fraction.option2 = Fraction.numOfSection*2;
        temp2 = Fraction.option2;
        Fraction.option2 = Fraction.numOfSection;
        Fraction.numOfSection = temp2;
    } 
      randomArray.push(Fraction.numOfColorPart);
      randomArray.push(Fraction.numOfSection);
  
      value = Fraction.numOfColorPart / Fraction.numOfSection;
    for (var i = 0; i < 3; i++) {
        while (Fraction.optionArray.length < 2) {
            var ransomoption1 = Math.floor(Math.random() * ((20-11)+11))+1;
            var ransomoption2 =  Math.floor(Math.random() * ((ransomoption1-11)+11))+1;
            if (ransomoption2 / ransomoption1  != value && ransomoption2 / ransomoption1 != 1){
                Fraction.optionArray.push(ransomoption1);
                Fraction.optionArray.push(ransomoption2);
                //randomArray.push(ransomoption1);
            }
        }
        Fraction.optionArray.sort(function (a, b) { return a - b }); //sort the num in the desc
        Fraction.mainOptionArray.push(Fraction.optionArray);
        Fraction.optionArray = [];
    }
    console.log(Fraction.mainOptionArray);
   Fraction.mainOptionArray = shuffle(Fraction.mainOptionArray);
   randomArray = [] ;
    Fraction.setOption();
}
Fraction.setOption = function () {//set Option
    for (var i = 0; i < 4; i++) {
        document.getElementById("numaratorID" + i).innerHTML = Fraction.mainOptionArray[i][0];
        document.getElementById("denomratorID" + i).innerHTML = Fraction.mainOptionArray[i][1];
    }
}
Fraction.playInstruction = function () {//sound button
    document.getElementById("playSound").src = Utils.Path + "sounds/Instruction/instruction.mp3";
    document.getElementById("playSound").play();
}
 Fraction.checkAnswer = function (clicked_id) {//check ans
    var childs,numarValue,denomValue;
    document.getElementById("canvasDivId2").style.visibility="hidden";
    $(".bounceInDown").removeClass("bounceInDown");
    scoreFlag = true;
    ansFlag = false;
    childs = document.getElementById(clicked_id).children;
    numarValue = childs[0].innerHTML;
    denomValue = childs[1].innerHTML;
    Fraction.Answer = Fraction.numOfColorPart / Fraction.numOfSection;
    Fraction.clicked_answer = numarValue / denomValue;
    if (Fraction.Answer == Fraction.clicked_answer) {
        $("#nextButtonDiv").css('pointer-events', 'none');
        document.getElementById("playSound").pause();
        $("#" + clicked_id).css('pointer-events', 'none');
        $("#" + clicked_id).css('opacity', '0.5');
        $("#" + clicked_id).addClass('animated bounce');
        Fraction.ansCount++;
            $("#correctWrongImage2").css({"transform":"rotate(0deg)","top":"0vh"});
         document.getElementById("correctWrongImage2").src = Utils.Path + "images/skin/Doll-Correct.gif";
			document.getElementById("playSound").src = Utils.Path + "sounds/Instruction/Weldone.mp3";
            document.getElementById("playSound").play();
			$('.optionDivClass').css('pointer-events', 'none');
            scoredMarks = 10;
            lebel = Fraction.reducedNumerator + "/"+Fraction.reducedDenominator;
            if (Fraction.autoNextTimerID) {
                clearTimeout(Fraction.autoNextTimerID);
                Fraction.autoNextTimerID = null;
            }
            Fraction.autoNextTimerID = setTimeout(function () { Fraction.nextQuestion(); }, 3000);
          }
        
else {  // when answer is wrong
        ansFlag = true;
        scoredMarks = 0;
        label =numarValue +"/"+ denomValue;;
		document.getElementById("playSound").src = Utils.Path + "sounds/Instruction/Not_this_one__Aditi.mp3";
        document.getElementById("playSound").play();
        $("#" + clicked_id).addClass('animated shake');
        document.getElementById("correctWrongImage2").src = Utils.Path + "images/skin/Doll-Wrong.gif";
		if (Fraction.wrongImgTimerId) {
            clearTimeout(Fraction.wrongImgTimerId);
            Fraction.correctImgTimerId = null;
        }
      
        Fraction.wrongImgTimerId = setTimeout(function () {
           document.getElementById("correctWrongImage2").src = Utils.Path+"images/skin/Doll_1.png";
            $('.shake').removeClass('animated shake');
            document.getElementById("watchImg").src =" ";
            document.getElementById("watchImg").style.display="none";
            document.getElementById("canvasDivId").style.backgroundImage  = Utils.Path+"url('images/skin/clock.png')";
            $("#canvasDivId").show();
            $("#canvasId").show();
            }, 1000);
    }
    Fraction.showCanvas(numarValue,denomValue);
}
Fraction.showCanvas = function(numarValue,denomValue){
    $("#canvasDivId2").addClass("animated bounceInDown");
    document.getElementById("canvasDivId2").style.visibility="visible";
    var upValue  = numarValue;
    var downvalue = denomValue;
    var canvasWidth = canvasDivId2.offsetWidth;
    var canvasHeigth = canvasDivId2.offsetHeight;
    document.getElementById("canvas2").setAttribute("width",canvasWidth);
    document.getElementById("canvas2").setAttribute("height",canvasHeigth);
    var canvasElement2 = document.getElementById("canvas2");
    var contex = canvasElement2.getContext('2d');
    canvasElement2.style.width = "99%";
    canvasElement2.style.height = "101%"; 
    var r = (canvasElement2.width/2.7), xAxis = (canvasElement2.width / 2.25), yAxis = (canvasElement2.height / 2);
    contex.beginPath();
    contex.arc(xAxis, yAxis, r , 0, 2 * Math.PI);
    contex.closePath();
    for (var i = 0; i < downvalue; i++) {
        var canvasArc = Math.PI * 2 / downvalue;
        var angleValue = -(0 + canvasArc * i);
        if (i < upValue)
        contex.fillStyle = "orange";
        else
        contex.fillStyle = "white";
        contex.beginPath();
        Fraction.ctx.lineTo(xAxis, yAxis); 
        contex.arc(xAxis,yAxis,  r,angleValue, angleValue+canvasArc, false);
        contex.arc(xAxis,yAxis, 1, angleValue + canvasArc,angleValue, true);
        contex.fill();
        contex.lineWidth = 2;
        contex.strokeStyle = "black";
        contex.stroke();
    }
}
Fraction.nextQuestion = function () {
    clearTimeout(Fraction.wrongImgTimerId);
    clearTimeout(Fraction.autoNextTimerID);
    $("#nextButtonDiv").css('pointer-events', 'auto');
    document.getElementById("canvasDivId2").style.visibility="hidden";
    document.getElementById("playSound").pause();
    $("#correctWrongImage2").css({"transform":"rotate(-90deg)","top":"16vh"});
    Fraction.quesCount++;
    Fraction.ansCount = 0;
    Fraction.ctx.clearRect(0, 0, canvasTag.width, canvasTag.height); //function to clear canvas
    Fraction.mainOptionArray = [];
    Fraction.ansArray = [];
    Fraction.flag = false;
	$('.shake').removeClass('animated shake');
    $('.bounce').removeClass('animated bounce'); 
    document.getElementById("correctWrongImage2").src = Utils.Path+"images/skin/Doll_1.png";
    $('.optionDivClass').css('pointer-events', 'auto');
    $('.optionDivClass').css('opacity', '1');
    for (var i = 0; i < 4; i++) {
        document.getElementById("numaratorID" + i).innerHTML = " ";
        document.getElementById("denomratorID" + i).innerHTML = " ";
    }
    
    if (!scoreFlag){ //when question skip
        scoredMarks = -1;
        label = null;
    }
     Fraction.scoreFunction();

    if (Fraction.quesCount < 5) 
        Fraction.drawCircle();
    else 
        Fraction.gameOver();
    
}
Fraction.replayGame = function () {
    document.getElementById("playSound").pause();
    Fraction.ctx.clearRect(0, 0, canvasTag.width, canvasTag.height);
    document.getElementById("innerOptionDivId").innerHTML = " ";
    document.getElementById("GameOver").innerHTML = " ";
    document.getElementById("acknowledgementDiv").style.display = "none";
    document.getElementById("endPage").style.display = "none";
    $("#correctWrongImage2").css({"transform":"rotate(-90deg)","top":"16vh"});
     Fraction.variableInitilization();
     Fraction.startGame();
}
Fraction.gameOver = function () {
    document.getElementById("playSound").pause();
    document.getElementById("endPage").style.display = "block";
    document.getElementById("widget").style.display = "none";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("GameOver").innerHTML = Fraction.hardcoded.gameOver;
}
Fraction.callHome = function () {
    if (!scoreFlag == false) {
        scoredMarks = 0;
        lebel = " ";
        Fraction.scoreFunction();
    }
    else {
        scoredMarks = 10;
        lebel = " ";
        Fraction.scoreFunction();
    }
    location.reload();
}
Fraction.createAcknowledgementDivs = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(Fraction.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(Fraction.AcknowledgementPageData)[i] + " : " + Object.values(Fraction.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.style.marginBottom = "2vh";
    acknowledgementDiv.appendChild(div);
}
Fraction.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();

}
Fraction.scoreFunction = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
    }
}
