var Abacus = {},
    Utils = {};
Utils.mobileDeviceFlag = false;
var audioCounter = 0,
    NumberBanaoOrNumberPhechanoArray = [1, 2],
    Language, startTime, somethingDone = false,
    fistTimeAnsWrong = false; //operation : 1=Number Banao ,2 =number phechano
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    label = 0,
    resId = 0,
    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 scoreFlag = false;
$(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 = "Hindi";
        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");
    //  $("#ballFor10000").prop("src", Utils.Path + "img/ballFor10000.png");
    $(".homeIcon").prop("src", Utils.Path + "img/home.png");
    $(".playIcon").prop("src", Utils.Path + "img/play.png");
    $(".prathamlogo").prop("src", Utils.Path + "img/logo.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/next.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();
}

// 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 = 1;
        Abacus.startgameForRange(min, max); });
    /* on click ball hover*/
    $(".ballInAbacusPad").on("click", function() {
        Abacus.onClickBallHover(this.id);

    });

    $(".SpeakerIcon").on("click", function() {
        $(".SpeakerIcon").addClass("animated pulse");
        setTimeout(function() { $(".SpeakerIcon").removeClass("animated pulse"); }, 700);
        Abacus.repeatQuestionSound();
    });
    $(".homeIcon").on("click", function() {
        Abacus.relodePage();
    });
    $(".ClearIcon").on("click", function() {
        $(".ClearIcon").addClass("animated pulse");
        setTimeout(function() { $(".ClearIcon").removeClass("animated pulse"); }, 700);
        Abacus.clearAbacusPad();
    });
    $(".SubmitIcon").on("click", function() {
        $(".SubmitIcon").addClass("animated pulse");
        setTimeout(function() { $(".SubmitIcon").removeClass("animated pulse"); }, 700);
        Abacus.checkAnswer();
    });
    $(".NextIcon").on("click", function() {
        $(".NextIcon").addClass("animated pulse");
        setTimeout(function() { $(".NextIcon").removeClass("animated pulse"); }, 700);
        if (scoreFlag == false) {
            if (somethingDone == true) {
                somethingDone = false;
                scoredMarks = 0;
            } else {
                scoredMarks = -1;
            }
            console.log(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, Abacus.AskedNumber);
            if (Utils.mobileDeviceFlag)
                Android.addScore(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, Abacus.AskedNumber);
        } //resId,questionId,scoredMarks,totalMarks,1,startTime,label
        Abacus.ChooseRandomNumberToPlay();
    });
    $(".homeIcon,.playIcon").on("click", Abacus.showLevelPage);
}

// 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");
}

//when click on Play or Home ,display level page
Abacus.showLevelPage = function() {
    $('#gamePage').show();
    $("#coverPage").hide();
    audioTag.pause();
	Abacus.level = 2;
		min = 100;
        max = 999;
        Abacus.startgameForRange(min, max);
    if (somethingDone == true) {
        somethingDone = false;
        scoredMarks = 0;
        console.log(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, Abacus.AskedNumber);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, Abacus.AskedNumber);
    }
}

//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) {
            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.operation == 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.operation == 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);
}

//choose a random number to play within range of level (Maximum number,minimum nu.)
Abacus.ChooseRandomNumberToPlay = function() {

    $(".NextIcon").css({ "pointer-events": "auto" });
    $(".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" });
    scoreFlag = false;
    $(".hoverBall").removeClass("hoverBall");
    ansScoreCnt = 0;
    somethingDone = false;
    fistTimeAnsWrong = false;
    Abacus.reloadflag = true;
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Abacus.audioArrayOfWholeNumber = [];
    audioCounter = 0;
    Abacus.OnesPlace = 0;
    Abacus.TensPlace = 0;
    Abacus.HundredsPlace = 0;
    Abacus.ThousandsPlace = 0, Abacus.NumberOfTensAndOnesPlace = 0;
    $('.ballInAbacusPad').css('visibility', 'hidden');
    $('.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,9)
        Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; // in range(1,9)
    } else if (Abacus.MaximumNumberOfLevel == 999) {
        //syntax : Math.floor(Math.random() * (max - min + 1)) + min
        Abacus.OnesPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 0; //in range(0,9)
        Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.TensPlace = 0 : Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 0;
        Abacus.HundredsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(1,9)
    } 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.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.TensPlace = 0 : Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,)
        Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.HundredsPlace = 0 : Abacus.HundredsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; //in range(0,6)
        Abacus.ThousandsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1; // in range(1,6)
    }
    /*  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.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.TensPlace = 0 : Abacus.TensPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1;  //in range(0,6)
       Abacus.IterationCounter > 4 && Abacus.IterationCounter <= 9 ? Abacus.HundredsPlace = 0 : Abacus.HundredsPlace = Math.floor(Math.random() * (6 - 1 + 1)) + 1;  //in range(0,9)
       Abacus.ThousandsPlace = Math.floor(Math.random() * (60 - 10 + 1)) + 10;  // in range(1,99)
       Abacus.TenThousandsPlace = Math.floor(Abacus.ThousandsPlace / 10);
       Abacus.newThousandsPlace = Abacus.ThousandsPlace % 10;

     } */
    Abacus.MinimumNumberOfLevel != 10 ? $("#TextOfTensAndOnesPlace").css("margin-left", "2%") : $("#TextOfTensAndOnesPlace").css("margin-left", "1%");
    Abacus.MinimumNumberOfLevel != 100 ? $("#TextOfHundredsPlace").css("margin-left", "1%") : $("#TextOfHundredsPlace").css("margin-left", "1%");

    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();

    //make complete Audio array of whole number & set respective text from JSON Data
    if (Abacus.ThousandsPlace != 0) {
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON[Abacus.ThousandsPlace]);
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.sauHajarSoundsJSON[2]);
        Abacus.operation == 1 ? $("#TextOfThousandsPlace").html(Abacus.numberTextJSON[Abacus.ThousandsPlace]) : $("#TextOfThousandsPlace").html("");
        $("#TextOfThousandsPlace ,#TextOfhazar").show();
    }

    if (Abacus.HundredsPlace != 0) {
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON[Abacus.HundredsPlace]);
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.sauHajarSoundsJSON[1]);
        Abacus.operation == 1 ? $("#TextOfHundredsPlace").html(Abacus.numberTextJSON[Abacus.HundredsPlace]) : $("#TextOfHundredsPlace").html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        $("#TextOfHundredsPlace ,#TextOfSou").show();
    }

    if (Abacus.TensPlace != 0) {
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON["" + Abacus.TensPlace + Abacus.OnesPlace]);
        Abacus.operation == 1 ? $("#TextOfTensAndOnesPlace").html(Abacus.numberTextJSON[Abacus.TensPlace + "" + Abacus.OnesPlace]) : $("#TextOfTensAndOnesPlace").html("");
        $("#TextOfTensAndOnesPlace").show();
    } else if (Abacus.OnesPlace != 0) {
        Abacus.audioArrayOfWholeNumber.push(Utils.Path + Abacus.numberSoundsJSON[Abacus.OnesPlace]);
        Abacus.operation == 1 ? $("#TextOfTensAndOnesPlace").html(Abacus.numberTextJSON[Abacus.OnesPlace]) : $("#TextOfTensAndOnesPlace").html("");
        $("#TextOfTensAndOnesPlace").show();
    }
    Abacus.NumberOfTensAndOnesPlace = (Abacus.TensPlace * 10 + Abacus.OnesPlace);

    console.log(Abacus.audioArrayOfWholeNumber);
    //start game for selected operation
    if (Abacus.operation == 1)
        Abacus.startGameForType_NumberBanao();
    else
        Abacus.startGameForType_NumberPehchano();
    //check que cnt and show next que or game over
    if (Abacus.queCnt >= 5) {
        $("#gamePage").hide();
        $("#finalPage").show();
        document.getElementById("gameOver").innerHTML = Abacus.hardcodedData.message2;
        audioTag.pause();
    } else
        Abacus.queCnt++;

}

//ask selected random number for "Number Banao"
Abacus.startGameForType_NumberBanao = function() {
    $("#AskedQues").html(Abacus.labelsAndTextJSON["NumberBanao"]);
    audioTag.pause();
    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.audioArrayOfWholeNumber, "");
        }
    }
    $("#abacusPad").css("text-align", "center");
    $("#abacusPad > .ballFor1,#abacusPad > .ballFor10,#abacusPad > .ballFor100,#abacusPad > .ballFor1000").remove();
    $("#column1,#column2,#column3,#column4").show();
    $(".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() {
    $("#AskedQues").html(Abacus.labelsAndTextJSON["NumberPechano"]);
    audioTag.pause();
    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": "orange", "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").remove();
    ballsDisplayStyle = Math.floor(Math.random() * (2 - 1 + 1)) + 1; // in range(1,2)
    // STyle = 1-balls under respective column
    if (ballsDisplayStyle == 1) {
        $("#abacusPad").css("text-align", "center");
        $("#column1,#column2,#column3,#column4").show();
        // Abacus.DisplayBeadsForNumberPhechano("column0", Abacus.TenThousandsPlace);
        Abacus.DisplayBeadsForNumberPhechano("column1", Abacus.ThousandsPlace);
        Abacus.DisplayBeadsForNumberPhechano("column2", Abacus.HundredsPlace);
        Abacus.DisplayBeadsForNumberPhechano("column3", Abacus.TensPlace);
        Abacus.DisplayBeadsForNumberPhechano("column4", Abacus.OnesPlace);
    }
    // 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.ThousandsPlace);
        Abacus.appendBallsImagesOfRandomnumber("ballFor100", Abacus.HundredsPlace);
        Abacus.appendBallsImagesOfRandomnumber("ballFor10", Abacus.TensPlace);
        Abacus.appendBallsImagesOfRandomnumber("ballFor1", Abacus.OnesPlace);
        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.ThousandsPlace != 0) {
        oneDigitOptions--;
        randomOptionArray.push(Abacus.ThousandsPlace);
    }
    if (Abacus.HundredsPlace != 0 && (Abacus.HundredsPlace != Abacus.ThousandsPlace)) {
        oneDigitOptions--;
        randomOptionArray.push(Abacus.HundredsPlace);
    }
    if (Abacus.NumberOfTensAndOnesPlace != 0 && (Abacus.HundredsPlace != Abacus.NumberOfTensAndOnesPlace) && (Abacus.ThousandsPlace != 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.HundredsPlace || randomOption == Abacus.ThousandsPlace)
            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.HundredsPlace || randomOption == Abacus.ThousandsPlace)
            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) {
            $(".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.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() {
    $(".NextIcon").css({ "pointer-events": "none" });
    $(".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" });
    ansScoreCnt++;

    if ((Number($('#column1 >.NoOfBallsInColumn').html()) == Abacus.ThousandsPlace &&
            Number($('#column2 >.NoOfBallsInColumn').html()) == Abacus.HundredsPlace &&
            Number($('#column3 >.NoOfBallsInColumn').html()) == Abacus.TensPlace &&
            Number($('#column4 >.NoOfBallsInColumn').html()) == Abacus.OnesPlace) ||

        (Abacus.ThousandsPlace == $("#TextOfThousandsPlace").attr("data") &&
            Abacus.HundredsPlace == $("#TextOfHundredsPlace").attr("data") &&
            Abacus.NumberOfTensAndOnesPlace == $("#TextOfTensAndOnesPlace").attr("data"))) {

        Abacus.IterationCounter++;
        audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["correct"][Math.floor(Math.random() * Abacus.CommonSoundsJSON["correct"].length)];
        audioTag.play();
        audioTag.onended = function() {
            $(".NextIcon").css({ "pointer-events": "auto" });
            audioTag.pause();
            if (Abacus.operation == 2) {
                audioCounter = 0;
                Abacus.playAudioList(Abacus.audioArrayOfWholeNumber, function() {
                    Abacus.clearAbacusPad();
                    Abacus.ChooseRandomNumberToPlay();
                });
            } else {
                Abacus.clearAbacusPad();
                Abacus.ChooseRandomNumberToPlay();
            }
        }
        scoredMarks = 10;

    } else {
        scoredMarks = 0;
        audioTag.src = Utils.Path + Abacus.CommonSoundsJSON["tryAgain"][Math.floor(Math.random() * Abacus.CommonSoundsJSON["tryAgain"].length)];
        audioTag.play();
        audioTag.onended = function() {
            $(".NextIcon").css({ "pointer-events": "auto" });
            $(".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" });
            Abacus.repeatQuestionSound();
        };
        if (somethingDone == true && !fistTimeAnsWrong) {
            fistTimeAnsWrong = true;
            scoredMarks = 0;
            /*  console.log(resId,questionId,scoredMarks,totalMarks,Abacus.level,startTime, Abacus.AskedNumber);
             if (Utils.mobileDeviceFlag)
               Android.addScore(resId,questionId,scoredMarks,totalMarks,Abacus.level,startTime, Abacus.AskedNumber); */
        }
    }
    if (ansScoreCnt == 1) {
        scoreFlag = true;
        console.log(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, Abacus.AskedNumber);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, Abacus.level, startTime, Abacus.AskedNumber);
    }
    somethingDone = false;
}

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

//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();
        }
    }
}

//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.operation == 1) {
        $('.NoOfBallsInColumn').html("0");
        $('.ballInAbacusPad').css('visibility', 'hidden');
    } else {
        $(".hoverBall").removeClass("hoverBall");
        //  $("#TextOfThousandsPlace,#TextOfHundredsPlace").html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").attr("data", "0");
        // $("#TextOfTensAndOnesPlace").html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").attr("data", "0");
    }
}

Abacus.relodePage = function() {
    /* $("#finalPage").hide();
    if (Abacus.reloadflag == true) {
        Abacus.reloadflag = false;
        $("#gamePage", "#finalPage").hide();
      //  $("#levelPage").show();
    } else */
        location.reload();
}
Abacus.onClickBallHover = function(object) {
    $("#" + object).addClass("hoverBall");
}