var Barakhadi = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 1,
    resId = 0,
    j = 0,
    indexOfletter = 0,
    type = "letter",
    totalLength = 0;
Barakhadi.attemptedCnt = 0;
Barakhadi.noOfTimeQuestionAnswered = 0;
Barakhadi.index = 0;
Barakhadi.cnt = 0;
Barakhadi.totalCnt = 0;
Barakhadi.attemptedCnt = 0;
Barakhadi.mulAkshareArr = [];
Barakhadi.todaysMulAkshare = [];
Barakhadi.soundFlag = true;
//function for loader
$(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(Utils.mobileDeviceFlag)
    {
    	//Utils.Path=Android.getMediaPath("Barakhadi_banao");
    	Barakhadi.todaysMulAkshare=(Android.getTodaysLetters()).split(',');
    }
    else */
    getTodaysLetters();
    console.log(Barakhadi.todaysMulAkshare);
    totalLength = Barakhadi.mulAkshare.length * Barakhadi.mulAkshare[0].list.length;
    setTimeout(function() {
        $("#homeDiv").css("visibility", "hidden");
        $('#endpage,#gamePage').hide();
        $('#coverPage').show();
        Barakhadi.setImages();

    }, 300);
});

//function to set images
Barakhadi.setImages = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + Barakhadi.coverImage + ")";
    document.getElementById('logo').src = Utils.Path + "images/logo.png";
    document.getElementById('nextImage').src = Utils.Path + "images/Next.png";
    document.getElementById('sound').src = Utils.Path + "images/Sound.png";
    document.getElementById('playImg').src = Utils.Path + "images/Play.png";
    document.getElementById('homeImg').src = Utils.Path + "images/Home.png";
    document.getElementById('akshar').style.backgroundImage = "url(" + Utils.Path + "images/Button.png)";
}
Barakhadi.playGame = function() {
    $("#homeDiv").css("visibility", "visible");
    $("#gamePage").show();
    $('#coverPage').hide();
    document.body.style.backgroundImage = "url('" + Utils.Path + "images/BG.jpg')";
    document.getElementById('aksharDiv').style.display = "block";
    Barakhadi.displayBarakhadi();
}

function getTodaysLetters() {
    var randomIndex;
    while (Barakhadi.todaysMulAkshare.length !== 2) {
        randomIndex = Math.floor(Math.random() * Barakhadi.mulAkshare.length);
        if ($.inArray(Barakhadi.mulAkshare[randomIndex].suffix, Barakhadi.todaysMulAkshare) === -1)
            Barakhadi.todaysMulAkshare.push(Barakhadi.mulAkshare[randomIndex].suffix);
    }
}
//to create no. of divs
Barakhadi.createDivs = function(parentDiv, numberOfDivs, idName, classname) {
    var temp = 2,
        newDiv, subDiv, img, totalImg = 0;
    for (var i = 0; i < 4; i++) {
        newDiv = document.createElement("div");
        newDiv.setAttribute("id", "mainDiv" + i);
        newDiv.setAttribute("class", "" + classname + "	col-xs-12 col-md-12 col-lg-12 col-sm-12");
        totalImg = 4 * numberOfDivs;
        for (var k = 0; k < numberOfDivs; k++) {
            subDiv = document.createElement("div");
            subDiv.setAttribute("id", "matraDiv" + j);
            subDiv.setAttribute("class", "" + classname + "	col-xs-" + temp + " col-md-" + temp + " col-lg-" + temp + " col-sm-" + temp);
            subDiv.setAttribute("onclick", "Barakhadi.check(this)");
            img = document.createElement("img");
            img.setAttribute("class", "img-responsive heightClass col-xs-12 col-md-12 col-lg-12 col-sm-12 noPadding");
            /* if(j>=Barakhadi.kanhaMatra.length)
            	$(img).prop('src',Utils.Path+'images/key.png');
            else
            	$(img).prop('src',Utils.Path+'images/'+Barakhadi.keyImages[j].img); */
            subDiv.append(img);
            newDiv.append(subDiv);
            $(subDiv).data('ans', Barakhadi.KanhaMatraArr[j]);
            j++;
        }
        parentDiv.append(newDiv);
    }
    Barakhadi.attachImages(totalImg);
};

Barakhadi.attachImages = function(totalImg) {
    for (var i = 0; i < totalImg; i++) {
        if (i >= Barakhadi.kanhaMatra.length)
            $('#matraDiv' + i).children('img').prop('src', Utils.Path + 'images/key.png');
        else
            $('#matraDiv' + i).children('img').prop('src', Utils.Path + 'images/' + (i + 1) +'_Telugu'+ '.png');
    }
};
//To show Barakhadi on screen
Barakhadi.displayBarakhadi = function() {
    var noOfDivs, length = 0;
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Barakhadi.noOfTimeQuestionAnswered = 0;
    document.getElementById("matraMainDiv").innerHTML = "";
    Barakhadi.kanhaMatra = [];
    Barakhadi.randomKanhaMatraSound = [];

    Barakhadi.kanhaMatra = Barakhadi.KanhaMatraArr.slice();
    length = Barakhadi.kanhaMatra.length / 4;
    if (length > 3)
        noOfDivs = 4;
    else
        noOfDivs = 3;

    Barakhadi.createDivs(matraMainDiv, noOfDivs, 'matraDiv', 'borderClass noPadding colorClass');
    indexOfletter = Barakhadi.findIndex(Barakhadi.mulAkshare, Barakhadi.todaysMulAkshare[Barakhadi.index]);
    Barakhadi.mulAkshareArr.push(Barakhadi.mulAkshare[indexOfletter]);
    if (Barakhadi.totalCnt == 0)
        Barakhadi.readText();
    document.getElementById('akshar').innerHTML = Barakhadi.mulAkshareArr[0].suffix;

    var i = Barakhadi.kanhaMatra.length;
    var k = j - Barakhadi.kanhaMatra.length;
    for (var p = 0; p < k; p++) {
        $('#matraDiv' + i).prop("onclick", null).off("click");
        i++;
    }
    Barakhadi.randomKanhaMatraSound = populate(Barakhadi.mulAkshareArr[0].list, Barakhadi.randomKanhaMatraSound, Barakhadi.mulAkshareArr[0].list.length);
    Barakhadi.randomKanhaMatraSound = shuffleArray(Barakhadi.randomKanhaMatraSound);
    Barakhadi.randomNumber = Math.floor(Math.random() * (Barakhadi.randomKanhaMatraSound.length));
    Barakhadi.randomSound = Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].sound;
    Barakhadi.readText();
    questionId = Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].id;
}
Barakhadi.findIndex = function(array, letter) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].suffix == letter)
            return i;
    }
}
Barakhadi.readText = function() {
    $(".paddingClass").css("pointer-events", "none");
    $(".noPadding").css("pointer-events", "none");
    Barakhadi.soundFlag = true;
    getDuration(Utils.Path + "sounds/" + Barakhadi.playSound[0].sound);
}

function getDuration(src) {
    var duration = 0;
    if (Barakhadi.soundFlag) {
        $('#playSound').on("loadedmetadata", function() {
            Barakhadi.soundFlag = false;
            duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
            Barakhadi.playFirstSound(duration);
        });
        $('#playSound').prop('src', src);
    }
}
Barakhadi.playFirstSound = function(duration) {
    console.log(duration);
    document.getElementById('playSound').play();
    if (Barakhadi.tempTimer) {
        clearTimeout(Barakhadi.tempTimer);
        Barakhadi.tempTimer = null;
    }
    Barakhadi.tempTimer = setTimeout(function() {
        document.getElementById("playSound").pause();
        document.getElementById('playSound').src = Utils.Path + "sounds/" + Barakhadi.randomSound;
        document.getElementById("playSound").play();
    }, duration * 1000);
    setTimeout(function() {
        $(".paddingClass").css("pointer-events", "auto");
        $('.noPadding').css('pointer-events', 'auto');
    }, 1000);

}
Barakhadi.check = function(element) {
    var a = $(element).data('ans');
    a = ($("#akshar").text()).concat(a);
    $(".paddingClass").css("pointer-events", "none");
    Barakhadi.noOfTimeQuestionAnswered++;
    var randomSound = Math.floor(Math.random() * (Barakhadi.correctAns.length));
    if ((Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].word.trim()) == a) {
        scoredMarks = 1;
        Barakhadi.cnt++;
        Barakhadi.totalCnt++;
        Barakhadi.attemptedCnt++;
        $('.noPadding').css('pointer-events', 'none');
        document.getElementById('akshar').innerHTML = "";
        $("#akshar").append(a);
        document.getElementById('akshar').style.backgroundImage = "url(" + Utils.Path + "images/green.png)";
        document.getElementById("playSound").src = Utils.Path + 'sounds/' + Barakhadi.correctAns[randomSound];
        document.getElementById("playSound").play();
        console.log(Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].word, Barakhadi.mulAkshare.length * Barakhadi.mulAkshare[0].list.length, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].word, Barakhadi.mulAkshare.length * Barakhadi.mulAkshare[0].list.length, type);

    } else {
        scoredMarks = 0;
        Barakhadi.totalCnt++;
        Barakhadi.cnt = 0;
        $('.noPadding').css('pointer-events', 'none');
        document.getElementById('akshar').innerHTML = "";
        document.getElementById('akshar').style.backgroundImage = "url(" + Utils.Path + "images/red.png)";
        $("#akshar").addClass('blinkClass');
        $("#akshar").append(a);
        setTimeout(function() {
            document.getElementById('akshar').innerHTML = "";
            $("#akshar").removeClass('blinkClass');
            $("#akshar").append(Barakhadi.mulAkshareArr[0].suffix);
            document.getElementById('akshar').style.color = "white";
            $('.noPadding').css('pointer-events', 'auto');
        }, 2000);
        document.getElementById("playSound").src = Utils.Path + "sounds/wrongSoundAksharkhadi.mp3";
        document.getElementById("playSound").play();
    }
    document.getElementById('nextDiv').style.display = "none";
    setTimeout(function() {
        document.getElementById('nextDiv').style.display = "block";
    }, 2000);
    if (Barakhadi.noOfTimeQuestionAnswered == 1) {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].word);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Barakhadi.randomKanhaMatraSound[Barakhadi.randomNumber].word);
    }
    if (Barakhadi.cnt == 3 || Barakhadi.totalCnt == 9) {
        /* if(Utils.mobileDeviceFlag)
        	Android.StudentLevelDetection(Barakhadi.attemptedCnt,Barakhadi.totalCnt); */
        console.log(Barakhadi.attemptedCnt, Barakhadi.totalCnt);
        Barakhadi.index++;
        Barakhadi.cnt = 0;
        Barakhadi.totalCnt = 0;
        if (Barakhadi.index == 1)
            Barakhadi.attemptedCnt = 0;

    }
    setTimeout(function() {
        Barakhadi.mulAkshareArr = [];
        Barakhadi.nextBarakhadi();
    }, 2000);
}
Barakhadi.nextBarakhadi = function() {
    $(".paddingClass").css("pointer-events", "auto");
    document.getElementById('akshar').style.backgroundImage = "url(" + Utils.Path + "images/Button.png)";
    j = 0;
    if (Barakhadi.index >= 2) {
        $('#endpage').show();
        document.getElementById('gamePage').innerHTML = "";
        document.getElementById('message').innerHTML = Barakhadi.endGame[0].message;
    } else
        Barakhadi.displayBarakhadi();
}
Barakhadi.callHome = function() {
    location.reload(true);
}