// 04/05/2019

var GuessWord = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var elePosition = null,
    leftPos = 0,
    askQueFlag = false,
    queSoundSrc, scoreFlag = true,
    label = "";
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0;
GuessWord.init = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/" + GuessWord.hardCodedData.cover_page + ")";
    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('Guess a Word');
    }
    setTimeout(function() {
        $("#playImgDiv").show();
        $("#playImgDiv").addClass('magictime slideDownReturn');
        $("#guessWordText").addClass('animated pulse');
        setTimeout(function() {
            $("#guessWordText").removeClass('animated pulse');
        }, 2000);
    }, 3000);
    GuessWord.setStartPage();
    GuessWord.setUnchangedVariables();
    GuessWord.setVariables();
    GuessWord.setImages();
    GuessWord.countJsonNodes();
}

GuessWord.setStartPage = function() {
    var i = 0,
        animationInterval;
    document.getElementById("aWordImg").src = Utils.Path + "images/a_word.png";
    animationInterval = setInterval(function() {
        i++;
        document.getElementById("w" + i).src = Utils.Path + "images/w" + i + ".png";
        $("#w" + i).addClass('magictime vanishIn');
        $("#w" + i).show();
        if (i >= 5) {
            setTimeout(function() {
                $("#aWordText").show();
            }, 700);
            $("#aWordImg").addClass('magictime foolishIn');
            clearInterval(animationInterval);
        }
    }, 200);
}
GuessWord.setUnchangedVariables = function() {
        GuessWord.jsonObjectLength = 0;
        GuessWord.previousQuestions = []; // array which stores previous questions
        GuessWord.totalQuestionCount = 5; //total question 
        GuessWord.attemptedQuestionCount = 0;
        GuessWord.correctSound = ["Very_Good!_The_word_is__Aditi.mp3", "Correct!_The_word_is__Aditi.mp3"];
        GuessWord.wrongSound = ["Sorry__the_word_is__Aditi.mp3", "Oh_no!_the_word_is_Aditi.mp3"];

    }
    //set variable
GuessWord.setVariables = function() {
    GuessWord.questionIndex; // preserve current question index
    GuessWord.strWithoutVowels; // question string without vowels
    GuessWord.strWithVowels; //question string with vowels
    GuessWord.attemptCount = 0; // answer attempt count(max 2 click)
    GuessWord.optionsIndex = []; // array which contains current option
    GuessWord.creditsFlag = false; // credits hode and show flag
    GuessWord.answerDivIndex; // preserve last digit of answer div
    GuessWord.loadmetaDataFlag = false;
    GuessWord.stopInterval;
    GuessWord.playSoundTimeOut;
    GuessWord.answerSoundFlag = false;
}

//set images
GuessWord.setImages = function() {
        document.getElementById("playImage").src = Utils.Path + "images/play.png";
        document.getElementById("home").src = Utils.Path + "images/Home.png";
        document.getElementById("logo").src = Utils.Path + "images/logo.png";
        document.getElementById("playAgainImage").src = Utils.Path + "images/playAgain.png";
        document.getElementById("creditsImage").src = Utils.Path + "images/credits.png";
        document.getElementById("roboImg").src = Utils.Path + "images/roboStand.png";
        document.getElementById("nextBtnImg").src = Utils.Path + "images/next.png";
    }
    // count total values in json
GuessWord.countJsonNodes = function() {
    var i = 0;
    for (i = 0; i < GuessWord.wordData.length; i++) {
        GuessWord.jsonObjectLength += GuessWord.wordData[i].data.length;
    }
}


//play game
GuessWord.playgame = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/" + GuessWord.hardCodedData.backGround + ")";
    document.getElementById("optionsMainDiv").style.backgroundImage = "url(" + Utils.Path + "images/Frame.png" + "" + ")";
    //	$("#optionsMainDiv").css("background-image", "url("+Utils.Path+"images/Frame.png"+""+")");
    document.getElementById("questionTextMainDiv").style.backgroundImage = "url(" + Utils.Path + "images/Main_box_bg.png" + "" + ")";
    document.getElementById("questionDiv").style.backgroundImage = "url(" + Utils.Path + "images/queBg.png" + "" + ")";
    document.getElementById("acknowledgementMainDiv").style.backgroundImage = "url(" + Utils.Path + "images/Frame2.png" + "" + ")";
    $("#playImgDiv").removeClass('magictime slideDownReturn');
    $("#nextBtnDiv").addClass('magictime slideRightReturn');
    $("#gamePage").show();
    $("#home").show();
    $("#home").addClass('magictime slideUpReturn');
    $("#startPage").hide();
    GuessWord.createOptionsDiv();

}

// create divs for set option strings
GuessWord.createOptionsDiv = function() {
    var i = 0,
        innrDiv, span;
    for (i = 1; i <= 4; i++) {
        innrDiv = document.createElement('div');
        innrDiv.setAttribute("id", "option" + i);
        innrDiv.setAttribute("class", "bgProp  col-xs-12 col-sm-12 col-md-12 col-lg-12 optionClass noPadding");
        innrDiv.setAttribute("onclick", "GuessWord.checkAnswer(this.id)");
        span = document.createElement('span');
        span.setAttribute("id", "optionText" + i);
        span.setAttribute("class", "optionSpanClass");
        optionsMainDiv.appendChild(innrDiv);
        innrDiv.appendChild(span);
        $("#option" + i).css("background-image", "url(" + Utils.Path + "images/Main.png" + ")");
    }
    GuessWord.setQuestion();
}

// set question function 
GuessWord.setQuestion = function() {
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    GuessWord.alphabetIndex = Math.floor(Math.random() * GuessWord.wordData.length);
    GuessWord.questionIndex = Math.floor(Math.random() * GuessWord.wordData[GuessWord.alphabetIndex].data.length);
    GuessWord.optionsIndex.push(GuessWord.questionIndex);
    GuessWord.strWithVowels = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].word;
    questionId = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].questionId;
    if (GuessWord.previousQuestions.includes(GuessWord.strWithVowels)) //if same question, then call again
    {
        GuessWord.setQuestion();
    } else {
        GuessWord.attemptedQuestionCount++;
        GuessWord.previousQuestions.push(GuessWord.strWithVowels);
        document.getElementById("questionTextDiv").innerHTML = GuessWord.strWithoutVowels = GuessWord.strWithVowels.replace(/[aeiou_]/gi, '').replace("-", '');
        $("#questionDiv").addClass('magictime spaceInLeft');
        $("#questionDiv").show();
        GuessWord.createOption();
    }
}

// create option for current quetion
GuessWord.createOption = function() {
    var i = 0,
        alphaIndex, tempStrWithoutVowels;
    while (GuessWord.optionsIndex.length < 4) {
        alphaIndex = Math.floor(Math.random() * GuessWord.wordData[GuessWord.alphabetIndex].data.length);
        if (GuessWord.optionsIndex.includes(alphaIndex)) {
            continue;
        } else {
            tempStrWithoutVowels = GuessWord.wordData[GuessWord.alphabetIndex].data[alphaIndex].word.replace(/[aeiou_]/gi, '').replace("-", '');
            if (GuessWord.questionIndex != alphaIndex && GuessWord.strWithoutVowels != tempStrWithoutVowels) {
                // check, is option word contain any one letter from GuessWord.strWithVowels(quetion string with Vowels)
                GuessWord.checkWordForSetOption(GuessWord.wordData[GuessWord.alphabetIndex].data[alphaIndex].word, alphaIndex);
            }
        }

    }
    GuessWord.setOption();
}

// check, is option word contain any one letter from GuessWord.strWithVowels(quetion string with Vowels)
GuessWord.checkWordForSetOption = function(optionWord, alphaIndex) {
    var i, j, letterCount = 0;
    for (i = 1; i < GuessWord.strWithVowels.length; i++) {
        if (optionWord.indexOf(GuessWord.strWithVowels[i]) != -1) {
            letterCount++;
            if (letterCount >= 2) {
                GuessWord.optionsIndex.push(alphaIndex);
                break;
            }
        }
    }
}

//set all option randomly 
GuessWord.setOption = function() {
    var i = 0,
        tempArray = [],
        tempIdCount, animationCount = 1,
        animationInterval;
    for (i = 0; i < GuessWord.optionsIndex.length; i++) {
        tempIdCount = Math.floor(Math.random() * 4) + 1;
        if (tempArray.includes(tempIdCount)) {
            i--;
            continue;
        } else {
            tempArray.push(tempIdCount);
            GuessWord.answerDivIndex = tempArray[0];
            document.getElementById("optionText" + tempIdCount).innerHTML = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.optionsIndex[i]].langWord;
            document.getElementById("option" + tempIdCount).setAttribute("engText", GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.optionsIndex[i]].word)
        }
    }

    animationInterval = setInterval(function() {
        if (animationCount == 2) {
            GuessWord.playSound("instruction/Buzzercorrect.mp3");
        }
        $("#option" + animationCount).addClass('magictime spaceInUp');
        $("#option" + animationCount).show();
        animationCount++;
        if (animationCount > 4) {
            $(".optionClass").css({ "pointer-events": "auto" });
            $("#nextBtnDiv").show();
            clearInterval(animationInterval);
        }
    }, 200);
}

//check answer function
GuessWord.checkAnswer = function(clickedID) {
    var dataText;
    GuessWord.attemptCount++;
    dataText = document.getElementById(clickedID).getAttribute("engText");
    $(".optionClass").removeClass('magictime spaceInUp');
    questionId = GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].questionId;
    console.log(questionId);
    if (dataText == GuessWord.strWithVowels) // correct answer
    {
        $("#nextBtnDiv").hide();
        $("#" + clickedID).addClass('animated flash');
        document.getElementById("roboImg").src = Utils.Path + "images/robo-happy.gif";
        GuessWord.loadmetaDataFlag = true;
        // play correct msg sound 
        GuessWord.soundDuration("sounds/instruction/" + GuessWord.correctSound[Math.floor(Math.random() * GuessWord.correctSound.length)]);
        $("#questionDiv").removeClass('magictime spaceInLeft');
        $(".optionClass").css({ "pointer-events": "none" });
        $(".optionClass").not("#" + clickedID).css({ "visibility": "hidden" });
        $("#" + clickedID).css({ "pointer-events": "none" });
        if (GuessWord.attemptCount == 1) //if correct in first attempt
            scoredMarks = 10;
        else //if correct in second attempt
            scoredMarks = 5;
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(GuessWord.strWithVowels, GuessWord.jsonObjectLength, "word");
        console.log(GuessWord.strWithVowels, GuessWord.jsonObjectLength, "word");
        GuessWord.scoreFun();
        GuessWord.attemptCount = 0;
    } else // if wrong answer click in both chance
    {
        $("#questionDiv").removeClass('magictime spaceInLeft');
        if (GuessWord.attemptCount > 1) {
            GuessWord.attemptCount = 0;
            $("#nextBtnDiv").hide();
            $("#option" + GuessWord.answerDivIndex).addClass('animated flash');
            $("#" + clickedID).addClass('animated shake');
            $("#" + clickedID).addClass("opacityClass");
            $(".optionClass").css({ "pointer-events": "none" });
            document.getElementById("roboImg").src = Utils.Path + "images/robo-sad.gif";
            GuessWord.loadmetaDataFlag = true;
            //play wrong msg sound  
            GuessWord.soundDuration("sounds/instruction/" + GuessWord.wrongSound[Math.floor(Math.random() * GuessWord.wrongSound.length)]);
            scoredMarks = 0;
            GuessWord.scoreFun();

        } else {
            $("#" + clickedID).addClass('animated shake');
            GuessWord.playSound("instruction/BuzzerWrong.mp3");
            $("#" + clickedID).addClass("opacityClass");
        }
    }
}

// this function takes the sound's path and return sound duration
GuessWord.soundDuration = function(sound) {
    var duration = 0;
    $('#playSound').prop('src', sound);
    if (GuessWord.loadmetaDataFlag) {
        $('#playSound').on("loadedmetadata", function() {
            duration = $('#playSound').prop('duration');
            GuessWord.loadmetaDataFlag = false;
            $('#playSound').unbind("loadedmetadata");
            GuessWord.WordSound(duration);
        });
    } else
        $('#playSound').unbind("loadedmetadata");
}

//play correct-wrong sound and call "GuessWord.soundDuration" function for word sound
GuessWord.WordSound = function(duration) {
    document.getElementById("playSound").play();
    GuessWord.showAnswerAndHighligth(GuessWord.strWithVowels);
    $("#option" + GuessWord.answerDivIndex).addClass('animated flash');
    $("#option" + GuessWord.answerDivIndex).addClass('vowelsClass');
    if (GuessWord.answerSoundFlag == false) {
        if (GuessWord.playSoundTimeOut) {
            clearTimeout(GuessWord.playSoundTimeOut);
            GuessWord.playSoundTimeOut = null;
        }
        GuessWord.playSoundTimeOut = setTimeout(function() {
            GuessWord.answerSoundFlag = true;
            GuessWord.loadmetaDataFlag = true;
            // duration function for word sound
            GuessWord.soundDuration("sounds/" + GuessWord.wordData[GuessWord.alphabetIndex].data[GuessWord.questionIndex].sound);
        }, duration * 1000);
    } else //call function for next question 
    {
        if (GuessWord.playSoundTimeOut) {
            clearTimeout(GuessWord.playSoundTimeOut);
            GuessWord.playSoundTimeOut = null;
        }
        GuessWord.playSoundTimeOut = setTimeout(function() {
            GuessWord.nextQuestion(); // load next question
        }, duration * 1500);
    }
}

//Add_score function 
GuessWord.scoreFun = function() {
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
    else
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
}

// show next question
GuessWord.nextQuestion = function() {
    $("#nextBtnDiv").hide();
    GuessWord.attemptCount = 0;
    document.getElementById("roboImg").src = Utils.Path + "images/roboStand.png";
    if (GuessWord.attemptedQuestionCount >= GuessWord.totalQuestionCount) {
        setTimeout(function() // game over and show last page
            {
                $("#gamePage").hide();
                $(".optionClass").removeClass("opacityClass");
                $(".optionClass").hide();
                $("#questionDiv").hide();
                GuessWord.AcknowledgementPage();
            }, 500);
    } else {
        setTimeout(function() // for next question
            {
                $(".optionClass").removeClass('animated shake');
                $(".optionClass").removeClass('animated flash');
                $(".optionClass").removeClass('vowelsClass');
                $(".optionClass").removeClass("opacityClass");
                $(".optionClass").css({ "visibility": "visible" });
                $(".optionClass").hide();
                $("#questionDiv").hide();
                GuessWord.setVariables();
                GuessWord.setQuestion();
            }, 10);
    }
}

// show question string with vowels and highlight the vowels and answer string
GuessWord.showAnswerAndHighligth = function(answerWord) {
    var span, vowelsString = "aeiouAEIOU";
    $("#questionTextDiv").html("");
    for (i = 0; i < answerWord.length; i++) {
        span = document.createElement('span');
        span.setAttribute("id", "span" + i);
        span.innerHTML = answerWord[i];
        if (vowelsString.includes(answerWord[i])) {
            span.setAttribute("class", "vowelsClass2");
        }
        questionTextDiv.appendChild(span);
    }
}

// if next button click
GuessWord.skipQuestion = function() {
    document.getElementById("playSound").pause();
    $(".optionClass").css({ "pointer-events": "none" });
    $("#nextBtnDiv").hide();
    $("#questionDiv").removeClass('magictime spaceInLeft');
    if (GuessWord.attemptCount != 0) // if first attempt is wrong and then skip, score will be 0
    {
        scoredMarks = 0;
        GuessWord.scoreFun();
    } else // if direct next click score will -1
    {
        scoredMarks = -1;
        GuessWord.scoreFun();
    }
    GuessWord.attemptCount = 0;
    GuessWord.nextQuestion();
}

//Acknowledgement page
GuessWord.AcknowledgementPage = function() {
    var i = 0,
        div;
    $("#acknowledgementMainDiv").show();
    $("#acknowledgementpageBottomDiv").show();
    $("#playAgainDiv").addClass('magictime slideRightReturn');
    $("#creditsDiv").addClass('magictime slideRightReturn');
    document.getElementById("gameOverMsg").innerHTML = GuessWord.hardCodedData.gameOverMSg;
    $("#gameOverMsg").show()
    acknowledgementDiv.innerHTML = "";
    for (i = 0; i < Object.keys(GuessWord.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.setAttribute("id", "div" + i);
        div.className = "nopadding fontClass forHide col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(GuessWord.AcknowledgementPageData)[i] + " : " + Object.values(GuessWord.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.setAttribute("id", "div" + i);
    div.className = "fontClass forHide col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = GuessWord.hardCodedData['createdOn'];
    acknowledgementDiv.appendChild(div);
}

//play again on click of last page playAgain button
GuessWord.playAgain = function() {
    $(".optionClass").removeClass('animated shake');
    $(".optionClass").removeClass('animated flash');
    $(".optionClass").removeClass('vowelsClass');
    $("#gamePage").show();
    $(".optionClass").css({ "visibility": "visible" });
    $("#acknowledgementMainDiv").hide();
    $("#acknowledgementDiv").hide();
    $("#acknowledgementpageBottomDiv").hide();
    GuessWord.setUnchangedVariables();
    GuessWord.countJsonNodes();
    GuessWord.setVariables();
    GuessWord.setQuestion();
}

//last pagre -> hide and show credits 
GuessWord.hideAndShowCreditsMsg = function() {
    var idCount = 0;
    $(".forHide").hide();
    $(".forHide").removeClass('animated fadeInUpBig');
    if (GuessWord.stopInterval) {
        clearInterval(GuessWord.stopInterval);
    }
    if (GuessWord.creditsFlag == false) {
        $("#div" + idCount).addClass('animated fadeInUpBig');
        $("#div" + idCount).show();
        idCount++;
        $("#acknowledgementDiv").show(); // show the credits info
        GuessWord.stopInterval = setInterval(function() {

            $("#div" + idCount).addClass('animated fadeInUpBig');
            $("#div" + idCount).show(); //one by one credits info animation
            idCount++;
            if (idCount > Object.keys(GuessWord.AcknowledgementPageData).length) {
                clearInterval(GuessWord.stopInterval);
            }
        }, 500);
        GuessWord.creditsFlag = true;
    } else {
        $("#acknowledgementDiv").hide();
        GuessWord.creditsFlag = false;
    }
}

//play sound , pass source as a parameter
GuessWord.playSound = function(src) {
    document.getElementById("playSound").src = "sounds/" + src;
    document.getElementById("playSound").play();
}

GuessWord.homeClick = function() {
    if (GuessWord.attemptCount != 0) // if first attempt wrong and then home clicked, score will be 0
    {
        scoredMarks = 0;
        GuessWord.scoreFun();
        location.reload();
    } else //otherwise only reload
        location.reload();
}