//Starting Date:- 07/02/2020

var Multiplication = {};
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("Multiplication");  */
	setTimeout(function () {
		Multiplication.init();
	}, 100);
}); 

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

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

Multiplication.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 = Multiplication.hardCodeddata.scoreText;
    document.getElementById('score').innerHTML = Multiplication.correctAnswer + Multiplication.hardCodeddata.totalScore;
	document.getElementById('multText').innerHTML = Multiplication.hardCodeddata.multiplicationtext;
    document.getElementById('gameOverTextDiv').innerHTML = Multiplication.hardCodeddata.gameovertext;
    document.getElementById('multiplySign1').innerHTML = Multiplication.hardCodeddata.multiplySign;
    document.getElementById('equalSign1').innerHTML = Multiplication.hardCodeddata.equalSign;
    document.getElementById('multiplySign2').innerHTML = Multiplication.hardCodeddata.multiplySign;
    document.getElementById('equalSign2').innerHTML = Multiplication.hardCodeddata.equalSign;
}

Multiplication.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');
    Multiplication.callSound();
	Multiplication.showQuestion();
}

Multiplication.showQuestion = function()    //show each level question.
{
    Multiplication.levelCnt++;
    Multiplication.noOfZeroArray=[];
    Multiplication.answer='';
    Multiplication.que1Flag = false;
    Multiplication.que2Flag = false;
    Multiplication.attemptFlag = false;
	clearTimeout(Multiplication.wrongAnsTimer);
	clearTimeout(Multiplication.correctAnsTimer);
	clearTimeout(Multiplication.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 = '';

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

    Multiplication.checkQueArray();  

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

    Multiplication.calculateAns();    
}

Multiplication.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);
    }
}

Multiplication.checkQueArray = function()
{
    var i,j, sameNoCnt=0;
    for(i=0; i<Multiplication.que1NoArray.length; i++)	//Loop to check whether Question nos unique or not.
    {
        for(j=0; j<Multiplication.que2NoArray.length; j++)
        {
            if(Multiplication.que1NoArray[i] == Multiplication.que2NoArray[j]){
                sameNoCnt++;
                break;
            } 
            else
                continue;
        }
    }
    if(sameNoCnt == 4 || sameNoCnt == 2) 
    {        
        Multiplication.que2NoArray =[];
        Multiplication.generateNumber(Multiplication.que2NoArray);
        Multiplication.checkQueArray();
    }
    else{
        switch(Multiplication.levelCnt){	//cases to add zeros accorting to level.
            case 1:
                Multiplication.nextLevel(1,1);
                break;
            case 2:
                Multiplication.nextLevel(10,1);
                break;    
            case 3:
                Multiplication.nextLevel(100,1);
                break;    
            case 4:
                Multiplication.nextLevel(10,10);
                break;    
            case 5:
                Multiplication.nextLevel(100,10);
                break; 
            case 6:
                $('.queDivCss').css('font-size', '3vw');
                $('.ansDivCss').css('font-size', '3vw');
                Multiplication.nextLevel(1000,100);
                break;     
            default:
                Multiplication.levelCnt=0;
                Multiplication.gameOver();
                break;
        }       
    }
}

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

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

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

Multiplication.colorQueZeros = function(arrayElement)       //Function to Color the zeros and add couma in number.
{
    var i, queNo, spanNo, noOfZeroCnt=0, spanArray=[];
    Multiplication.queNodivCnt++;
    spanNo = arrayElement.toString();
    spanArray = spanNo.split('');
	
    for(i=0; i<spanArray.length; i++){
        span = document.createElement('span');
        $(span).prop("id","span"+Multiplication.queNodivCnt+(i+1));
        document.getElementById("num"+Multiplication.queNodivCnt).appendChild(span);
        queNo = document.getElementById("span"+Multiplication.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';     
    }
    Multiplication.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"+Multiplication.queNodivCnt+(i+1));
        queNo.innerHTML = spanArray[i];
    }    
}

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

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

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

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

Multiplication.clickedButton = function(clickedNumberId)  //Click on number pad button.
{
    var clickedBtn=''; 
    document.getElementById("playSound").pause(); 
    document.getElementById(clickedNumberId).style.color ='black'; 
    if(Multiplication.numPadColorTimer){
        clearTimeout(Multiplication.numPadColorTimer);
        Multiplication.numPadColorTimer = null;
    }    
    Multiplication.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(Multiplication.clickedAnsDiv).innerHTML ='';
	}	
    else{                                    //click on Other Buttons.
        Multiplication.attemptFlag = true;
        clickedBtn = document.getElementById(clickedNumberId).innerHTML;
        document.getElementById(Multiplication.clickedAnsDiv).append(clickedBtn);
        Multiplication.answer = document.getElementById(Multiplication.clickedAnsDiv).innerHTML;
        
        if(Multiplication.clickedAnsDiv == 'ans1'){
			$("#ans2").css("pointer-events", "none");
            if(Multiplication.answer.length == Multiplication.answer1Array.length)
                Multiplication.checkAnswer(Multiplication.answer1);
        }    
        else{
			$("#ans1").css("pointer-events", "none");
            if(Multiplication.answer.length == Multiplication.answer2Array.length)
                Multiplication.checkAnswer(Multiplication.answer2);  
        }
    }    
}

Multiplication.checkAnswer = function(finalAnswer)		//Function to check answer.
{
	if(finalAnswer == Multiplication.answer)
    {
        if(finalAnswer == Multiplication.answer1)
            Multiplication.que1Flag = true;
        if(finalAnswer == Multiplication.answer2)
            Multiplication.que2Flag = true; 
		Multiplication.correctAnswer++;
        $("#nextBtn").css("pointer-events", "none"); 
		$("#numberPad").css("pointer-events", "none");
        document.getElementById(Multiplication.clickedAnsDiv).style.color = 'green';
        document.getElementById(Multiplication.clickedAnsDiv).classList.remove('blink_me');
		document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_green_01-April.png')";
        document.getElementById('score').innerHTML = Multiplication.correctAnswer + Multiplication.hardCodeddata.totalScore;
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Buzzercorrect 1.mp3";
        document.getElementById("playSound").play();
        if(Multiplication.colorAnsZeroTimer){
            clearTimeout(Multiplication.colorAnsZeroTimer);
            Multiplication.colorAnsZeroTimer = null;
        }
		Multiplication.colorAnsZeroTimer = setTimeout(function()	//colorAnsZeroTimer to color the ans zeros according to level after showing ans in correct.
        { 
			$("#nextBtn").css("pointer-events", "auto");
			document.getElementById(Multiplication.clickedAnsDiv).style.color = 'black';
            document.getElementById(Multiplication.clickedAnsDiv).classList.add("animated","flash");
            Multiplication.colorAnsZeros(); 
			Multiplication.answer=''; 
		}, 250);  
		if(Multiplication.correctAnsTimer){
			clearTimeout(Multiplication.correctAnsTimer);
			Multiplication.correctAnsTimer = null;
		}  
		Multiplication.correctAnsTimer = setTimeout(function()       //correctAnsTimer to show auto next Question after giving both answers correct.
		{   
			if(Multiplication.que1Flag == true && Multiplication.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);
				Multiplication.showQuestion();
			}
			$("#numberPad").css("pointer-events", "auto");
			if(Multiplication.que1Flag == true){
				document.getElementById('ans2').classList.add('blink_me'); 
				Multiplication.clickedAnsDiv = 'ans2';
			}
			else{
				document.getElementById('ans1').classList.add('blink_me'); 
				Multiplication.clickedAnsDiv = 'ans1';
			}
			document.getElementById("gamePage").style.backgroundImage = "url('images/skin/gadget_yellow_01-April.png')";
		}, 1500);      
        $("#"+Multiplication.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(Multiplication.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(Multiplication.wrongAnsTimer){
            clearTimeout(Multiplication.wrongAnsTimer);
            Multiplication.wrongAnsTimer = null;
        }
        Multiplication.wrongAnsTimer = setTimeout(function()
        {
            document.getElementById(Multiplication.clickedAnsDiv).innerHTML ='';
            document.getElementById(Multiplication.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);
        Multiplication.answer='';
    }   
}

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

    noOfAnsColorZero = Multiplication.noOfZeroArray[0]+Multiplication.noOfZeroArray[1];
    spanArray = Multiplication.answer.split('');
    difference = spanArray.length - noOfAnsColorZero;		//eg: 500 x 40 = 20,000 (only give red color to last three zeros).
    document.getElementById(Multiplication.clickedAnsDiv).innerHTML='';
    for(i=0; i<spanArray.length; i++)
    {
        span = document.createElement('span');
        $(span).prop("id",Multiplication.clickedAnsDiv+"Span"+(i+1));
        document.getElementById(Multiplication.clickedAnsDiv).appendChild(span);    
        queNo = document.getElementById(Multiplication.clickedAnsDiv+"Span"+(i+1));
        queNo.innerHTML = spanArray[i];
    }
    for(i=spanArray.length; i>difference; i--)
    {
        queNo = document.getElementById(Multiplication.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(Multiplication.clickedAnsDiv+"Span"+(i+1));
        queNo.innerHTML = spanArray[i];
    }    
}

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

Multiplication.playAgainGame = function()
{
    $("#acknowledgementDiv").hide();
    Multiplication.correctAnswer=0;
    $('.queDivCss').css('font-size', '3.5vw');
    $('.ansDivCss').css('font-size', '3.5vw');
    document.getElementById('score').innerHTML = Multiplication.correctAnswer + Multiplication.hardCodeddata.totalScore;
    Multiplication.playGame();
}

Multiplication.callHome = function()
{
    if (!Multiplication.attemptFlag) {
        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    }
    else{
        if((Multiplication.que1Flag == true && Multiplication.que2Flag == false) || (Multiplication.que1Flag == false && Multiplication.que2Flag == true))  //If 1 question is correct then scoredMarks = 5.
            scoredMarks = 5; 
        if(Multiplication.que1Flag == true && Multiplication.que2Flag == true)
            scoredMarks = 10;    
        if(Multiplication.que1Flag == false && Multiplication.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();
}

Multiplication.callNext = function()
{
   document.getElementById("playSound").pause(); 
    if (!Multiplication.attemptFlag) {
		scoredMarks = -1;
    }
    else{
        if((Multiplication.que1Flag == true && Multiplication.que2Flag == false) || (Multiplication.que1Flag == false && Multiplication.que2Flag == true))  //If 1 question is correct then scoredMarks = 5.
            scoredMarks = 5; 
        if(Multiplication.que1Flag == true && Multiplication.que2Flag == true)
            scoredMarks = 10;    
        if(Multiplication.que1Flag == false && Multiplication.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);

    Multiplication.showQuestion();
}

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

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

}