var Division = {}; //namespace
var Utils = {};
Utils.Path = "";
Division.numberOfDigit = 1; // number of digit of answer;
var resId = 0, questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, label = "word", level = 1, scoreFlag = false, number = 0, text='',clicked_id='';
$(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("Division"); */
    setTimeout(function () { Division.Initilize(); }, 200);
});
Division.Initilize = function () {
    Division.setImage();
	document.title = Division.hardcoded.gameTitle;
    document.getElementById("homeDiv").style.visibility = "hidden";
    document.getElementById("widgeDiv").style.display = "none";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("endPage").style.display = "none";
    document.body.style.backgroundImage = "url('images/skin/Cover.png')";
    Division.variableInitilization();
    Division.createAcknowledgementDivs();
}
Division.setImage = function () {
    document.getElementById("logoImg").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("homeImg").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("Nextstep").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("playAgain").src = Utils.Path + "images/skin/replay.png";
    document.getElementById("creditImg").src = Utils.Path + "images/skin/Credits.png";
	document.getElementById("gamePage").style.backgroundImage=Utils.Path+"url('images/skin/gadget_yellow.png')";
    document.getElementById("titleId").style.backgroundImage=Utils.Path+"url('images/skin/long-gray-button.png')";
    document.getElementById("titleId").innerHTML = Division.hardcoded.title;
    document.getElementById("scoreId").innerHTML = Division.hardcoded.scoreText;
}
Division.variableInitilization = function () {
    Division.index = 0;
    Division.num1 = 0; // muitiplication number1
    Division.num2 = 0; //multiplication number 2
    Division.DivId = 0; //variable contain id of the ans div
    Division.level = 0; //game level {0,1,2,3,4}
    Division.quesCount = 0;
    Division.ansCount = 0; //count for the correct ans
	Division.ansLevel = 1;
    Division.noOfAns = 0; // variable for to display score on the top of the gamePage
    Division.quesLevel = 1;
    Division.correctGreenColor; //timer for the calculator button color chnage 
    Division.autoNextTimer; //automatically next quetion timer
    Division.wrongRedColorTimerId;
    Division.pointertimer;
    Division.answerFlag = false;//flag to identify clicked answer div
    Division.randomNumberArray = [];  //array that contain two random number for multiplication logic
	Division.Divisorarray = []; // array that contains two node and each node contain divisor of the divident
    Division.multiplicationAnswer = []; //array which contain the divident
}
Division.startGame = function () {
    Division.playInstruction();
    document.body.style.backgroundImage = "url('images/skin/BG1.jpg')";
    document.getElementById("gamePage").style.display = "block";
    document.getElementById("playGame").style.display = "none";
    document.getElementById("widgeDiv").style.display = "block";
    document.getElementById("endPage").style.display = "none";
    document.getElementById("homeDiv").style.visibility = "visible";
	document.getElementById("gameOver").innerHTML = " ";
    numberKey(); //numberPad function
    Division.randomCalculation();
    Division.equationDiv();
    Division.setEquation(1, 1);
}
Division.playInstruction = function () { //sound button
    document.getElementById("playSound").src = Utils.Path + "sound/instruction/simpleDivision_Instruction.mp3";
    document.getElementById("playSound").play();
}
Division.randomCalculation = function () {//two random number for multiplication
    while (Division.randomNumberArray.length < 4) 
	{
         var number1 = Math.floor(Math.random() * 10);
        if (number1 > 1 && number1 < 10) {
            if (Division.randomNumberArray.indexOf(number1) == -1) {
                Division.randomNumberArray.push(number1);
            }
        }
    }
    Division.calculation();
}
Division.calculation = function () {//calculation to make equation
    var j = 0, index = 0,i=0;
    for (i = 0; i < 2; i++) {
		Division.num1 = Division.randomNumberArray[j];
        Division.num2 = Division.randomNumberArray[j + 1];
        if ((Division.num1 * Division.num2) > 9) {//formula for divident of the equation 
            Division.multiplicationAnswer.push(Division.num1 * Division.num2);
            j = 2;
        }
        else {
            Division.multiplicationAnswer = [];
            Division.randomNumberArray = [];
            Division.Divisorarray = [];
            Division.randomCalculation();
        }
	}
}
Division.equationDiv = function () {//create div and set value
      var DivTag, equDiv;
      //score
      document.getElementById("score").innerHTML = Division.noOfAns + Division.hardcoded.score;
     for (var i = 0; i < 2; i++){ //Question Div
        DivTag = document.createElement("div");
        DivTag.setAttribute("id", "divId" + i);
        DivTag.setAttribute("class", "nopadding divIdClass col-sm-12 col-xs-12 col-lg-12 col-md-12");
        var innerDivTag = document.createElement("div");
        innerDivTag.setAttribute("id", "innerDivId" + i);
        innerDivTag.setAttribute("class", "nopadding innerDivClass col-sm-6 col-xs-6 col-md-6 col-lg-6");
        innerDivTag.style.backgroundImage =Utils.Path+"url('images/skin/gray_button.png')";
        DivTag.appendChild(innerDivTag);
        for (var j = 0; j < 3; j++) {
            spanTag = document.createElement("span");
            spanTag.setAttribute("id", "spanId" + i + j);
            spanTag.setAttribute("class", "nopadding spanIDclass");
            innerDivTag.appendChild(spanTag);
        }
		//equal Sign Div
		var equalSign = document.createElement("div");
		equalSign.setAttribute("id","equalSign"+i);
		equalSign.setAttribute("class","nopadding equalClass col-sm-1 xol-xs-1 col-lg-1 col-md-1");
		equalSign.innerHTML=Division.hardcoded.equalSign;
		DivTag.appendChild(equalSign);
        // AnswerDiv
        var equDiv = document.createElement("div");
        equDiv.setAttribute("id", "AnswerDivId" + i);
        equDiv.setAttribute("class", "nopadding AnswerDivIdclass answer col-sm-5 col-xs-5 col-md-5 col-lg-5");
        equDiv.setAttribute("questionId", i);
		equDiv.style.backgroundImage =Utils.Path+"url('images/skin/gray_button.png')";
        equDiv.setAttribute("onclick", "Division.shownumberPad(this.id)");
		 equDiv.innerHTML = " ";
        DivTag.appendChild(equDiv);
        document.getElementById("questionDiv").appendChild(DivTag);
        $("#AnswerDivId0").addClass('blink_me');
        $("#AnswerDivId0").removeClass('answer');
	}
}
//function to set the equation
Division.setEquation = function (levelValue, questionLevel) {
	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 k = 0,numLen,numArray,splitatedNumber,i,j;
    scoreFlag = false;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            if (j == 0) {
                 splitatedNumber = numberSplit(levelValue * Division.multiplicationAnswer[i]);
                 numLen = splitatedNumber.length;
                 numArray = splitatedNumber.toString();
                for (let m = 0; m < numLen; m++) {
                    var innerSpan = document.createElement("span");
                    innerSpan.setAttribute("id", "innerSpanId" + i + m);
                    innerSpan.setAttribute("class", "nopadding spanClass");
                    innerSpan.innerHTML = numArray[m];
                    if (i == 0)
                        document.getElementById("spanId00").appendChild(innerSpan);
                    else
                        document.getElementById("spanId10").appendChild(innerSpan);
				}
			}
			else if (j == 1) {
                document.getElementById("spanId" + i + j).innerHTML = Division.hardcoded.DivisionSign;
            }
            else if (j == 2) {
                document.getElementById("spanId" + i + j).innerHTML = Division.randomNumberArray[k] * questionLevel;
            }
        }
        k = k + 2;
    }
    Division.colorQuesZero();
    $("#keyPadDiv").css('pointer-events', 'auto');
}
Division.colorQuesZero = function(){//color zero level wise
    if (Division.level == 1) 
        $("#innerSpanId02,#innerSpanId12").addClass("highlightZero");
    else if (Division.level == 2) 
        $("#innerSpanId03,#innerSpanId13,#innerSpanId04,#innerSpanId14").addClass("highlightZero");
    else if (Division.level == 4) 
        $("#innerSpanId04,#innerSpanId14").addClass("highlightZero");
}
//function to display number into answer Div from numberPad
function displayNumber(elementInformation) {
    scoreFlag = true;
    clearTimeout(Division.pointertimer);
    document.getElementById(elementInformation.id).style.color="black";
    setTimeout(function()
    { 
         document.getElementById(elementInformation.id).style.color ='white';  
    }, 250);
    if (Division.answerFlag == false) { //id of the answerDiv who has blink_me class
        Division.DivId = $('.blink_me').attr("id");
	}
    clicked_id = elementInformation.id;  //id of the clicked button of the numberPad
     $('.flash').removeClass("flash");
    if (Division.colorTimerId) {
        clearTimeout(Division.colorTimerId);
        Division.colorTimerId = null;
    }
    $("#" + clicked_id).addClass('NumberColorClass');
    Division.colorTimerId = setTimeout(function () { $("#" + clicked_id).removeClass('NumberColorClass'); }, 200);
    text = $("#" + clicked_id).text();
    if (($("#" + Division.DivId).text()).length < 4){
    if (Division.DivId == 'AnswerDivId0') {
                var ansSpan = document.createElement("span");
                ansSpan.setAttribute("id", "ansspanId" + number);
                ansSpan.setAttribute("class", "nopadding");
                ansSpan.append(text);
                document.getElementById(Division.DivId).appendChild(ansSpan);
			   number++;
			}
            else {
                var ansSpan = document.createElement("span");
                ansSpan.setAttribute("id", "ansspanId0" + number);
                ansSpan.setAttribute("class", "nopadding");
                ansSpan.append(text);
                document.getElementById(Division.DivId).appendChild(ansSpan);
                number++;
            }
    }
    if (document.getElementById(Division.DivId).getAttribute("questionId") == 0) {
		if (String(($("#" + Division.DivId).text())).length - 1 == Division.numberOfDigit) {
            if (Division.level == 3 || Division.level == 4) {
                if (Division.randomNumberArray[1] * 1 * Division.quesLevel == $("#" + Division.DivId).text()) {
                    $("#keyPadDiv").css('pointer-events', 'none');
                    Division.colorAnsZero();
                    Division.checkAnswer();
                }
                else {
                    $("#keyPadDiv").css('pointer-events', 'none');
					Division.wrongAnswer();
				}
			}
			else if (Division.randomNumberArray[1] * Division.ansLevel * Division.quesLevel == $("#" + Division.DivId).text()) {
                $("#keyPadDiv").css('pointer-events', 'none');
                Division.colorAnsZero();
				Division.checkAnswer();
            }
            else {
                $("#keyPadDiv").css('pointer-events', 'none');
					Division.wrongAnswer();
                }
        }
    }
    else {
			$('.flash').removeClass("flash");
			if (String(($("#" + Division.DivId).text())).length - 1 == Division.numberOfDigit) {
            if (Division.level == 3 || Division.level == 4) {
                if (Division.randomNumberArray[3] * 1 * Division.quesLevel == $("#" + Division.DivId).text()) {
                    $("#keyPadDiv").css('pointer-events', 'none');
                    Division.colorAnsZero();
                       Division.checkAnswer();
                }
                else {
                    $("#keyPadDiv").css('pointer-events', 'none');
					Division.wrongAnswer()
				}
			}
			else if (Division.randomNumberArray[3] * Division.ansLevel == $("#" + Division.DivId).text()) {
                $("#keyPadDiv").css('pointer-events', 'none');
                Division.colorAnsZero();
                 Division.checkAnswer();
			}
            else {
                $("#keyPadDiv").css('pointer-events', 'none');
					Division.wrongAnswer();
            }
        }
    }
}
Division.colorAnsZero = function(){//color ans zero
    if (Division.DivId == 'AnswerDivId0') {
       if (Division.level == 1||Division.level == 4) 
          $("#ansspanId1").addClass("highlightZero");
       else if (Division.level == 2) 
        $("#ansspanId1,#ansspanId2").addClass("highlightZero"); 
    }
    else{
        if (Division.level == 1||Division.level == 4)
              $("#ansspanId01").addClass("highlightZero");
        else if (Division.level == 2) 
           $("#ansspanId01,#ansspanId02").addClass("highlightZero");
    }
}
Division.shownumberPad = function (clicked_id) {//after clicking on answerDiv
    Division.answerFlag = true;
    Division.answerFlag = true;
    if(clicked_id == 'AnswerDivId0')
    {
        Division.DivId = clicked_id;
        $("#AnswerDivId1").removeClass("blink_me");
        $("#AnswerDivId0").addClass("blink_me");
        $("#AnswerDivId0").removeClass("answer");
        $("#AnswerDivId1").addClass("answer");
    }
    if(clicked_id == 'AnswerDivId1')
    {
        Division.DivId = clicked_id;
        $("#AnswerDivId0").removeClass("blink_me");
        $("#AnswerDivId1").addClass("blink_me");
        $("#AnswerDivId1").removeClass("answer");
        $("#AnswerDivId0").addClass("answer");
    }
    number = 0;
}
Division.checkAnswer = function () {// check ans is write or wrong
    clearTimeout(Division.wrongRedColorTimerId);
    clearTimeout(Division.correctGreenColor);
    clearTimeout(Division.pointertimer);
    Division.noOfAns++;
    $('#' + Division.DivId).css('pointer-events', 'none');
    $('.flash').removeClass("flash");
    document.getElementById("playSound").pause();
    $('#' + Division.DivId).css('color','green');
    if (Division.correctGreenColor) {
        clearTimeout(Division.correctGreenColor);
        Division.correctGreenColor = null;
    }
	   document.getElementById("playSound").src = "sound/instruction/Buzzercorrect 1.mp3";
       document.getElementById("playSound").play();
	   $("#" + Division.DivId).addClass('animated flash');
	   document.getElementById("gamePage").style.backgroundImage=Utils.Path+"url('images/skin/gadget_green.png')";
       number = 0;
       Division.ansCount++;
       Division.answerFlag = false;
       Division.correctGreenColor = setTimeout(function (){
        
        if ($("#" + Division.DivId).hasClass('blink_me')) {
            $("#" + Division.DivId).removeClass('blink_me');
		}
        for (var i = 0; i < 2; i++) {
            if ($("#AnswerDivId" + i).hasClass('answer')) {
                $("#AnswerDivId" + i).addClass('blink_me');
                $("#AnswerDivId" + i).removeClass('answer');
			}
        }
        document.getElementById("gamePage").style.backgroundImage=Utils.Path+"url('images/skin/gadget_yellow.png')";   $('#' + Division.DivId).css('color','black');
       },500);
       Division.pointertimer = setTimeout(function(){$("#keyPadDiv").css('pointer-events', 'auto');},1900);
			if (Division.autoNextTimer) {
				clearTimeout(Division.autoNextTimer);
				Division.autoNextTimer = null;
			}
            document.getElementById("score").innerHTML = Division.noOfAns + Division.hardcoded.score;
            if(Division.ansCount == 2){
              scoredMarks = 10;
				label = " ";
                Division.scoreFunction();
              Division.autoNextTimer = setTimeout(function () { Division.nextQuestion(); },2000);
	}
}
Division.wrongAnswer = function () {//when ans is wrong
    number = 0;
    clearTimeout(Division.pointertimer);
    clearTimeout(Division.correctGreenColor);
    clearTimeout(Division.wrongRedColorTimerId);
    document.getElementById("playSound").pause();
    $('.flash').removeClass("flash");
    document.getElementById("gamePage").style.backgroundImage=Utils.Path+"url('images/skin/gadget_red.png')"; 
    document.getElementById("playSound").src = "sound/instruction/wrongSound.mp3";
    document.getElementById("playSound").play();
    $('#' + Division.DivId).css('color','red');
    if (Division.wrongRedColorTimerId) {
        clearTimeout(Division.wrongRedColorTimerId);
        Division.wrongRedColorTimerId = null;
    }
    Division.wrongRedColorTimerId = setTimeout(function () { $("#" + Division.DivId).text(" ");
    $("#" + Division.DivId).innerHTML = " ";  $("#keyPadDiv").css('pointer-events', 'auto');
    document.getElementById("gamePage").style.backgroundImage=Utils.Path+"url('images/skin/gadget_yellow.png')";   $('#' + Division.DivId).css('color','black');
	}, 400);
}
Division.nextQuestion = function () {//function two next ques after correct ans
    clearTimeout(Division.wrongRedColorTimerId);
    clearTimeout(Division.correctGreenColor);
     document.getElementById("playSound").pause();
    if (scoreFlag == false) {
        scoredMarks = -1;
        label = " ";
        Division.scoreFunction();
    }
    if (scoreFlag == true && Division.ansCount == 1) {
        scoredMarks = 5;
        label = " ";
        Division.scoreFunction();
    }
    if (scoreFlag == true && Division.ansCount == 0) {
        scoredMarks = 0;
        label = " ";
        Division.scoreFunction();
	}
    Division.numberOfDigit++;
    document.getElementById("playSound").pause();
    clearTimeout(Division.autoNextTimer);
    Division.quesCount++;
    Division.level++;
    Division.ansCount = 0;
    Division.answerFlag=false;
    number = 0;
    $('.flash').removeClass("flash");
    if (Division.quesCount < 5) {
        Division.Divisorarray = [];
        Division.multiplicationAnswer = [];
        Division.randomNumberArray = [];
		document.getElementById("questionDiv").innerHTML = " ";
        document.getElementById("score").innerHTML=" ";
        Division.randomCalculation();
        Division.equationDiv();
        switch (Division.level) {
            case 1:
                Division.ansLevel = 10;
                Division.setEquation(10, 1);
                break;

            case 2:
                Division.ansLevel = 100;
                Division.setEquation(100, 1);
                break;

            case 3: Division.ansLevel = 10;
                Division.numberOfDigit = 1
                Division.setEquation(10, 10);
                break;

            case 4: Division.ansLevel = 100;
                Division.quesLevel = 10;
                Division.numberOfDigit = 2;
                Division.setEquation(100, 10);
		}
    }
    else {
        Division.gameOver();
    }
}
 Division.gameOver = function () {
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("widgeDiv").style.display = "none";
    document.getElementById("endPage").style.display = "block";
    document.getElementById("gameOver").innerHTML = Division.hardcoded.gameOver;
 }
Division.replayGame = function () {
    $('.flash').removeClass("flash");
    document.getElementById("acknowledgementDiv").style.display = "none";
    document.getElementById("questionDiv").innerHTML = " ";
     document.getElementById("keyPadDiv").innerHTML = " ";
     document.getElementById("score").innerHTML = " ";
     document.getElementById("gameOver").innerHTML = " ";
     Division.numberOfDigit = 1;
     Division.variableInitilization();
     Division.startGame();
}
//function to redirect to the home page by clicking on home image
Division.goBack = function () {
    document.getElementById("playSound").pause();
    if (scoreFlag == false) {
        scoredMarks = 0;
        label = " ";
        Division.scoreFunction();
    }
    if (scoreFlag == true && Division.ansCount == 1) {
        scoredMarks = 5;
        label = " ";
        Division.scoreFunction();
	}
    if (scoreFlag == true && Division.ansCount == 2) {
        scoredMarks = 10;
        label = " ";
        Division.scoreFunction();
    }
    location.reload();
}
function clearText() {
    $('.flash').removeClass("flash");
    if (Division.level == 1 || Division.level == 4) {
        Division.numberOfDigit = 2;
    }
    else if (Division.level == 2) {
        Division.numberOfDigit = 3;
    }
    else if (Division.level == 3) {
        Division.numberOfDigit = 1;
    }
    else {
        Division.numberOfDigit = 1;
    }
    number = 0;
    var ansDiv = $('.blink_me').attr("id");
    document.getElementById(ansDiv).innerHTML = " ";
}
Division.createAcknowledgementDivs = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(Division.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(Division.AcknowledgementPageData)[i] + " : " + Object.values(Division.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);
}
Division.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();
}
Division.scoreFunction = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
    }
}

 

 