//Starting Date:- 07/02/2020

var Addition = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;

var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, level = 1, label ='';


$(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(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag = true; */
	/* if(Utils.mobileDeviceFlag) 
		Utils.Path=Android.getMediaPath("Addition");  */
	setTimeout(function () {
		Addition.init();
	}, 100);
}); 

Addition.init = function()
{
    $("#coverPage").show();
    $("#homeAndLogoBtn").show();
    $("#gameOverPage").hide();
    $("#homeImage").hide();
    $("#gamePage").hide();
	document.title = Addition.hardCodeddata.NameoftheGame;
    document.body.style.backgroundImage = "url('images/skin/CoverPage.png')";
    Addition.initializeVariables();
    Addition.makeNumberPad();
    Addition.setAllImages();
    Addition.createAcknowledgementDivs();
}

Addition.initializeVariables = function()
{
    Addition.que1Flag = false;    //for checking 1st Que correct or not.
    Addition.que2Flag = false;    //for checking 2nd Que correct or not.
    Addition.attemptFlag = false; //for attempt.
    Addition.levelCnt=0;
    Addition.queNodivCnt=0;
    Addition.correctAnswer=0;
	Addition.wrongAnsTimer = null;	
	Addition.correctAnsTimer = null;	
	Addition.numPadColorTimer = null;	
	Addition.colorAnsZeroTimer = null;		
    Addition.answer='';			//variable to store ans given by user.
	Addition.answer1='';			//variable to store ans of que1 in background.
	Addition.answer2='';			//variable to store ans of que2 in background.
	Addition.clickedAnsDiv='';	
    Addition.que1NoArray =[], Addition.que2NoArray =[];
    Addition.answer1Array=[], Addition.answer2Array=[], Addition.noOfZeroArray=[];
}

Addition.setAllImages = function()
{
    document.getElementById("logoImage").src = Utils.Path+"images/skin/logo.png";
    document.getElementById("homeImage").src = Utils.Path+"images/skin/Home.png";
    document.getElementById("playImage").src = Utils.Path+"images/skin/Play.png";
    document.getElementById("nextImage").src = Utils.Path+"images/skin/Next.png";
    document.getElementById("soundImage").src = Utils.Path+"images/skin/Sound.png";
    document.getElementById("creditImage").src = Utils.Path+"images/skin/Credits.png";
    document.getElementById("playAgainImage").src = Utils.Path+"images/skin/Replay.png";	
	document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_yellow_01-April.png')";
	document.getElementById("multText").style.backgroundImage = "url('images/skin/long-gray-button.png')";	
    document.getElementById("que1").style.backgroundImage = "url('images/skin/gray-button.png')";
    document.getElementById("que2").style.backgroundImage = "url('images/skin/gray-button.png')";
    document.getElementById("ans1").style.backgroundImage = "url('images/skin/gray-button.png')";
    document.getElementById("ans2").style.backgroundImage = "url('images/skin/gray-button.png')";
	document.getElementById('scoreText').innerHTML = Addition.hardCodeddata.scoreText;
    document.getElementById('score').innerHTML = Addition.correctAnswer + Addition.hardCodeddata.totalScore;
	document.getElementById('multText').innerHTML = Addition.hardCodeddata.Additiontext;
    document.getElementById('gameOverTextDiv').innerHTML = Addition.hardCodeddata.gameovertext;
    document.getElementById('additionSign1').innerHTML = Addition.hardCodeddata.additionSign;
    document.getElementById('equalSign1').innerHTML = Addition.hardCodeddata.equalSign;
    document.getElementById('additionSign2').innerHTML = Addition.hardCodeddata.additionSign;
    document.getElementById('equalSign2').innerHTML = Addition.hardCodeddata.equalSign;
}

Addition.playGame = function()
{
    $("#coverPage").hide();
    $("#gameOverPage").hide();
    $("#homeAndLogoBtn").show();
    $("#homeImage").show();
    $("#gamePage").show();
    $("#numberPad").addClass("buttonDivCss");
    document.body.style.backgroundImage = "url('images/skin/ONLY BG.jpg')";
    console.log('Play Game');
    Addition.callSound();
	Addition.showQuestion();
}

Addition.showQuestion = function()    //show each level question.
{
    Addition.levelCnt++;
    Addition.noOfZeroArray=[];
    Addition.answer='';
    Addition.que1Flag = false;
    Addition.que2Flag = false;
    Addition.attemptFlag = false;
	clearTimeout(Addition.wrongAnsTimer);
	clearTimeout(Addition.correctAnsTimer);
	clearTimeout(Addition.colorAnsZeroTimer);
    $("#ans1").css("pointer-events", "auto");
    $("#ans2").css("pointer-events", "auto");
    $("#soundBtn").css("pointer-events", "auto");
    $("#numberPad").css("pointer-events", "auto");
    document.getElementById('ans1').innerHTML = '';
    document.getElementById('ans2').innerHTML = '';
    document.getElementById('ans1').classList.remove('blink_me');
    document.getElementById('ans2').classList.remove('blink_me');
    document.getElementById('ans1').classList.remove('flash');
    document.getElementById('ans2').classList.remove('flash');
	d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    
    for(var i=0; i<4; i++)         
        document.getElementById('num'+(i+1)).innerHTML = '';

    Addition.que1NoArray =[];
    Addition.generateNumber(Addition.que1NoArray);
    Addition.que2NoArray =[];
    Addition.generateNumber(Addition.que2NoArray);

    Addition.checkQueArray();  

    if(Addition.que1Flag == false)
        document.getElementById('ans1').classList.add('blink_me');

    Addition.calculateAns();    
}

Addition.generateNumber = function(noArray)	//Function to calculate two numbers for each Question.
{
    while(noArray.length != 2){
        var random_no = Math.floor(Math.random() * 9);
        if(random_no < 2)	//Number should not be 0 or 1.
            continue;
        else
            noArray.push(random_no);
    }
}

Addition.checkQueArray = function()
{
    var i,j, sameNoCnt=0;
    for(i=0; i<Addition.que1NoArray.length; i++)	//Loop to check whether Question nos unique or not.
    {
        for(j=0; j<Addition.que2NoArray.length; j++)
        {
            if(Addition.que1NoArray[i] == Addition.que2NoArray[j]){
                sameNoCnt++;
                break;
            } 
            else
                continue;
        }
    }
    if(sameNoCnt == 4 || sameNoCnt == 2) 
    {        
        Addition.que2NoArray =[];
        Addition.generateNumber(Addition.que2NoArray);
        Addition.checkQueArray();
    }
    else{
        switch(Addition.levelCnt){	//cases to add zeros accorting to level.
            case 1: case 2:
                Addition.nextLevel(1,1);
                break;
            /* case 2:
                Addition.nextLevel(1,1);
                break;  */   
            case 3:
                Addition.nextLevel(10,10);
                break;     
            default:
                Addition.levelCnt=0;
                Addition.gameOver();
                break;
        }       
    }
}

Addition.nextLevel = function(firstNumber,secondNumber)       //Add zeros to each number according to level.
{
    Addition.queNodivCnt=0;
    Addition.que1NoArray[0] = eval(Addition.que1NoArray[0] * firstNumber);
    Addition.que2NoArray[0] = eval(Addition.que2NoArray[0] * firstNumber);

    Addition.que1NoArray[1] = eval(Addition.que1NoArray[1] * secondNumber);
    Addition.que2NoArray[1] = eval(Addition.que2NoArray[1] * secondNumber);

    for(i=0; i<Addition.que1NoArray.length; i++)
        Addition.colorQueZeros(Addition.que1NoArray[i]); 
    for(i=0; i<Addition.que2NoArray.length; i++)
        Addition.colorQueZeros(Addition.que2NoArray[i]);
}

Addition.colorQueZeros = function(arrayElement)       //Function to Color the zeros and add couma in number.
{
    var i, queNo, spanNo, noOfZeroCnt=0, spanArray=[];
    Addition.queNodivCnt++;
    spanNo = arrayElement.toString();
    spanArray = spanNo.split('');
	
    for(i=0; i<spanArray.length; i++){
        span = document.createElement('span');
        $(span).prop("id","span"+Addition.queNodivCnt+(i+1));
        document.getElementById("num"+Addition.queNodivCnt).appendChild(span);
        queNo = document.getElementById("span"+Addition.queNodivCnt+(i+1));
        queNo.innerHTML = spanArray[i];
        if(queNo.innerHTML == 0){		//Add specific color to 0 in number.
            noOfZeroCnt++;
            queNo.style.color ='red'; 
        }  
        else    
            queNo.style.color ='black';     
    }
    Addition.noOfZeroArray.push(noOfZeroCnt);  
    index = spanArray.length - 3;		//Add couma into number.
    while(index > 0){
        spanArray[index-1] = spanArray[index-1]+",";
        index = index-2;
    }
    for(i=0; i<spanArray.length; i++){
        queNo = document.getElementById("span"+Addition.queNodivCnt+(i+1));
        queNo.innerHTML = spanArray[i];
    }    
}

Addition.calculateAns = function()    //calculate answer of both question.
{
    if(Addition.que1Flag == false)
        Addition.clickedAnsDiv = 'ans1';

    Addition.answer1 = (eval(Addition.que1NoArray[0] + Addition.que1NoArray[1])).toString();
    Addition.answer1Array = Addition.answer1.split('');

    Addition.answer2 = (eval(Addition.que2NoArray[0] + Addition.que2NoArray[1])).toString();
    Addition.answer2Array = Addition.answer2.split('');  
}

Addition.selectQuestion = function(ansDivId)  //select question to be answered. clicked on ans div.
{
	if(ansDivId == 'ans1'){
		Addition.clickedAnsDiv = 'ans1';
		document.getElementById('ans2').classList.remove('blink_me');
		document.getElementById('ans1').classList.add('blink_me'); 
	}	
	if(ansDivId == 'ans2'){
		Addition.clickedAnsDiv = 'ans2';
		document.getElementById('ans1').classList.remove('blink_me');
		document.getElementById('ans2').classList.add('blink_me'); 
	}	
}

Addition.clickedButton = function(clickedNumberId)  //Click on number pad button.
{
    var clickedBtn=''; 
    document.getElementById("playSound").pause(); 
    document.getElementById(clickedNumberId).style.color ='black'; 
    if(Addition.numPadColorTimer){
        clearTimeout(Addition.numPadColorTimer);
        Addition.numPadColorTimer = null;
    }    
    Addition.numPadColorTimer = setTimeout(function(){ 			//numPadColorTimer to change color of clicked button.
        document.getElementById(clickedNumberId).style.color ='white';  
    },150);

    if(clickedNumberId == 'button42'){       //click on Clear Button
		document.getElementById(Addition.clickedAnsDiv).innerHTML ='';
	}	
    else{                                    //click on Other Buttons.
        Addition.attemptFlag = true;
        clickedBtn = document.getElementById(clickedNumberId).innerHTML;
        document.getElementById(Addition.clickedAnsDiv).append(clickedBtn);
        Addition.answer = document.getElementById(Addition.clickedAnsDiv).innerHTML;
        
        if(Addition.clickedAnsDiv == 'ans1'){
			$("#ans2").css("pointer-events", "none");
            if(Addition.answer.length == Addition.answer1Array.length)
                Addition.checkAnswer(Addition.answer1);
        }    
        else{
			$("#ans1").css("pointer-events", "none");
            if(Addition.answer.length == Addition.answer2Array.length)
                Addition.checkAnswer(Addition.answer2);  
        }
    }    
}

Addition.checkAnswer = function(finalAnswer)		//Function to check answer.
{
	if(finalAnswer == Addition.answer)
    {
        if(finalAnswer == Addition.answer1)
            Addition.que1Flag = true;
        if(finalAnswer == Addition.answer2)
            Addition.que2Flag = true; 
		Addition.correctAnswer++;
        $("#nextBtn").css("pointer-events", "none"); 
		$("#numberPad").css("pointer-events", "none");
        document.getElementById(Addition.clickedAnsDiv).style.color = 'green';
        document.getElementById(Addition.clickedAnsDiv).classList.remove('blink_me');
		document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_green_01-April.png')";
        document.getElementById('score').innerHTML = Addition.correctAnswer + Addition.hardCodeddata.totalScore;
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Buzzercorrect 1.mp3";
        document.getElementById("playSound").play();
        if(Addition.colorAnsZeroTimer){
            clearTimeout(Addition.colorAnsZeroTimer);
            Addition.colorAnsZeroTimer = null;
        }
		Addition.colorAnsZeroTimer = setTimeout(function()	//colorAnsZeroTimer to color the ans zeros according to level after showing ans in correct.
        { 
			$("#nextBtn").css("pointer-events", "auto");
			document.getElementById(Addition.clickedAnsDiv).style.color = 'black';
            document.getElementById(Addition.clickedAnsDiv).classList.add("animated","flash");
            Addition.colorAnsZeros(); 
			Addition.answer=''; 
		}, 250);  
		if(Addition.correctAnsTimer){
			clearTimeout(Addition.correctAnsTimer);
			Addition.correctAnsTimer = null;
		}  
		Addition.correctAnsTimer = setTimeout(function()       //correctAnsTimer to show auto next Question after giving both answers correct.
		{   
			if(Addition.que1Flag == true && Addition.que2Flag == true)  //If both questions are correct then show next question.
			{
				scoredMarks = 10;
				console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
				if (Utils.mobileDeviceFlag)
					Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
				Addition.showQuestion();
			}
			$("#numberPad").css("pointer-events", "auto");
			if(Addition.que1Flag == true){
				document.getElementById('ans2').classList.add('blink_me'); 
				Addition.clickedAnsDiv = 'ans2';
			}
			else{
				document.getElementById('ans1').classList.add('blink_me'); 
				Addition.clickedAnsDiv = 'ans1';
			}
			document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_yellow_01-April.png')";
		}, 1500);      
        $("#"+Addition.clickedAnsDiv).css("pointer-events", "none");
    }
    else{		
        $("#nextBtn").css("pointer-events", "none");  	//If ans is wrong change the color of given ans to red and vanish the answer.
		$("#numberPad").css("pointer-events", "none");
        document.getElementById(Addition.clickedAnsDiv).style.color = 'red';
		document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_red_01-April.png')";
		document.getElementById("playSound").src = Utils.Path + "sounds/instructions/wrongSoundBeep.mp3";
        document.getElementById("playSound").play();
        if(Addition.wrongAnsTimer){
            clearTimeout(Addition.wrongAnsTimer);
            Addition.wrongAnsTimer = null;
        }
        Addition.wrongAnsTimer = setTimeout(function()
        {
            document.getElementById(Addition.clickedAnsDiv).innerHTML ='';
            document.getElementById(Addition.clickedAnsDiv).style.color = 'black';
			document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_yellow_01-April.png')";
            $("#nextBtn").css("pointer-events", "auto");
			$("#numberPad").css("pointer-events", "auto");
        }, 500);
        Addition.answer='';
    }   
}

Addition.colorAnsZeros = function()   //Function to color the zeros of ans according to level.
{
    var i, spanArray=[];

    noOfAnsColorZero = Addition.noOfZeroArray[0]+Addition.noOfZeroArray[1];
    spanArray = Addition.answer.split('');
    difference = spanArray.length - noOfAnsColorZero;		//eg: 500 x 40 = 20,000 (only give red color to last three zeros).
    document.getElementById(Addition.clickedAnsDiv).innerHTML='';
    for(i=0; i<spanArray.length; i++)
    {
        span = document.createElement('span');
        $(span).prop("id",Addition.clickedAnsDiv+"Span"+(i+1));
        document.getElementById(Addition.clickedAnsDiv).appendChild(span);    
        queNo = document.getElementById(Addition.clickedAnsDiv+"Span"+(i+1));
        queNo.innerHTML = spanArray[i];
    }
    for(i=spanArray.length; i>difference; i--)
    {
        queNo = document.getElementById(Addition.clickedAnsDiv+"Span"+i);
        if(queNo.innerHTML == 0)		//Change color of ans zeros according to level.
            queNo.style.color ='red';
        else    
            queNo.style.color ='black';     
    }

    index = spanArray.length - 3;   //Add couma into number.
    while(index > 0){
        spanArray[index-1] = spanArray[index-1]+",";
        index = index-2;
    }
    for(i=0; i<spanArray.length; i++)
    {
        queNo = document.getElementById(Addition.clickedAnsDiv+"Span"+(i+1));
        queNo.innerHTML = spanArray[i];
    }    
}

Addition.callSound = function()
{
    document.getElementById("playSound").src = Utils.Path + "sounds/Instructions/MultiplicationInstruction.mp3";
    document.getElementById("playSound").play();    
} 
 
Addition.gameOver = function()
{
    $("#gamePage").hide();
    $("#homeAndLogoBtn").show();
    $("#gameOverPage").show();
	clearTimeout(Addition.wrongAnsTimer);
	clearTimeout(Addition.correctAnsTimer);
	clearTimeout(Addition.colorAnsZeroTimer);
}

Addition.playAgainGame = function()
{
    $("#acknowledgementDiv").hide();
    Addition.correctAnswer=0;
    document.getElementById('score').innerHTML = Addition.correctAnswer + Addition.hardCodeddata.totalScore;
    Addition.playGame();
}

Addition.callHome = function()
{
    if (!Addition.attemptFlag) {
        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    }
    else{
        if((Addition.que1Flag == true && Addition.que2Flag == false) || (Addition.que1Flag == false && Addition.que2Flag == true))  //If 1 question is correct then scoredMarks = 5.
            scoredMarks = 5; 
        if(Addition.que1Flag == true && Addition.que2Flag == true)
            scoredMarks = 10;    
        if(Addition.que1Flag == false && Addition.que2Flag == false)
            scoredMarks = 0;
    }
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);

    location.reload();
}

Addition.callNext = function()
{
   document.getElementById("playSound").pause(); 
    if (!Addition.attemptFlag) {
		scoredMarks = -1;
    }
    else{
        if((Addition.que1Flag == true && Addition.que2Flag == false) || (Addition.que1Flag == false && Addition.que2Flag == true))  //If 1 question is correct then scoredMarks = 5.
            scoredMarks = 5; 
        if(Addition.que1Flag == true && Addition.que2Flag == true)
            scoredMarks = 10;    
        if(Addition.que1Flag == false && Addition.que2Flag == false)
            scoredMarks = 0;
    }
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);

    Addition.showQuestion();
}

Addition.createAcknowledgementDivs = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(Addition.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(Addition.AcknowledgementPageData)[i] + " : " + Object.values(Addition.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 = Addition.hardCodeddata['createdOn'];
    div.style.marginBottom = "2vh";
    acknowledgementDiv.appendChild(div);
}

Addition.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();

}