Balloons = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    totalMarks = 1,
    resId = 0,
    indexOfletter = 0,
    quesCnt = 0,
    queCorrectCnt = 0,
    type = "letter";
Balloons.seconds = 0;
Balloons.no = 5; //number of balloons
Balloons.scoredMarks = 0;
Balloons.soundFlag = true;
Balloons.skipFlag = true;
Balloons.mainOptionArr = []; //contains 5 question with options
Balloons.questionArr = []; //contains 5 question
Balloons.alreadyShownObject = [];
//function for loader
$(document).ready(function () {
    $('title').text(Balloons.GameName);
    $(".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;
    setTimeout(function() {
        $("#gamePage,#widgetDiv,#endPage").hide();
        $("#coverPage").show();
        $("#Yes").text(Balloons.hardcoded.yes);
        $("#No").text(Balloons.hardcoded.no);
        Balloons.setImages();
    }, 300);
    /* if(Utils.mobileDeviceFlag)
    	Utils.Path=Android.getMediaPath("Balloon_game"); */
});
//function to set images
Balloons.setImages = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + Balloons.coverImage + ")";
    $("#nextImage").prop("src", Utils.Path + "images/skin/Skip.png");
    $("#logo").prop("src", Utils.Path + "images/skin/logo.png");
    $("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
    $("#sound").prop("src", Utils.Path + "images/skin/Sound.png");
    $("#nextGameImage").prop('src', Utils.Path + "images/skin/Next.png");
}

Balloons.playGame = function() {
    document.body.style.backgroundImage = "url('" + Utils.Path + "images/skin/BG.jpg')";
    $("#gamePage,#widgetDiv").show();
    $("#coverPage").hide();
    for (var i = 0; i < Balloons.no; i++) { //create 5 question set
        Balloons.mulAkshareArr = [];
        Balloons.mulAkshareArr = populate(Balloons.mulAkshare, Balloons.mulAkshareArr, Balloons.no);
        uniqueQue = Math.floor(Math.random() * Balloons.mulAkshareArr.length);
        while ($.inArray(Balloons.mulAkshareArr[uniqueQue].word, Balloons.alreadyShownObject) != -1)
            uniqueQue = Math.floor(Math.random() * Balloons.mulAkshareArr.length);
        Balloons.alreadyShownObject.push(Balloons.mulAkshareArr[uniqueQue].word);
        Balloons.questionArr.push(Balloons.mulAkshareArr[uniqueQue]);
        Balloons.mainOptionArr[i] = Balloons.mulAkshareArr;
    }
    Balloons.createStars();
    Balloons.createBalloons();
}
Balloons.createStars = function() { //5 stars 
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= 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 + "images/skin/star1.png");
        $(newDiv).append(newImage);
        $("#starDiv").append(newDiv);
    }
    $("#starDiv").css("visibility", "hidden");
};
//to create balloons
Balloons.createBalloons = function() {
        var d, balloonDiv, noOfBalloons = 5;
        Balloons.skipFlag = true;
        $("#balloonDiv").css("pointer-events", "auto");
        Balloons.mulAkshareArr = [];
        d = new Date();
        startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        $('#myModal').hide();
        document.getElementById("balloonDiv").innerHTML = "";
        balloonDiv = document.getElementById("balloonDiv");
        var imgArrNum = [0, 1, 2, 3, 4];
        shuffleArray(imgArrNum);
        for (var i = 0; i < noOfBalloons; i++) {
            Balloons.createDivs(balloonDiv, imgArrNum, 'paddingClass', Balloons.mainOptionArr[quesCnt][i].word, i);
            var div = Balloons.mainOptionArr[quesCnt][i].word;
            Balloons.animate(div);
        }
        console.log(Balloons.questionArr[quesCnt].word);
        questionId = Balloons.questionArr[quesCnt].id;
        Balloons.playInstruction();
    }
    //create divs
Balloons.createDivs = function(parentDiv, imgArrNum, classname, word, i) {
        var temp = 2,
            newDiv, newImage, para;

        newDiv = document.createElement("div");
        newDiv.setAttribute("id", word);
        newDiv.setAttribute("class", "" + classname + " col-xs-" + temp + " col-md-" + temp + " col-lg-" + temp + " col-sm-" + temp);
        newDiv.setAttribute("onclick", "Balloons.checkAnswer(this);");
        parentDiv.appendChild(newDiv);

        newImage = document.createElement("img");
        newImage.setAttribute("id", "img" + word);
        newImage.setAttribute("class", "img-responsive noPadding");
        newImage.setAttribute("src", Utils.Path + Balloons.balloonImages.imgName + imgArrNum[i] + Balloons.balloonImages.imgType);
        newDiv.appendChild(newImage);

        para = document.createElement("p");
        para.setAttribute("id", "para" + word);
        para.setAttribute("class", "akshar text-center");
        para.innerHTML = word;
        newDiv.appendChild(para);
    }
    //set animation for balloons
Balloons.animate = function(div) {
        var speed = 0;
        speed = Math.floor((Math.random() * 20000) + 6000);
        $("#" + div).css({ 'top': $('#balloonDiv').height() });
        $("#" + div).animate({
            'top': '-=' + ($(document).height() + ($("#" + div).outerHeight()))
        }, speed, function() {
            $(this).stop();
            id = $(this).prop('id');
            Balloons.animate(id);
        });
    }
    //this function will execute on click of sound button
Balloons.playInstruction = function() {
    var cnt = 0;
    Balloons.soundFlag = true;
    $("#soundDiv").css("pointer-events", "none");
    $("#balloonDiv").css("pointer-events", "none");
    getDuration(Utils.Path + "sound/" + Balloons.questionArr[quesCnt].sound);
}

function getDuration(src) { //gets duration of sound 
    var duration = 0;
    if (Balloons.soundFlag) {
        $('#playSound').on("loadedmetadata", function() {
            Balloons.soundFlag = false;
            duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
            Balloons.playNextSound(duration);
        });
        $('#playSound').prop('src', src);
    }
}
Balloons.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('playSound').play();
        if (Balloons.instructionTimer) {
            clearTimeout(Balloons.instructionTimer);
            Balloons.instructionTimer = null;
        }
        Balloons.instructionTimer = setTimeout(function() {
            document.getElementById('playSound').pause();
            document.getElementById('playSound').src = Utils.Path + "sound/instruction/" + Balloons.playSound[1].sound;
            document.getElementById('playSound').play();
            $("#soundDiv").css("pointer-events", "auto");
            $("#balloonDiv").css("pointer-events", "auto");
            Balloons.startTimer();
        }, duration * 1000);
    }
Balloons.startTimer = function() { //5 second timer (No responce Sound)
        $("#nextImage").css({ "pointer-events": "auto" });
        if (Balloons.noResponseTimer) {
            clearInterval(Balloons.noResponseTimer);
            Balloons.noResponseTimer = null;
            Balloons.seconds = 0;
        }
        Balloons.noResponseTimer = setInterval(function() {
            Balloons.seconds++;
            if (Balloons.seconds >= 10) {
                document.getElementById("playSound").src = Utils.Path + "sound/instruction/" + Balloons.hardcoded.noResponce;
                document.getElementById("playSound").play();
                $(".pointerClass").css("pointer-events", "auto");
                clearInterval(Balloons.noResponseTimer)
                if (Balloons.timeOut) {
                    clearTimeout(Balloons.timeOut);
                    Balloons.timeOut = null;
                }
                Balloons.timeOut = setTimeout(function() {
                    Balloons.seconds = 0;
                    Balloons.startTimer();
                }, 2000);
            }
        }, 1000);
    }
    //function to check answer
Balloons.checkAnswer = function(element) {
    var counter = 1,
        totalMarks = 1,
        duration = 0,
        flag = false;
    Balloons.skipFlag = false;
    clearInterval(Balloons.noResponseTimer);
    clearTimeout(Balloons.nextQues);
    clearTimeout(Balloons.instructionTimer);
    $($("#myModal").children()[0]).css("border", "0")
    $(".balloonDiv").stop();
    $("#balloonDiv").css("pointer-events", "none");
    $("#soundDiv1").css("pointer-events", "none");
    if (element.id == Balloons.questionArr[quesCnt].word.trim()) {
        $(element).hide();
        queCorrectCnt++;
        Balloons.attemptedCnt++;
        counter = 0;
        Balloons.scoredMarks = 1;
        console.log(Balloons.questionArr[quesCnt].word, Balloons.mulAkshare.length, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(Balloons.questionArr[quesCnt].word, Balloons.mulAkshare.length, type);
    } else {
        counter = 1;
        Balloons.scoredMarks = 0;
    }
    setTimeout(function() {
        $('#myModal').show();
        $('#myModal').addClass('overlay');
        document.getElementById('answerImg').src = Utils.Path + Balloons.ansMessages[counter]['img'];
        document.getElementById('showMessage').innerHTML = Balloons.ansMessages[counter]['message'];
    }, 500);
    //if (counter == 0) {
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + "sound/instruction/" + Balloons.ansMessages[counter]['sound'];
    document.getElementById('playSound').play();
    console.log(resId, questionId, Balloons.scoredMarks, totalMarks, 1, startTime, Balloons.questionArr[quesCnt].word);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, Balloons.scoredMarks, totalMarks, 1, startTime, Balloons.questionArr[quesCnt].word);
    Balloons.mainOptionArr.splice(quesCnt, 1);
    Balloons.questionArr.splice(quesCnt, 1);
    if (Balloons.nextQue) {
        clearTimeout(Balloons.nextQue);
        Balloons.nextQue = null;
    }
    Balloons.nextQue = setTimeout(function() {
        $('#myModal').hide();
        Balloons.nextQuestion();
    }, 3000);

}
Balloons.nextQuestion = function() {
    clearInterval(Balloons.noResponseTimer);
    clearTimeout(Balloons.nextQues);
    clearTimeout(Balloons.instructionTimer);
    document.getElementById('playSound').pause();
    if (Balloons.skipFlag)
        quesCnt++;
    if (Balloons.questionArr.length == 0)
        Balloons.lastPage();
    else if (quesCnt == Balloons.questionArr.length) {

        $('#responseBox').css("border", "4px solid white");
        $('#responseBoxDiv').show();
        $('#confiramtionText').text(Balloons.hardcoded.message);
    } else {
        Balloons.createBalloons();
        Balloons.startTimer();
    }
}
Balloons.showNext = function(element) { //onclick of Yes/No modal option
    if ($(element).text() == Balloons.hardcoded.no)
        Balloons.lastPage();
    else
        Balloons.showRemaining();
}
Balloons.lastPage = function() { //show last page
    clearInterval(Balloons.noResponseTimer);
    clearTimeout(Balloons.nextQues);
    clearTimeout(Balloons.instructionTimer);
    document.getElementById('playSound').pause();
    $('#endPage').show();
    $('#responseBoxDiv,#gamepage,#widgetDiv').hide();
    $("#message").text(Balloons.hardcoded.gameOver);
    $("#message").css("visibility", "visible");
    Balloons.giveStars();
    console.log(queCorrectCnt, Balloons.no);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(queCorrectCnt, Balloons.no, "3");
}
Balloons.giveStars = function() { //calculates stars
    var i, numberOfStars = queCorrectCnt;
    for (i = 1; i <= numberOfStars; i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
    $("#starDiv").css("visibility", "visible");
    if (queCorrectCnt != 0) {
        document.getElementById('playSound').src = Utils.Path + 'sound/instruction/' + 'Star' + queCorrectCnt + '.mp3';
        document.getElementById('playSound').play();
    }
};
Balloons.showRemaining = function() { //show remaining questions
    quesCnt = 0;
    $('#responseBoxDiv').hide();
    $('#gamepage').show();
    $("#soundDiv").css("visibility", "visible");
    Balloons.createBalloons();
}
Balloons.nextGame = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}