var Abacus = {},
    Utils = {};
Utils.mobileDeviceFlag = false;
var audioCounter = 0,
    NumberBanaoOrNumberPhechanoArray = [1, 2],
    Language, startTime;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    label = 0,
    resId = 0,
    scoreFlag = false; //operation : 1=Number Banao ,2 =number phechano

var scoreFlag = false;
Abacus.queCnt = 0; //que counter for display 5 qns;
Abacus.reloadflag = false;
var max = 0,
    min = 0,
    ballsDisplayStyle = 0;
var ansScoreCnt = 0;
var soundCnt = 0;
var colorFlag = false;
Abacus.queTypeArray = [1, 2, 3];
Abacus.queArray = []; //5 que array [ [1],[2],[3],[4],[5] ]	
//Abacus.levelArray=[1,2,3];
Abacus.levelArray = [1];
Abacus.level = 0;
var min = 0,
    max = 0;
Abacus.allQueAudioArray = [];
Abacus.singleQueArray = [];
Abacus.seconds = 0;
Abacus.total_No_of_Questions = 5;
Abacus.correctCounter = 0;

$(document).ready(function() {
    // check whether it is Tablet or Desktop
    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("JaanoNumber");
     }
     else */
    Utils.Path = '';
    $(".se-pre-con").fadeOut("slow");
    setTimeout(function() {
        Language = "Marathi";
        console.log(Language);
        document.title = Abacus.name;
        //setFontFamilyForLang(langWiseJSON[Language].LabelsAndTags.font);
        Abacus.setImagesAndLabels();
        Abacus.registerEventListener();
        Abacus.attachBallsToRespectivePlaces();
    }, 10);
});

// set font family to body for selected lang. if required.
setFontFamilyForLang = function(fontFilePath) {
    var newStyle = "<style>" +
        "@font-face {  " +
        "font-family: 'CustomFontFamily';" +
        "src: url('" + fontFilePath + "') format('truetype');" +
        "}  </style>";
    $("head").append(newStyle);
    $("body").css("font-family", "CustomFontFamily");
}

//Select JSON data for lang. & set all images
Abacus.setImagesAndLabels = function() {
    audioTag = new Audio();
    Abacus.IterationCounter = 0;
    Abacus.labelsAndTextJSON = langWiseJSON[Language].LabelsAndTags;
    Abacus.numberTextJSON = langWiseJSON[Language].numberTextJSON;
    Abacus.numberSoundsJSON = langWiseJSON[Language].numberSoundsJSON;
    Abacus.CommonSoundsJSON = langWiseJSON[Language].CommonSoundsJSON;
    //$(".homeIcon").hide();
    $('#levelPage,#gamePage').hide();
    $("#AbacusGameMainDiv").css("background-image", "url('" + Utils.Path + "img/BodyBG.jpg')");
    $(".coverPageImage").prop("src", Utils.Path + Abacus.labelsAndTextJSON["coverPage"]);
    $("#levelOneImage").prop("src", Utils.Path + "img/10_99.png");
    $("#levelTwoImage").prop("src", Utils.Path + "img/100_999.png");
    $("#levelThreeImage").prop("src", Utils.Path + "img/1000_9999.png");
    // $("#levelFourImage").prop("src", Utils.Path + "img/10000_99999.png");
    $("#ballFor1").prop("src", Utils.Path + "img/ballFor1.png");
    $("#ballFor10").prop("src", Utils.Path + "img/ballFor10.png");
    $("#ballFor100").prop("src", Utils.Path + "img/ballFor100.png");
    $("#ballFor1000").prop("src", Utils.Path + "img/ballFor1000.png");
    $("#creditbtn").prop("src", Utils.Path + "img/next.png");
    $(".homeIcon").prop("src", Utils.Path + "img/home.png");
    $(".playIcon").prop("src", Utils.Path + "img/play.png");
    $(".prathamlogo").prop("src", Utils.Path + "img/prathamlogo.png");
    $(".SpeakerIcon").prop("src", Utils.Path + "img/speaker.png");
    $(".ClearIcon").prop("src", Utils.Path + "img/clear.png");
    $(".SubmitIcon").prop("src", Utils.Path + "img/submit.png");
    $(".NextIcon").prop("src", Utils.Path + "img/skip.png");
    $("#replatbtn").prop("src", Utils.Path + "img/clear.png");
    $("#TextOfhazar").html(Abacus.labelsAndTextJSON["thousand"]);
    $("#TextOfSou").html(Abacus.labelsAndTextJSON["hundred"]);
    $("#paryay").html(Abacus.labelsAndTextJSON["Option"]);
    $(".placeHeaderOf1").html(Abacus.labelsAndTextJSON["placeHeaderOf1"]);
    $(".placeHeaderOf10").html(Abacus.labelsAndTextJSON["placeHeaderOf10"]);
    $(".placeHeaderOf100").html(Abacus.labelsAndTextJSON["placeHeaderOf100"]);
    $(".placeHeaderOf1000").html(Abacus.labelsAndTextJSON["placeHeaderOf1000"]);
    // $(".placeHeaderOf10000").html(Abacus.labelsAndTextJSON["placeHeaderOf10000"]);
    $("#coverPage").show();
    for (var i = 0; i < 2; i++) {
        var randNo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
        Abacus.queTypeArray.push(randNo);
    }
}

// register all on click event listener
Abacus.registerEventListener = function() {
    $("#levelOneImage").on("click", function() { Abacus.level = 1;
        min = 10;
        max = 99;
        Abacus.startgameForRange(min, max); });
    $("#levelTwoImage").on("click", function() { Abacus.level = 2;
        min = 100;
        max = 999;
        Abacus.startgameForRange(min, max); });
    $("#levelThreeImage").on("click", function() { Abacus.level = 3;
        min = 1000;
        max = 9999;
        Abacus.startgameForRange(min, max); });
    // $("#levelFourImage").on("click", function () { Abacus.level = 4; Abacus.startgameForRange(); });
    $("#playAgainDiv").on("click", function() { Abacus.level = 4;
        Abacus.startgameForRange(min, max); });
    /* on click ball hover*/
    $(".ballInAbacusPad").on("click", function() {
        Abacus.onClickBallHover(this.id);

    });

    $(".SpeakerIcon").on("click", function() {
        document.getElementById("audio").pause();
        clearInterval(Abacus.noResponseTimer);
        clearTimeout(Abacus.timeOut);
        Abacus.seconds = 0;
        Abacus.startTimer();
        $(".SpeakerIcon").addClass("animated pulse");
        setTimeout(function() { $(".SpeakerIcon").removeClass("animated pulse"); }, 700);
        Abacus.repeatQuestionSound();
    });
    $(".homeIcon").on("click", function() {
        Abacus.relodePage();
    });
    $(".ClearIcon").on("click", function() {
        document.getElementById("audio").pause();
        clearInterval(Abacus.noResponseTimer);
        clearTimeout(Abacus.timeOut);
        Abacus.seconds = 0;
        Abacus.startTimer();
        $(".ClearIcon").addClass("animated pulse");
        setTimeout(function() { $(".ClearIcon").removeClass("animated pulse"); }, 700);
        Abacus.clearAbacusPad();
    });
    $(".SubmitIcon").on("click", function() {
        document.getElementById("audio").pause();
        clearInterval(Abacus.noResponseTimer);
        clearTimeout(Abacus.timeOut);
        Abacus.seconds = 0;
        Abacus.startTimer();
        $(".SubmitIcon").addClass("animated pulse");
        setTimeout(function() { $(".SubmitIcon").removeClass("animated pulse"); }, 700);
        Abacus.checkAnswer();
    });
    $(".NextIcon").on("click", function() {
        document.getElementById("audio").pause();
        clearInterval(Abacus.noResponseTimer);
        clearTimeout(Abacus.timeOut);
        Abacus.seconds = 0;
        Abacus.startTimer();
        Abacus.nextQue();
        $(".NextIcon").addClass("animated pulse");
        setTimeout(function() { $(".NextIcon").removeClass("animated pulse"); }, 700);
    });

    // $(".playIcon").on("click",Abacus.showLevelPage);
}
Abacus.playGame = function() {
    $('#gamePage').show();
    $("#coverPage").hide();
    var rno = Math.floor(Math.random() * Abacus.levelArray.length);
    Abacus.level = Abacus.levelArray[rno];
    if (Abacus.level == 1)
        min = 10, max = 99;
    else if (Abacus.level == 2)
        min = 100, max = 999;
    else if (Abacus.level == 3)
        min = 1000, max = 9999;
    else
        min = 10000, max = 99999;
    Abacus.startgameForRange(min, max);
}

// attach 9 balls in each column And hide them at start.
Abacus.attachBallsToRespectivePlaces = function() {
        for (var i = 1; i < 5; i++) {
            template = '', maxRowInColumn = 5;
            for (var row = 1, ballNo = 1; row <= maxRowInColumn; row++, ballNo++) {
                template += '<div class="BeadsImages " style="margin-top:2px;">' +
                    '<img id="' + (i) + "" + (ballNo) + '" class="ballInAbacusPad ballNo' + (ballNo) + '" src="" onclick="Abacus.onClickBallHover(this.id)">' +
                    '<img id="' + (i) + "" + (ballNo + 5) + '" class="ballInAbacusPad ballNo' + (ballNo + 5) + '" src="" onclick="Abacus.onClickBallHover(this.id)">' +
                    '</div>';
            }
            $('#column' + i).append(template);
        }
        $('.ballInAbacusPad').css('visibility', 'hidden');
        //  $('#column0 >.BeadsImages >.ballInAbacusPad').prop("src", Utils.Path + "img/ballFor10000.png").attr("data", "column0");
        $('#column1 >.BeadsImages >.ballInAbacusPad').prop("src", Utils.Path + "img/ballFor1000.png").attr("data", "column1");
        $('#column2 >.BeadsImages >.ballInAbacusPad').prop("src", Utils.Path + "img/ballFor100.png").attr("data", "column2");
        $('#column3 >.BeadsImages >.ballInAbacusPad').prop("src", Utils.Path + "img/ballFor10.png").attr("data", "column3");
        $('#column4 >.BeadsImages >.ballInAbacusPad').prop("src", Utils.Path + "img/ballFor1.png").attr("data", "column4");
    }
    //set range to select random number as click on level 
Abacus.startgameForRange = function(MinimumNumber, MaximumNumber) {
    //Abacus.queCnt=0;
    document.getElementById("finalPage").style.display = "none";
    document.getElementById("gamePage").style.display = "block";
    somethingDone = false;
    $('#gamePage').show();
    $('#levelPage').hide();
    Abacus.MinimumNumberOfLevel = MinimumNumber;
    Abacus.MaximumNumberOfLevel = MaximumNumber;
    Abacus.applyDragAndDropToBalls();
    Abacus.ChooseRandomNumberToPlay();

}

// apply drag option to balls for game "Number Banao"  &  make each colum droppable   
Abacus.applyDragAndDropToBalls = function() {
    $('.ballInPickerBox,.ballInAbacusPad').draggable({
        zIndex: 100,
        revert: function() {
            $(".hover").removeClass("hover");
        },
        containment: '#gamePage',
        helper: "clone",
        start: function(event, ui) {
            clearInterval(Abacus.noResponseTimer);
            clearTimeout(Abacus.nextQueTimer);
            document.getElementById("audio").pause();
            audioTag.pause();
        }
    });
    /*  $('#column0').droppable({
       over:animate,

     //  accept: '#ballFor10000',
       drop: function (event, ui) { Abacus.appendBallInAbacusPad(ui); }
     }); */
    $('#column1').droppable({
        over: animate,
        //  accept: '#ballFor1000',
        drop: function(event, ui) { Abacus.appendBallInAbacusPad(ui); }
    });
    $('#column2').droppable({
        over: animate,
        //  accept: '#ballFor100',
        drop: function(event, ui) { Abacus.appendBallInAbacusPad(ui); }
    });
    $('#column3').droppable({
        over: animate,
        //  accept: '#ballFor10',
        drop: function(event, ui) { Abacus.appendBallInAbacusPad(ui); }
    });
    $('#column4').droppable({
        over: animate,
        // accept: '#ballFor1',
        drop: function(event, ui) { Abacus.appendBallInAbacusPad(ui); }
    });
    $('#ballPickerBox').droppable({
        accept: '.ballInAbacusPad',
        drop: function(event, ui) { Abacus.removeBallFromAbacusPad(ui); }
    });
}

function animate(event, ui) {
    if (Abacus.queTypeArray[Abacus.queCnt] == 1) {
        $(".hover").removeClass("hover");
        $(this).addClass("hover");
    }
}
// append dragged ball in respective column
Abacus.appendBallInAbacusPad = function(ui) {
    $(".hover").removeClass("hover");
    somethingDone = true;
    var columnNo = ui.draggable.attr("data");
    if (Abacus.queTypeArray[Abacus.queCnt] == 1) {
        var ballsExistsInTheColumn = Number($('#' + columnNo + '>.NoOfBallsInColumn').html());
        if (ballsExistsInTheColumn < 9) {
            $("#" + columnNo + '>.BeadsImages > .ballNo' + (ballsExistsInTheColumn + 1)).css("visibility", "visible");
            $('#' + columnNo + '>.NoOfBallsInColumn').html(ballsExistsInTheColumn + 1);
        }
    }
}

//remove ball from column (back dragging)
Abacus.removeBallFromAbacusPad = function(ui) {
    $(".hover").removeClass("hover");
    somethingDone = true;
    var columnNo = ui.draggable.attr("data");
    var ballsExistsInTheColumn = Number($('#' + columnNo + '>.NoOfBallsInColumn').html());
    $("#" + columnNo + '>.BeadsImages > .ballNo' + ballsExistsInTheColumn).css("visibility", "hidden");
    $('#' + columnNo + '>.NoOfBallsInColumn').html(ballsExistsInTheColumn - 1);
}

Abacus.ChooseRandomNumberToPlay = function() {
    soundCnt = 0;
    for (var i = 0; i < 5; i++, soundCnt++) {
        Abacus.audioArrayOfWholeNumber = [];
        Abacus.singleQueArray = [];
        audioCounter = 0;
        Abacus.OnesPlace = 0;
        Abacus.TensPlace = 0;
        Abacus.HundredsPlace = 0;
        Abacus.ThousandsPlace = 0, Abacus.NumberOfTensAndOnesPlace = 0;

        $('.NoOfBallsInColumn').html("0");
        if (Abacus.MaximumNumberOfLevel == 99) {
            //syntax : Math.floor(Math.random() * (max - min + 1)) + min
            Abacus.OnesPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; // in range(1,6)
            Abacus.singleQueArray.push(Abacus.OnesPlace);
            Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; // in range(1,6)
            Abacus.singleQueArray.push(Abacus.TensPlace);
        } else if (Abacus.MaximumNumberOfLevel == 999) {
            //syntax : Math.floor(Math.random() * (max - min + 1)) + min
            Abacus.OnesPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.OnesPlace);
            Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.TensPlace = 0 : Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1;
            Abacus.singleQueArray.push(Abacus.TensPlace);
            Abacus.HundredsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(1,6)
            Abacus.singleQueArray.push(Abacus.HundredsPlace);
        } else if (Abacus.MaximumNumberOfLevel == 9999) {
            //syntax : Math.floor(Math.random() * (max - min + 1)) + min
            Abacus.OnesPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.OnesPlace);
            Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.TensPlace = 0 : Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.TensPlace);
            Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.HundredsPlace = 0 : Abacus.HundredsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.HundredsPlace);
            Abacus.ThousandsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; // in range(1,6)
            Abacus.singleQueArray.push(Abacus.ThousandsPlace);
        } else {
            //syntax : Math.floor(Math.random() * (max - min + 1)) + min
            Abacus.OnesPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.OnesPlace);
            Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.TensPlace = 0 : Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.TensPlace);
            Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.HundredsPlace = 0 : Abacus.HundredsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
            Abacus.singleQueArray.push(Abacus.HundredsPlace);
            Abacus.ThousandsPlace = Math.floor(Math.random() * (60 - 10 + 1)) + 10; // in range(1,60)

            Abacus.TenThousandsPlace = Math.floor(Abacus.ThousandsPlace / 10);
            Abacus.newThousandsPlace = Abacus.ThousandsPlace % 10;
            Abacus.singleQueArray.push(Abacus.TenThousandsPlace);
            Abacus.singleQueArray.push(Abacus.newThousandsPlace);
        }

        Abacus.AskedNumber = (Abacus.ThousandsPlace * 1000) + (Abacus.HundredsPlace * 100) + (Abacus.TensPlace * 10 + Abacus.OnesPlace);
        console.log(Abacus.AskedNumber);
        //select random operation for "No. Banao" or "No. pehachano"
        Abacus.operation = NumberBanaoOrNumberPhechanoArray[Math.floor(Math.random() * NumberBanaoOrNumberPhechanoArray.length)];

        // $("#TextOfThousandsPlace,#TextOfHundredsPlace,#TextOfTensAndOnesPlace,#TextOfhazar,#TextOfSou").attr("data", "0").hide();
        Abacus.queArray[i] = Abacus.singleQueArray;
        //make complete Audio array of whole number & set respective text from JSON Data
        if (Abacus.level == 3) {
            if (Abacus.queArray[i][3] != 0) {
                Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON[Abacus.queArray[i][3]]);
                Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.sauHajarSoundsJSON[2]);
                /*  Abacus.operation == 1 ? $("#TextOfThousandsPlace").html(Abacus.numberTextJSON[Abacus.queArray[i][3]]) : $("#TextOfThousandsPlace").html("");
                 $("#TextOfThousandsPlace ,#TextOfhazar").show(); */
            }
        }
        Abacus.showQueText();
        // Abacus.NumberOfTensAndOnesPlace = (Abacus.queArray[Abacus.queCnt][1] * 10 + Abacus.queArray[Abacus.queCnt][0]);
        console.log(Abacus.audioArrayOfWholeNumber);
        Abacus.allQueAudioArray[i] = Abacus.audioArrayOfWholeNumber;
    }
    Abacus.showQue();
}

Abacus.showQueText = function() {
    if (Abacus.level != 1) {
        if (Abacus.queArray[soundCnt][2] != 0) {
            Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON[Abacus.queArray[soundCnt][2]]);
            Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.sauHajarSoundsJSON[1]);
            /*  Abacus.operation == 1 ? $("#TextOfHundredsPlace").html(Abacus.numberTextJSON[Abacus.queArray[soundCnt][2]]) : $("#TextOfHundredsPlace").html("");
             $("#TextOfHundredsPlace ,#TextOfSou").show(); */
        }
    }
    if (Abacus.queArray[soundCnt][1] != 0) {
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON["" + Abacus.queArray[soundCnt][1] + Abacus.queArray[soundCnt][0]]);
        /*  Abacus.operation == 1 ? $("#TextOfTensAndOnesPlace").html(Abacus.numberTextJSON[Abacus.queArray[soundCnt][1] + "" + Abacus.queArray[soundCnt][0]]) : $("#TextOfTensAndOnesPlace").html("");
         $("#TextOfTensAndOnesPlace").show(); */
    } else if (Abacus.queArray[soundCnt][0] != 0) {
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON[Abacus.queArray[soundCnt][0]]);
        /*  Abacus.operation == 1 ? $("#TextOfTensAndOnesPlace").html(Abacus.numberTextJSON[Abacus.queArray[soundCnt][0]]) : $("#TextOfTensAndOnesPlace").html("");
         $("#TextOfTensAndOnesPlace").show(); */
    }
}

//choose a random number to play within range of level (Maximum number,minimum nu.)
Abacus.showQue = function() {
    scoreFlag = false;
    Abacus.showQueTextFun();
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    label = (Abacus.queArray[Abacus.queCnt][3] * 1000) + (Abacus.queArray[Abacus.queCnt][2] * 100) + (Abacus.queArray[Abacus.queCnt][1] * 10 + Abacus.queArray[Abacus.queCnt][0]);
    console.log(label);

    Abacus.NumberOfTensAndOnesPlace = (Abacus.queArray[Abacus.queCnt][1] * 10 + Abacus.queArray[Abacus.queCnt][0]);
    $(".hoverBall").removeClass("hoverBall");
    ansScoreCnt = 0;
    Abacus.reloadflag = true;

    //start game for selected operation
    if (Abacus.queTypeArray[Abacus.queCnt] == 1)
        Abacus.startGameForType_NumberBanao();
    else
        Abacus.startGameForType_NumberPehchano();
}

//ask selected random number for "Number Banao"
Abacus.startGameForType_NumberBanao = function() {
    Abacus.clearAbacusPad();
    $("#AskedQues").html(Abacus.labelsAndTextJSON["NumberBanao"]);
    audioTag.pause();
    clearTimeout(Abacus.nextQueTimer);
    audioTag.src = Utils.Path + "sounds/ting.mp3";
    audioTag.play();
    audioTag.onended = function() {
        audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["numberBanao"];
        audioTag.play();
        audioTag.onended = function() {
            audioTag.pause();
            audioCounter = 0;
            Abacus.playAudioList(Abacus.allQueAudioArray[Abacus.queCnt], "");
        }
    }
    $("#abacusPad").css("text-align", "center");
    $("#abacusPad > .ballFor1,#abacusPad > .ballFor10,#abacusPad > .ballFor100,#abacusPad > .ballFor1000,#abacusPad > .ballFor10000").remove();
    $("#column0,#column1,#column2,#column3,#column4").show();
    $('.ballInAbacusPad').css('visibility', 'hidden');
    $(".NoOfBallsInColumn").css("visibility", "visible");
    $("#AnsOption").hide();
    $("#ballPickerBox").show();
    $("#TextOfThousandsPlace,#TextOfHundredsPlace,#TextOfTensAndOnesPlace").css({ "color": "black", "border-bottom": "none" });
}

//ask selected random number for "Number Pehchano"
Abacus.startGameForType_NumberPehchano = function() {
    Abacus.startTimer();
    $("#AskedQues").html(Abacus.labelsAndTextJSON["NumberPechano"]);
    audioTag.pause();
    clearTimeout(Abacus.nextQueTimer);
    audioTag.src = Utils.Path + "sounds/ting.mp3";
    audioTag.play();
    audioTag.onended = function() {
        audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["numberPehachano"];
        audioTag.play();
        audioTag.onended = function() {
            audioTag.pause();
        }
    }
    $(".NoOfBallsInColumn").css("visibility", "hidden");
    $("#ballPickerBox").hide();
    $("#AnsOption").show();
    $("#TextOfThousandsPlace,#TextOfHundredsPlace,#TextOfTensAndOnesPlace").css({ "color": "transperent", "border-bottom": "2px solid black" });

    // Display STyle = 1-balls under respective column...2-balls at random places
    $("#abacusPad > .ballFor1,#abacusPad > .ballFor10,#abacusPad > .ballFor100,#abacusPad > .ballFor1000,#abacusPad > .ballFor10000").remove();
    var ballsDisplayStyle = Math.floor(Math.random() * (2 - 1 + 1)) + 1; // in range(1,2)
    // STyle = 1-balls under respective column
    if (Abacus.queTypeArray[Abacus.queCnt] == 2) {
        $("#abacusPad").css("text-align", "center");
        $("#column1,#column2,#column3,#column4").show();
        $('.ballInAbacusPad').css('visibility', 'hidden');
        // Abacus.DisplayBeadsForNumberPhechano("column0", Abacus.TenThousandsPlace);
        Abacus.DisplayBeadsForNumberPhechano("column1", Abacus.queArray[Abacus.queCnt][3]);
        Abacus.DisplayBeadsForNumberPhechano("column2", Abacus.queArray[Abacus.queCnt][2]);
        Abacus.DisplayBeadsForNumberPhechano("column3", Abacus.queArray[Abacus.queCnt][1]);
        Abacus.DisplayBeadsForNumberPhechano("column4", Abacus.queArray[Abacus.queCnt][0]);
    }
    // style =2 = balls at random places
    else {
        $("#abacusPad").css("text-align", "left");
        $("#column1,#column2,#column3,#column4").hide();
        // Abacus.appendBallsImagesOfRandomnumber("ballFor10000", Abacus.TenThousandsPlace);
        Abacus.appendBallsImagesOfRandomnumber("ballFor1000", Abacus.queArray[Abacus.queCnt][3]);
        Abacus.appendBallsImagesOfRandomnumber("ballFor100", Abacus.queArray[Abacus.queCnt][2]);
        Abacus.appendBallsImagesOfRandomnumber("ballFor10", Abacus.queArray[Abacus.queCnt][1]);
        Abacus.appendBallsImagesOfRandomnumber("ballFor1", Abacus.queArray[Abacus.queCnt][0]);
        Abacus.PlaceBallsInRandomPlaces();
    }
    Abacus.CreateHTMlTemplateForAnsOptionsAndAppend();
    Abacus.applyDragAndDropToAnsOptions();
}

//For number pehechano ,,display style 2 (balls places at random)
Abacus.appendBallsImagesOfRandomnumber = function(imageName, NoOfImages) {
    var template = '';
    for (var i = 1; i <= NoOfImages; i++) {
        template += '<img id="' + imageName + "" + (i) + '" class="ballInBallsBox ' + imageName + '" src="' + Utils.Path + 'img/' + imageName + '.png" onclick="Abacus.onClickBallHover(this.id)">';
    }
    $("#abacusPad").append(template);
}

//For number pehchano ..Display style 2 -- place all balls in box at random places
Abacus.PlaceBallsInRandomPlaces = function() {
    var containerW = $("#abacusPad").width();
    var containerH = $("#abacusPad").height();
    var positions = [];
    $('.ballInBallsBox').each(function() {
        var coords = {
            w: $(this).outerWidth(true),
            h: $(this).outerHeight(true)
        };
        var success = false;
        while (!success) {
            coords.x = parseInt(Math.random() * (containerW - coords.w));
            coords.y = parseInt(Math.random() * (containerH - coords.h));
            var success = true;
            $.each(positions, function() {
                if (
                    coords.x <= (this.x + this.w) &&
                    (coords.x + coords.w) >= this.x &&
                    coords.y <= (this.y + this.h) &&
                    (coords.y + coords.h) >= this.y) {
                    success = false;
                }
            });
        }
        positions.push(coords);
        $(this).animate({
            top: coords.y - 10 + 'px',
            left: coords.x - 10 + 'px'
        }, 500);
    });
}

//For number pehechano ,,display style 1 (balls under respective column)
Abacus.DisplayBeadsForNumberPhechano = function(column, NoOfBalls) {
    for (var ballNo = 1; ballNo <= NoOfBalls; ballNo++)
        $("#" + column + " > .BeadsImages > .ballNo" + ballNo).css("visibility", "visible");
}

// for operation "number phechano" create list of ans option to fill blank places in number text & append to html div  
Abacus.CreateHTMlTemplateForAnsOptionsAndAppend = function() {
    var optionList = '',
        TotalOptions = 10;
    var RandomOptionArray = Abacus.CreateRandomOptionArray();
    // removed class "row" for div and set width inherit
    for (var option = 1; option <= TotalOptions; option++) {
        optionList += '<div data="' + RandomOptionArray[option - 1] + '"  class="optionDiv AnsOptionText col-lg-5 col-md-5 col-sm-5 col-xs-5 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1">' + Abacus.numberTextJSON[RandomOptionArray[option - 1]] + '</div>';
        // '<span data="' + RandomOptionArray[option - 1] + '" class="AnsOptionText">' + Abacus.numberTextJSON[RandomOptionArray[option - 1]] + '</span></div>';
    }
    $("#AnsOptionList").html(optionList);
}

// create a list of 9 (unique)option (5 from(1,9) 4 from(10,99)) including correct option ..n suffle 
Abacus.CreateRandomOptionArray = function() {
    var randomOptionArray = [],
        randomOption = 0,
        oneDigitOptions = 5,
        TwoDigitOptions = 5;
    if (Abacus.level == 3) {
        if (Abacus.queArray[Abacus.queCnt][3] != 0) {
            oneDigitOptions--;
            randomOptionArray.push(Abacus.queArray[Abacus.queCnt][3]);
        }
    }
    if (Abacus.queArray[Abacus.queCnt][2] != 0 && (Abacus.queArray[Abacus.queCnt][2] != Abacus.queArray[Abacus.queCnt][3])) {
        oneDigitOptions--;
        randomOptionArray.push(Abacus.queArray[Abacus.queCnt][2]);
    }
    if (Abacus.NumberOfTensAndOnesPlace != 0 && (Abacus.queArray[Abacus.queCnt][2] != Abacus.NumberOfTensAndOnesPlace) && (Abacus.queArray[Abacus.queCnt][3] != Abacus.NumberOfTensAndOnesPlace)) {
        TwoDigitOptions--;
        randomOptionArray.push(Abacus.NumberOfTensAndOnesPlace);
    }
    for (var i = 1; i <= oneDigitOptions; i++) {
        //syntax : Math.floor(Math.random() * (max - min + 1)) + min
        randomOption = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
        while (($.inArray(randomOption, randomOptionArray) >= 0) || randomOption == Abacus.queArray[Abacus.queCnt][2] || randomOption == Abacus.queArray[Abacus.queCnt][3])
            randomOption = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
        randomOptionArray.push(randomOption);
    }
    for (var i = 1; i <= TwoDigitOptions; i++) {
        //syntax : Math.floor(Math.random() * (max - min + 1)) + min
        randomOption = Math.floor(Math.random() * (99 - 1 + 1)) + 1;
        while (($.inArray(randomOption, randomOptionArray) >= 0) || randomOption == Abacus.queArray[Abacus.queCnt][2] || randomOption == Abacus.queArray[Abacus.queCnt][3])
            randomOption = Math.floor(Math.random() * (99 - 1 + 1)) + 1;
        randomOptionArray.push(randomOption);
    }
    // shuffle option array
    for (var i = randomOptionArray.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = randomOptionArray[i];
        randomOptionArray[i] = randomOptionArray[j];
        randomOptionArray[j] = temp;
    }
    return randomOptionArray;
}

// for operation "number phechano" apply drag option to text options & make blank palces droppable 
Abacus.applyDragAndDropToAnsOptions = function() {
        $('.AnsOptionText').draggable({
            helper: "clone",
            zIndex: 100,
            revert: 'invalid',

            start: function(event, ui) {
                clearInterval(Abacus.noResponseTimer);
                clearTimeout(Abacus.nextQueTimer);
                document.getElementById("audio").pause();
                audioTag.pause();
                Abacus.seconds = 0;
                Abacus.startTimer();
                $(".optionDiv").css({ "background-color": "rgba(248, 248, 255, 0.598);" });
                $(".AnsOptionText").css({ "color": "black" });
                $(this).css({ "color": "green" }); //when drag option color will green see($( ui.draggable).css({"color":"black"});) for again text color black
                $(this).css({ "background-color": "rgb(255, 200, 128)" });
                $(ui.helper).css({ "background-color": "transparent" });
                audioTag.pause();
                audioTag.src = Utils.Path + Abacus.numberSoundsJSON[$(event.target).attr("data")];
                audioTag.play();
                audioTag.onended = function() { audioTag.pause(); }
            }
        });

        $('#TextOfThousandsPlace,#TextOfHundredsPlace,#TextOfTensAndOnesPlace').droppable({
            accept: ".AnsOptionText",
            tolerance: "intersect",
            drop: function(event, ui) {
                $(ui.draggable).css({ "color": "black" }); //again green color black after drop option
                $(ui.droppable).css({ "color": "orange" }); //color: orange;
                $(ui.draggable).css({ "background-color": "rgba(248, 248, 255, 0.598);" });
                somethingDone = true;
                ui.draggable.draggable('option', 'revert', false);
                if (($(this).attr("id") == "TextOfThousandsPlace" || $(this).attr("id") == "TextOfHundredsPlace") && ui.draggable.attr("data") > 60) {
                    // $(this).css({"background-color":"yellow"})
                    audioTag.pause();
                    audioTag.src = Utils.Path + "sounds/BuzzerWrong.mp3";
                    audioTag.play();
                    audioTag.onended = function() { audioTag.pause(); }
                    ui.draggable.draggable('option', 'revert', true);
                } else {
                    $(this).html(ui.draggable.html());
                    $(this).attr("data", ui.draggable.attr("data"));
                }
            }
        });
    }
    //check Ans of both operation using only one if condi.  for both 
Abacus.checkAnswer = function() {
        $(".SubmitIcon").css({ "pointer-events": "none" });
        $(".SpeakerIcon").css({ "pointer-events": "none" });
        $(".ClearIcon").css({ "pointer-events": "none" });
        $(".ballInPickerBox").css({ "pointer-events": "none" });
        $(".optionDiv").css({ "pointer-events": "none" });
        $(".ballInBallsBox").css({ "pointer-events": "none" });
        $(".ballInAbacusPad").css({ "pointer-events": "none" });
        audioTag.pause();
        clearTimeout(Abacus.nextQueTimer);
        scoreFlag = true;
        ansScoreCnt++;
        // var counter=Abacus.level;
        var condition = false;
        var columnNo = 4;
        var arrayCnt = 0
        for (var i = 1; i <= Abacus.level + 1; i++) {
            condition = Number($('#column' + columnNo + ' >.NoOfBallsInColumn').html()) == Abacus.queArray[Abacus.queCnt][arrayCnt];
            if (condition == false)
                break;
            columnNo--;
            arrayCnt++;
        }
        if (
            (condition == true) ||
            (Abacus.queArray[Abacus.queCnt][3] == $("#TextOfThousandsPlace").attr("data") &&
                Abacus.queArray[Abacus.queCnt][2] == $("#TextOfHundredsPlace").attr("data") &&
                Abacus.NumberOfTensAndOnesPlace == $("#TextOfTensAndOnesPlace").attr("data"))) {
            scoredMarks = 10;
            Abacus.scoreFunction();
            Abacus.correctCounter++;
            Abacus.IterationCounter++;
            audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["correct"][Math.floor(Math.random() * Abacus.CommonSoundsJSON["correct"].length)];
            audioTag.play();
            audioTag.onended = function() {
                audioTag.pause();
            };
            scoredMarks = 10;
        } else {
            scoredMarks = 0;
            Abacus.scoreFunction();
            audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["tryAgain"][Math.floor(Math.random() * Abacus.CommonSoundsJSON["tryAgain"].length)];
            audioTag.play();
            audioTag.onended = function() {
                audioTag.pause();
            };
        }
        Abacus.queArray.splice(Abacus.queCnt, 1);
        Abacus.queTypeArray.splice(Abacus.queCnt, 1);
        Abacus.allQueAudioArray.splice(Abacus.queCnt, 1);
        if (Abacus.nextQueTimer) {
            clearTimeout(Abacus.nextQueTimer);
            Abacus.nextQueTimer = null;
        }
        Abacus.nextQueTimer = setTimeout(function() {

            Abacus.nextQue();
        }, 1700);
    }
    //when click on speaker ,repeat Q sound
Abacus.repeatQuestionSound = function() {
    audioCounter = 0;
    Abacus.queTypeArray[Abacus.queCnt] == 1 ? audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["numberBanao"] : audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["numberPehachano"];
    audioTag.play();
    audioTag.onended = function() {
        audioTag.pause();
        if (Abacus.queTypeArray[Abacus.queCnt] == 1)
            Abacus.playAudioList(Abacus.allQueAudioArray[Abacus.queCnt], "");
    }
}

//play list of audio and calls "callBackFunction" if exists when list finish
Abacus.playAudioList = function(AudioList, callBackFunction) {
    audioTag.pause();
    audioTag.src = AudioList[audioCounter];
    audioTag.play();
    audioCounter++;
    if (audioCounter < (AudioList.length)) {
        audioTag.onended = function() {
            audioTag.pause();
            Abacus.playAudioList(AudioList, callBackFunction);
        }
    } else {
        audioCounter = 0;
        audioTag.onended = function() {
            audioTag.pause();
            if (callBackFunction != '')
                callBackFunction.call();
        }
    }
    Abacus.startTimer();
}

//execute when press on clear icon
Abacus.clearAbacusPad = function() {
    audioTag.pause();
    audioTag.src = Utils.Path + "sounds/clearSound.mp3";
    audioTag.play();
    audioTag.onended = function() {
        audioTag.pause();
    }
    if (Abacus.queTypeArray[Abacus.queCnt] == 1) {
        $('.NoOfBallsInColumn').html("0");
        $('.ballInAbacusPad').css('visibility', 'hidden');
    } else {
        $(".hoverBall").removeClass("hoverBall");
    }
}

Abacus.relodePage = function() {
    $("#finalPage").hide();
    if (Abacus.reloadflag == true) {
        Abacus.reloadflag = false;
        $("#gamePage", "#finalPage").hide();
        $("#levelPage").show();
    } else
        location.reload();
}
Abacus.onClickBallHover = function(object) {
    clearInterval(Abacus.noResponseTimer);
    clearTimeout(Abacus.nextQueTimer);
    document.getElementById("audio").pause();
    audioTag.pause();
    $("#" + object).addClass("hoverBall");
}

Abacus.showQueTextFun = function() {
    if (Abacus.level == 3) {
        if (Abacus.queArray[Abacus.queCnt][3] != 0) {
            Abacus.queTypeArray[Abacus.queCnt] == 1 ? $("#TextOfThousandsPlace").html(Abacus.numberTextJSON[Abacus.queArray[Abacus.queCnt][3]]) : $("#TextOfThousandsPlace").html("");
            $("#TextOfThousandsPlace ,#TextOfhazar").show();
        }
    }
    Abacus.showText();
}

Abacus.showText = function() {
    if (Abacus.level != 1) {
        if (Abacus.queArray[Abacus.queCnt][2] != 0) {
            Abacus.queTypeArray[Abacus.queCnt] == 1 ? $("#TextOfHundredsPlace").html(Abacus.numberTextJSON[Abacus.queArray[Abacus.queCnt][2]]) : $("#TextOfHundredsPlace").html("");
            $("#TextOfHundredsPlace ,#TextOfSou").show();
        }
    }
    if (Abacus.queArray[Abacus.queCnt][1] != 0) {
        Abacus.queTypeArray[Abacus.queCnt] == 1 ? $("#TextOfTensAndOnesPlace").html(Abacus.numberTextJSON[Abacus.queArray[Abacus.queCnt][1] + "" + Abacus.queArray[Abacus.queCnt][0]]) : $("#TextOfTensAndOnesPlace").html("");
        $("#TextOfTensAndOnesPlace").show();
    } else if (Abacus.queArray[Abacus.queCnt][0] != 0) {
        Abacus.queTypeArray[Abacus.queCnt] == 1 ? $("#TextOfTensAndOnesPlace").html(Abacus.numberTextJSON[Abacus.queArray[Abacus.queCnt][0]]) : $("#TextOfTensAndOnesPlace").html("");
        $("#TextOfTensAndOnesPlace").show();
    }
}

Abacus.nextQue = function() {
    clearInterval(Abacus.noResponseTimer);
    clearTimeout(Abacus.nextQueTimer);
    document.getElementById("audio").pause();
    audioTag.pause();
    $(".SubmitIcon").css({ "pointer-events": "auto" });
    $(".SpeakerIcon").css({ "pointer-events": "auto" });
    $(".ClearIcon").css({ "pointer-events": "auto" });
    $(".ballInPickerBox").css({ "pointer-events": "auto" });
    $(".optionDiv").css({ "pointer-events": "auto" });
    $(".ballInBallsBox").css({ "pointer-events": "auto" });
    $(".ballInAbacusPad").css({ "pointer-events": "auto" });
    if (scoreFlag != true) {
        Abacus.queCnt++;
    }
    if (Abacus.queArray.length == 0) {
        audioTag.pause();
        Abacus.gameOver();
    } else if (Abacus.queCnt == Abacus.queArray.length) {
        audioTag.pause();
        clearInterval(Abacus.noResponseTimer);
        document.getElementById("responseBoxDiv").style.display = "block";
        document.getElementById("No").innerHTML = Abacus.modalData.no;
        document.getElementById("Yes").innerHTML = Abacus.modalData.yes;
        document.getElementById("questionMsg").innerHTML = Abacus.modalData.responseMsg;
    } else {
        Abacus.showQue();
    }
}
Abacus.gameOver = function() {
    audioTag.pause();
    clearInterval(Abacus.noResponseTimer);
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("finalPage").style.display = "block";
    document.getElementById("responseBoxDiv").style.display = "none";
    document.getElementById('gameOver').innerHTML = Abacus.hardcodedData.message2;
    audioTag.pause();
    /* 	for(i=0;i<Object.keys(Abacus.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(Abacus.AcknowledgementPageData)[i]+" : "+Object.values(Abacus.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=Abacus.hardcodedData['createdOn'];
    	acknowledgementDiv.appendChild(div);
    	document.getElementById("acknowledgementDiv").style.display="none"; */
    Abacus.createStars();
    Abacus.giveStars();
}
Abacus.scoreFunction = function() //score Function
    {
        console.log(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, label);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, label);
        }
    }

Abacus.showSkippedQuestions = function() {
    document.getElementById("responseBoxDiv").style.display = "none";
    Abacus.queCnt = 0;
    Abacus.showQue();
}

//function which creates star divs
Abacus.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 + "img/star1.png");
        $(newDiv).append(newImage);
        $("#starsDiv").append(newDiv);
    }
};

Abacus.giveStars = function() {
    var fractionVar, i, temp;
    var numberOfStars = 0;
    ans = Abacus.total_No_of_Questions / 5;
    temp = Abacus.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 + "img/star2.png");
    /* if(temp>numberOfStars)
    document.getElementById("starImg"+i).setAttribute("src",Utils.path+"img/halfStar.png"); */
    $("#starsDiv").css("visibility", "visible");
    if (numberOfStars != 0) {
        document.getElementById("audio").src = Utils.Path + "sounds/Instructions/" + "Star" + numberOfStars + ".mp3";
        document.getElementById("audio").play();
    }
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(Abacus.correctCounter, Abacus.total_No_of_Questions, "1");
};

Abacus.goNext = function() {
    clearInterval(Abacus.skipTimer);
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}

Abacus.startTimer = function() {
    if (Abacus.noResponseTimer) {
        clearInterval(Abacus.noResponseTimer);
        Abacus.noResponseTimer = null;
        Abacus.seconds = 0;
    }
    Abacus.noResponseTimer = setInterval(function() {
        Abacus.seconds++;
        if (Abacus.seconds >= 7) {
            document.getElementById("audio").src = Utils.Path + "sounds/Instructions/please_ans_the_ques.mp3";
            document.getElementById("audio").play();
            clearInterval(Abacus.noResponseTimer);
            if (Abacus.timeOut) {
                clearTimeout(Abacus.timeOut);
                Abacus.timeOut = null;
            }
            Abacus.timeOut = setTimeout(function() {
                Abacus.seconds = 0;
                Abacus.startTimer();
            }, 2000);
        }
    }, 1000);
};