//4th May 2019
var RhymingWords = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    resId = 0,
    totalMarks = 10,
    wrongCnt = 0,
    levelNumber = 1,
    totalLength = 0,
    type = "word",
    correctCnt = 0;
RhymingWords.skipedQ = 0;
RhymingWords.homeFlag = null;
RhymingWords.alreadyShownObject = [];
RhymingWords.tempArr = []; //json data
RhymingWords.skipFlag = true;
RhymingWords.attemptFlag = false;
RhymingWords.objPointerFlag = true; //text clicked flag
RhymingWords.optionCnt = 0; //counter for playing option in sequence
RhymingWords.levelName = false; //false for learn & true for practice
//function for loader
$(document).ready(function () {
    $('title').text(RhymingWords.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;
    /* if(Utils.mobileDeviceFlag)
    	Utils.Path=Android.getMediaPath("ChitraVichitra");  */
    setTimeout(function() {
        $("#gamepage,#endpage,#homeImg").hide();
        $("#coverpage").show();
        RhymingWords.init();
        RhymingWords.setImages();
        if (RhymingWords.hardcoded['languageFont'] != null)
        setFontFamilyForLang("fonts/" + RhymingWords.hardcoded['languageFont']);
    }, 300);
});
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");
}
RhymingWords.init = function() {
    for (var i = 0; i < RhymingWords.data.length; i++)
        totalLength += RhymingWords.data[i].list.length;
    console.log(totalLength + " " + type);
    if (Utils.mobileDeviceFlag)
        RhymingWords.levelName = Android.isPractice(); //false for learn & true for practice
}
RhymingWords.setImages = function() { //set images 
    document.body.style.backgroundImage = "url(" + Utils.Path + RhymingWords.coverImage + ")";
    $("#homeImg").prop("src", Utils.Path + "images/skin/Home.png");
    $("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
    $("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
    $("#nextImage").prop("src", Utils.Path + "images/skin/Next.png");
    $("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
    $("#credit").prop("src", Utils.Path + "images/skin/credits.png");
    $("#sound").prop('src', Utils.Path + "images/skin/Sound.png");
}
RhymingWords.playGame = function() { //onclick of play button
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
    $("#homeImg,#gamepage,#gameParlourDiv").show();
    $("#coverpage").hide();
    RhymingWords.createDivs();
    $(".textClass").css("margin-top", "1vh");
    RhymingWords.skipedQ = 0;
    RhymingWords.alreadyShownObject = [];
    $("#gameOverDiv").css("visibility", "hidden");
    $("#soundDiv").css("visibility", "visible");
    RhymingWords.tempArr = RhymingWords.data.slice();
    RhymingWords.showObjects();
}
RhymingWords.createDivs = function() { //create Divs for text node
    var spanDiv, gameMachineDiv, screenDiv, displayDiv, buttonDiv, wordSoundDiv, wordSoundimg, spanDiv;
    for (var j = 0; j < RhymingWords.hardcoded.number; j++) {
        gameMachineDiv = document.createElement("div");
        gameMachineDiv.setAttribute("id", "gameMachineDiv" + j);
        gameMachineDiv.setAttribute("class", "gameMachineClass pointerClass bgClass noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
        gameMachineDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/machinBg.png)";
        $(gameMachineDiv).click(function(e) {
            RhymingWords.checkAnswer(this);
        });
        gameParlourDiv.appendChild(gameMachineDiv);

        screenDiv = document.createElement("div");
        screenDiv.setAttribute("id", "screenDiv" + j);
        screenDiv.setAttribute("class", "screenClass noPadding bgClass col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
        screenDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/screenBg.png)";
        gameMachineDiv.appendChild(screenDiv);

        displayDiv = document.createElement("div");
        displayDiv.setAttribute("id", "displayDiv" + j);
        displayDiv.setAttribute("class", "bgClass marginClass   noPadding displayClass col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
        displayDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/Display.png)";
        screenDiv.appendChild(displayDiv);

        spanDiv = document.createElement("div");
        spanDiv.setAttribute("id", "spanDiv" + j);
        spanDiv.setAttribute("class", "textFontClass noPadding noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
        displayDiv.appendChild(spanDiv);

        buttonDiv = document.createElement("div");
        buttonDiv.setAttribute("id", "buttonDiv" + j);
        buttonDiv.setAttribute("class", "borderClass buttonClass bgClass noPadding col-md-10 col-xs-10 col-lg-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
        buttonDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/buttonBg.png)";
        gameMachineDiv.appendChild(buttonDiv);

        wordSoundDiv = document.createElement("div");
        wordSoundDiv.setAttribute("class", "optionClass col-lg-6 col-md-6 col-xs-6 col-sm-6 col-sm-offset-5 col-lg-offset-5 col-md-offset-5 col-xs-offset-5");
        buttonDiv.appendChild(wordSoundDiv);
        $(wordSoundDiv).data("ans", j);

        wordSoundimg = document.createElement('img');
        wordSoundimg.setAttribute("class", "img-responsive noPadding col-xs-12 col-sm-12 col-lg-12 col-md-12");
        if (RhymingWords.levelName) {
            wordSoundimg.setAttribute("src", Utils.Path + "images/skin/plain_Sound.png");
            $(".optionClass").css("transform", "none");
        } else {
            wordSoundimg.setAttribute("src", Utils.Path + "images/skin/Sound_M.png");
            $(wordSoundDiv).click(function(e) {
                e.stopImmediatePropagation();
                RhymingWords.playOptions(this);
            });
        }
        wordSoundDiv.appendChild(wordSoundimg);
    }
}
RhymingWords.showObjects = function() { //display objects on screen
    var d;
    RhymingWords.optionCnt = 0;
    RhymingWords.skipFlag = true;
    RhymingWords.objPointerFlag = true;
    $("#nextImage").css({ "pointer-events": "none" });
    $(".pointerClass").css({ "pointer-events": "none" });
    $("#gamepage").show();
    RhymingWords.homeFlag = "showlevel";
    $("#acknowledgementDiv,.textFontClass").text('');
    $("#gameOverDiv").css("visibility", "hidden");
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    RhymingWords.randomLevel = Math.floor(Math.random() * RhymingWords.tempArr.length);
    while (RhymingWords.tempArr[RhymingWords.randomLevel].list.length < 3) //if list length < 3 calculate newlevel
        RhymingWords.randomLevel = Math.floor(Math.random() * RhymingWords.tempArr.length);
    console.log(RhymingWords.tempArr[RhymingWords.randomLevel].list.length);
    RhymingWords.uniqueTextArr = [];
    RhymingWords.uniqueTextArr = populate(RhymingWords.tempArr[RhymingWords.randomLevel].list, RhymingWords.uniqueTextArr, RhymingWords.hardcoded.number);

    for (var j = 0; j < 3; j++) { //display text & set data to text
        var index = 0;
        $("#gameMachineDiv" + j).data("ans", RhymingWords.uniqueTextArr[j].word);
        /* for (var k = 0; k < RhymingWords.uniqueTextArr[j].word.length; k++)			//create span for each letter
		{
		var spanEle;
			spanEle = document.createElement("span");
			spanEle.setAttribute("id", "spanEle" + k + j);
			spanEle.setAttribute("class", "spanClass");
			$(spanEle).text(RhymingWords.uniqueTextArr[j].word[k]);
			$("#spanDiv" + j).append(spanEle); */

        $("#spanDiv" + j).text(RhymingWords.uniqueTextArr[j].word);
        //}
        /* index = RhymingWords.uniqueTextArr[j].word.lastIndexOf(RhymingWords.tempArr[RhymingWords.randomLevel].suffix);
        for (; index < RhymingWords.uniqueTextArr[j].word.length; index++)
        	$("#spanEle" + index + j).css("color", "rgb(243, 42, 10)");	 */ //suffix in red color
    }
    RhymingWords.uniqueQue = Math.floor(Math.random() * (RhymingWords.uniqueTextArr.length)); //get unique Question
    while ($.inArray(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word, RhymingWords.alreadyShownObject) !== -1)
        RhymingWords.uniqueQue = Math.floor(Math.random() * (RhymingWords.uniqueTextArr.length));
    RhymingWords.alreadyShownObject.push(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word);
    console.log(RhymingWords.alreadyShownObject);
    questionId = parseInt(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].questionId);
    RhymingWords.playInstruction();
}
RhymingWords.playOptions = function(element) { //plays particular sound for text
    clearTimeout(RhymingWords.optionTimer);

    $("#soundDiv").css({ "pointer-events": "auto" });
    //$(".textFontClass").removeClass("animated zoomIn");
    var data = $(element).data("ans");
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + RhymingWords.uniqueTextArr[data].sound;
    document.getElementById('playSound').play();
}
RhymingWords.playInstruction = function() { // plays instruction/option sounds
    RhymingWords.soundFlag = true;
    $(".optionClass").css("pointer-events", "none");
    $("#nextImage").css({ "pointer-events": "auto" });
    if (RhymingWords.objPointerFlag)
        $(".pointerClass").css({ "pointer-events": "none" });
    if (RhymingWords.levelName)
        getDuration(Utils.Path + 'sounds/instruction/' + RhymingWords.hardcoded.instruction, "playInstruction");
    else {
        if (RhymingWords.optionCnt < 3)
            getDuration(Utils.Path + 'sounds/' + RhymingWords.uniqueTextArr[RhymingWords.optionCnt].sound, "play");
        else
            getDuration(Utils.Path + 'sounds/instruction/' + RhymingWords.hardcoded.instruction, "playInstruction");
    }
}

function getDuration(src, functionName) { //gets duration of sound 
    var duration = 0;
    if (RhymingWords.soundFlag) {
        $('#playSound').on("loadedmetadata", function() {
            RhymingWords.soundFlag = false;
            duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
            if (functionName == "playInstruction")
                RhymingWords.playNextSound(duration);
            else
                RhymingWords.playOptionsInLoop(duration);
        });
        $('#playSound').prop('src', src);
    }
}
RhymingWords.playOptionsInLoop = function(duration) //play option sounds in a loop
    {
        $("#spanDiv" + RhymingWords.optionCnt).addClass("animated zoomIn");
        document.getElementById('playSound').play();
        if (RhymingWords.optionTimer) {
            clearTimeout(RhymingWords.optionTimer);
            RhymingWords.optionTimer = null;
        }
        RhymingWords.optionTimer = setTimeout(function() {
            $("#spanDiv" + RhymingWords.optionCnt).removeClass("animated zoomIn");
            RhymingWords.optionCnt++;
            if (RhymingWords.optionCnt > 2) {
                clearTimeout(RhymingWords.optionTimer);
                RhymingWords.playInstruction();
                //setTimeout(function () { RhymingWords.playInstruction(); }, 1000);
            } else
                RhymingWords.playInstruction();
        }, duration * 2000);
    }
RhymingWords.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('playSound').play();
        if (RhymingWords.instructionTimer) {
            clearTimeout(RhymingWords.instructionTimer);
            RhymingWords.instructionTimer = null;
        }
        RhymingWords.instructionTimer = setTimeout(function() {
            document.getElementById('playSound').pause();
            document.getElementById('playSound').src = Utils.Path + 'sounds/' + RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].sound;
            document.getElementById('playSound').play();
            setTimeout(function() {
                if (RhymingWords.objPointerFlag) {
                    RhymingWords.objPointerFlag = false;
                    $(".pointerClass").css({ "pointer-events": "auto" });
                }
                if (RhymingWords.levelName != true)
                    $(".optionClass").css({ "pointer-events": "auto" });
            }, duration * 800);
        }, duration * 1000);
    }
RhymingWords.checkAnswer = function(element) { //Check Answer
    var randomSound;

    $(".optionClass").css("pointer-events", "auto");
    clearTimeout(RhymingWords.wrongAnsTimer);
    RhymingWords.skipFlag = false;
    clearTimeout(RhymingWords.instructionTimer);
    if (wrongCnt == 0)
        scoredMarks = 10;
    else if (wrongCnt == 1)
        scoredMarks = 5;
    if (($(element).data('ans') == RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word)) {
        $(element).addClass("animated zoomIn");
        correctCnt++;
        randomSound = Math.floor(Math.random() * (RhymingWords.correctAns.length));
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + RhymingWords.correctAns[randomSound];
        document.getElementById('playSound').play();

        console.log(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word, totalLength, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word, totalLength, type);
        RhymingWords.calculateScore();
    } else {
        wrongCnt++;
        $(element).css({ "pointer-events": "none", "opacity": "0.7" });
        if (RhymingWords.levelName)
            $(".optionClass").css({ "pointer-events": "none" });
        $("#spanDiv" + $($(element).children()[1].children).data("ans")).addClass("animated shake");
        RhymingWords.attemptFlag = true;
        randomSound = Math.floor(Math.random() * (RhymingWords.wrongAns.length));
        if (wrongCnt == 2)
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
        else
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + RhymingWords.wrongAns[randomSound];
        document.getElementById('playSound').play();
        if (RhymingWords.wrongAnsTimer) {
            clearTimeout(RhymingWords.wrongAnsTimer);
            RhymingWords.wrongAnsTimer = null;
        }
        RhymingWords.wrongAnsTimer = setTimeout(function() {
            $(element).children().removeClass("animated zoomIn shake");
        }, 2000);
    }
    if (wrongCnt == 2 || correctCnt == 1) {
        $(".pointerClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
        if (RhymingWords.nextQ) {
            clearTimeout(RhymingWords.nextQ);
            RhymingWords.nextQ = null;
        }
        RhymingWords.nextQ = setTimeout(function() {
            $(element).children().removeClass("animated zoomIn");
            RhymingWords.nextQuestion();
        }, 3000);
    }
}
RhymingWords.nextQuestion = function() { //Loads Next Question
    RhymingWords.skipedQ++;
    clearTimeout(RhymingWords.nextQ);
    clearTimeout(RhymingWords.wrongAnsTimer);
    clearTimeout(RhymingWords.instructionTimer);
    clearTimeout(RhymingWords.optionTimer);
    document.getElementById('playSound').pause();
    $(".gameMachineClass,.textFontClass").removeClass("animated zoomIn shake");
    if (RhymingWords.attemptFlag) {
        scoredMarks = 0;
        RhymingWords.attemptFlag = false;
        RhymingWords.calculateScore();
    }
    if (RhymingWords.skipFlag) {
        scoredMarks = -1;
        RhymingWords.calculateScore();
    }
    wrongCnt = 0;
    correctCnt = 0;
    $(".pointerClass").css({ "pointer-events": "auto", "opacity": "1" });
    RhymingWords.tempArr.splice(RhymingWords.tempArr.indexOf(RhymingWords.uniqueTextArr[RhymingWords.uniqueQue]));
    if (RhymingWords.skipedQ == 5) {
        $('#endpage').show();
        $('#gamepage,#acknowledgementDiv').hide();
        $("#soundDiv").css("visibility", "hidden");
        $("#gameOverDiv").text(RhymingWords.hardcoded.gameOver);
        $("#gameOverDiv").css("visibility", "visible");
        RhymingWords.createHardcodeddivs();
    } else
        RhymingWords.showObjects();
}
RhymingWords.createHardcodeddivs = function() {
    var ackDiv;
    for (var i = 0; i < Object.keys(RhymingWords.acknowledgementData).length; i++) {
        ackDiv = document.createElement("div");
        ackDiv.setAttribute("id", "ack" + i);
        ackDiv.setAttribute("class", "noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
        ackDiv.innerHTML = Object.keys(RhymingWords.acknowledgementData)[i] + " : " + Object.values(RhymingWords.acknowledgementData)[i];
        document.getElementById("acknowledgementDiv").appendChild(ackDiv);
    }
    div = document.createElement('div');
    div.className = "noPadding fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = RhymingWords.hardcoded['createdOn'];
    document.getElementById("acknowledgementDiv").appendChild(div);
}
RhymingWords.callHome = function() {
    if (RhymingWords.attemptFlag) {
        scoredMarks = 0;
        RhymingWords.attemptFlag = false;
        RhymingWords.calculateScore();
    }
    location.reload();
}
RhymingWords.playAgain = function() {
    document.getElementById('playSound').pause();
    $(".gameMachineClass,.textFontClass").removeClass("animated zoomIn shake");
    $("#gameOverDiv,#soundDiv").css("visibility", "visible");
    $("#endpage").hide();
    RhymingWords.skipedQ = 0;
    wrongCnt = 0;
    correctCnt = 0;
    RhymingWords.optionCnt = 0;
    RhymingWords.skipFlag = true;
    clearTimeout(RhymingWords.nextQ);
    clearTimeout(RhymingWords.instructionTimer);
    clearTimeout(RhymingWords.optionTimer);
    RhymingWords.alreadyShownObject = [];
    RhymingWords.tempArr = [];
    RhymingWords.tempArr = RhymingWords.data.slice();
    RhymingWords.showObjects();
}
RhymingWords.calculateScore = function() {
    RhymingWords.attemptFlag = false;
    console.log(resId, questionId, scoredMarks, totalMarks, levelNumber, startTime, RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, levelNumber, startTime, RhymingWords.uniqueTextArr[RhymingWords.uniqueQue].word);
}
RhymingWords.showCredit = function() {
    $("#acknowledgementDiv").show();
}