// Game Started 8/11/2018
var FindIt = {};
var Utils = {};
Utils.Path = '';
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMark = 10,
    resId = 0,
    level = 1,
    attempt = "",
    scoreSubmit = false;
Utils.mobileDeviceFlag = false;
var askedQue = [];
var currentWord, totalLength, questionType = "word";
$(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;
    setTimeout(function() {
        document.body.style.backgroundImage = "url(" + Utils.Path + "images/find-the-word_Cover.png)";
        FindIt.setImages();
        FindIt.setEvents();
        if (FindIt.hardCodedData['languageFont'] != null)
            setFontFamilyForLang("fonts/" + FindIt.hardCodedData['languageFont']);
    }, 200);
    FindIt.level = 0; //Math.floor(Math.random()*3);
    console.log("Level " + FindIt.level);
});

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

FindIt.setImages = function() {
    document.getElementById('leftDiv').style.backgroundImage = "url(" + Utils.Path + "images/bg_1.png)";
    document.getElementById('rightDiv').style.backgroundImage = "url(" + Utils.Path + "images/bg_2.png)";
    document.getElementById('home').src = Utils.Path + "images/home.png";
    document.getElementById('logo').src = Utils.Path + "images/logo.png";
    document.getElementById('playImage').src = Utils.Path + "images/Play.png";
    document.getElementById('nextQueBtn').src = Utils.Path + "images/next.png";
    document.getElementById('soundBtn').src = Utils.Path + "images/Sound.png";
    document.getElementById('column').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy-wall.png)";
    FindIt.imgArr = ["Boy_1_get", "Boy_3_wall", "Girl_3_wall", "Girl_2_tree", "Boy_2_troli", "Girl_1_tank"];
    for (var i = 0; i < FindIt.imgArr.length; i++)
        document.getElementById('object' + i).style.backgroundImage = "url(" + Utils.Path + "images/" + FindIt.imgArr[i] + ".png)";
    document.getElementById('questionDiv').style.backgroundImage = "url(" + Utils.Path + "images/Boy_1_get_Board.png)";
    FindIt.setAnswerWiseImages("");
    var tilesArr = ["Boy_1_get_Board.png", "wall_Board.png", "Girl_3_wall_Board.png", "Girl_2_tree_Board.png", "Boy_2_troli_Board.png", "Girl_1_tank_Board.png"]
        //document.getElementById('boyImg').src=Utils.Path+"images/Main-boy.png";
    for (var i = 0; i < tilesArr.length; i++)
        document.getElementById('optionTile' + i).src = Utils.Path + "images/" + tilesArr[i];

    document.getElementById('replayImg').src = Utils.Path + "images/replay.png";
    document.getElementById('creditImg').src = Utils.Path + "images/credits.png";
}

FindIt.setEvents = function() {
    $("#home").click(function() {
        FindIt.callHome();
    });
    $("#playImage").click(function() {
        FindIt.playgame();
    });
    $("#sound").click(function() {
        FindIt.playSound();
    });
    $("#nextBtn").click(function() {
        FindIt.nextQue("skip");
    });
    $("#replayImg").click(function() {
        $("#acknowledgementDiv").empty();
        $("#endPage").hide();
        FindIt.playgame();
        //location.reload();
    });
    $('.tileDiv').click(function(event) {
        event.stopPropagation();
        FindIt.checkAnswer(this.id);
    });
    $('.tileSpan').click(function(event) {
        event.stopPropagation();
        FindIt.checkAnswer(this.id);
    });
    $("#credits").click(function() {
        $("#acknowledgementDiv").css("visibility", "visible");
    });
}

// set suffix and sound
FindIt.playgame = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/bg.png)";
    //$("#logo").css("visibility","hidden");

    FindIt.reset();
    //document.body.style.backgroundImage = "url(images/back.png)";
    document.getElementById("home").style.visibility = "visible";
    document.getElementById("coverPage").style.display = "none";
    document.getElementById("gamePage").style.display = "block";
    document.getElementById('endPage').style.display = "none";
    FindIt.copyJson = JSON.parse(JSON.stringify(FindIt.wordsData[FindIt.level].levelData));
    totalLength = FindIt.copyJson.length;
    getData();
}

FindIt.reset = function() {
    FindIt.isLetterSelected = false;
    FindIt.questionArr = [];
    FindIt.attemptCnt = 0;
    FindIt.questionAttemptCnt = 0;
    FindIt.optionCnt = 6;
    FindIt.questionArr = [];
}


function getData() {
    var d;
    FindIt.correct = false;
    scoreSubmit = false;
    $('.wordSpan').text('');
    $("#nextBtn").css("pointer-events", "auto");
    clearTimeout(FindIt.answerAudio);
    FindIt.answerAudio = null;
    FindIt.questionArr = [];
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    getUniqueValArr(FindIt.copyJson, FindIt.questionArr, FindIt.optionCnt);
    FindIt.question = Math.floor(Math.random() * FindIt.questionArr.length);

    while ($.inArray(FindIt.questionArr[FindIt.question].word, askedQue) != -1)
        FindIt.question = Math.floor(Math.random() * FindIt.questionArr.length);
    currentWord = FindIt.questionArr[FindIt.question].langWord;
    FindIt.answer = FindIt.questionArr[FindIt.question].langWord;
    questionId = FindIt.questionArr[FindIt.question].questionId;
    askedQue.push(FindIt.answer);
    console.log(FindIt.questionArr);
    console.log(FindIt.answer);

    FindIt.setQuestionAndOption();
}

function getUniqueValArr(inputArr, outputArr, length) {
    for (var i = 0; i < length; i++) {
        var randNum = Math.floor(Math.random() * inputArr.length);
        if (outputArr.includes(inputArr[randNum])) {
            i--;
            continue;
        } else {
            outputArr.push(inputArr[randNum]);
        }
    }
}

FindIt.setQuestionAndOption = function() {
    for (var i = 0; i < FindIt.optionCnt; i++) {
        $("#option" + i).text(FindIt.questionArr[i].langWord);
        $("#option" + i).data("setWord", FindIt.questionArr[i].langWord);
    }
    //if(i==6)
    //{
    //$("#question").text(FindIt.questionArr[FindIt.question].langWord);
    $("#question").data("setWord", FindIt.questionArr[FindIt.question].langWord);
    //}	
    FindIt.playSound();
}

FindIt.playSound = function() {
    document.getElementById("playSound").pause();
    FindIt.answerAudio = setTimeout(function() {
        document.getElementById("playSound").src = Utils.Path + 'sounds/' + FindIt.questionArr[FindIt.question].sound;
        document.getElementById("playSound").play();
    }, 500);
}

FindIt.checkAnswer = function(id) {
    if (id.length == 7)
        id = id.substring(6);
    else
        id = id.substring(10);
    $('.tileSpan').css("pointer-events", "none");
    $('.tileDiv').css("pointer-events", "none");
    //	alert(id);

    var getClickedOption;
    getClickedOption = $("#option" + id).text();
    $("#question").text(getClickedOption);
    //getClickedOption=document.getElementById(id).nextSibling.innerHTML;
    FindIt.isLetterSelected = true;
    attempt += $("#option" + id).text() + ",";
    FindIt.questionAttemptCnt++;

    if (getClickedOption == FindIt.answer) {
        $("#nextBtn").css("pointer-events", "none");
        $("#sound").css("pointer-events", "none");
        //alert('Correct');
        FindIt.correct = true;


        document.getElementById("playSound").src = Utils.Path + 'sounds/instruction/Anahhh.mp3';
        document.getElementById("playSound").play();
        if (FindIt.questionAttemptCnt == 1)
            scoredMarks = 10;
        else if (FindIt.questionAttemptCnt == 2)
            scoredMarks = 5;
        else
            scoredMarks = 0;
        //alert(scoredMarks);
        scoreSubmit = true;
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
            Android.addLearntData(currentWord, totalLength, questionType);

        }
        console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
        console.log(currentWord, totalLength, questionType);
        FindIt.setAnswerWiseImages("sad");
        setTimeout(function() {
            FindIt.setAnswerWiseImages("");
            $('.tileSpan').css("pointer-events", "auto");
            $('.tileDiv').css("pointer-events", "auto");
            $("#sound").css("pointer-events", "auto");
            //setTimeout(function(){
            FindIt.nextQue("newQue");
            //	},1000); 
        }, 2500);
        //$("#wordSpan"+6).addClass("animated zoomIn");


    } else {
        //alert('Wrong');
        if (FindIt.questionAttemptCnt == 1) {
            document.getElementById("playSound").src = Utils.Path + 'sounds/instruction/Try_again.mp3';
            document.getElementById("playSound").play();
        }
        scoredMarks = 0;
        FindIt.correct = false;
        if (FindIt.questionAttemptCnt == 2) {
            document.getElementById("playSound").src = Utils.Path + 'sounds/instruction/Cheering.mp3';
            document.getElementById("playSound").play();
            scoreSubmit = true;
            if (Utils.mobileDeviceFlag)
                Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
            console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
        }
        $("#nextBtn").css("pointer-events", "none");
        $("#sound").css("pointer-events", "none");
        FindIt.setAnswerWiseImages("happy");
        setTimeout(function() {
            FindIt.setAnswerWiseImages("");
            $('.tileSpan').css("pointer-events", "auto");
            $('.tileDiv').css("pointer-events", "auto");
            $("#nextBtn").css("pointer-events", "auto");
            $("#sound").css("pointer-events", "auto");
            //setTimeout(function(){
            if (FindIt.questionAttemptCnt == 2)
                FindIt.nextQue("newQue");
            //},1000); 
        }, 2500);
    }
}

FindIt.setAnswerWiseImages = function(flag) {
    if (flag == "sad")
        document.getElementById('boy').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy_Win.png)";
    else if (flag == "happy")
        document.getElementById('boy').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy_Lose.png)";
    else
        document.getElementById('boy').style.backgroundImage = "url(" + Utils.Path + "images/Main-boy.png)";
    //document.getElementById('boyImg').src=Utils.Path+"images/Main-boy.png";

    for (var i = 0; i < FindIt.imgArr.length; i++) {
        if (flag == "happy" || flag == "sad")
            document.getElementById('object' + i).style.backgroundImage = "url(" + Utils.Path + "images/" + FindIt.imgArr[i] + "_" + flag + ".png)";
        else
            document.getElementById('object' + i).style.backgroundImage = "url(" + Utils.Path + "images/" + FindIt.imgArr[i] + ".png)";

    }
}
FindIt.nextQue = function(attemptType) {
    clearTimeout(FindIt.newQueLoad);
    FindIt.newQueLoad = null;
    $("#question").text("");
    FindIt.attemptCnt++;
    // skip
    if (attemptType == "skip" && FindIt.isLetterSelected == false) {
        scoredMarks = -1;
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
        //Android.addScore(resId,questionId,scoredMarks,totalMark,level,startTime);
        console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
    } // option select and skip
    else if (attemptType != "newQue" && !FindIt.correct) {
        scoredMarks = 0;
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
        //Android.addScore(resId,questionId,scoredMarks,totalMark,level,startTime);
        console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
    }

    if (FindIt.attemptCnt < 5) {
        FindIt.questionAttemptCnt = 0;
        attempt = '';
        FindIt.correct = false;
        FindIt.isLetterSelected = false;
        getData();
    } else
        FindIt.showEndPage();
    //},1000);
}

FindIt.showEndPage = function() {
    askedQue = [];
    document.getElementById("playSound").pause();
    clearTimeout(FindIt.answerAudio);
    FindIt.answerAudio = null;

    document.getElementById("gamePage").style.display = "none";
    document.getElementById("endPage").style.display = "block";
    $("#acknowledgementDiv").css("visibility", "hidden");
    FindIt.AcknowledgementPage();
    $("#gameOver").text(FindIt.hardCodedData.gameOver);
}

FindIt.AcknowledgementPage = function() {
    var i = 0,
        div;
    gameOver.innerHTML = FindIt.hardCodedData.gameOver;
    //console.log(Object.keys(FindIt.AcknowledgementPageData).length);
    for (i = 0; i < Object.keys(FindIt.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(FindIt.AcknowledgementPageData)[i] + " : " + Object.values(FindIt.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = FindIt.hardCodedData['createdOn'];
    acknowledgementDiv.appendChild(div);
}

FindIt.callHome = function() {
    var attemptedLetter = attempt.split(",").splice(0, attempt.split(",").length - 1);
    attempt = attempt.slice(0, attempt.length - 1);
    console.log(attemptedLetter.length + "**" + attempt);

    if (FindIt.isLetterSelected && !scoreSubmit) {
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMark, level, startTime, attempt);
        //Android.addScore(resId,questionId,scoredMarks,totalMark,level,startTime);	
        console.log(questionId, scoredMarks, totalMark, level, startTime, attempt);
    }

    FindIt.isLetterSelected = false;

    document.getElementById("playSound").pause();
    location.reload();
}