var synonyms = {}; // namespace name
var Utils = {};
Utils.path = '';
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 0,
    resId = 0,
    mobileDeviceFlag = false;
var scoreFlag = false;
$(document).ready(function() {
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
        Utils.mobileDeviceFlag = true;
    $(".se-pre-con").fadeOut("slow");
    setTimeout(function() {
        synonyms.setimage();
    }, 100);
    if (synonyms.hardcodedData.languageFont != null)
        setFontFamilyForLang(synonyms.hardcodedData.languageFont);
}, 200);
//set a font
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");
}
synonyms.globalvariables = function() {
        synonyms.QuetionArray = []; //to store the questions
        synonyms.QueCounter = 0; //question counter 
        synonyms.timeout; //timer used for display modal
        synonyms.getDataFlag = false; //used for get data 
        synonyms.getOneSynonymsArray = []; //store the all options of one word
        synonyms.optionsArray = []; //used to store options
        synonyms.seconds = 0;
        synonyms.correctCounter = 0;
        synonyms.correctWordArray = [];
    }
    //set the all images
synonyms.setimage = function() {
    document.body.style.backgroundImage = "url(" + Utils.path + synonyms.coverImage + ")";
    $("#playbtnid").prop("src", Utils.path + "images/Play.png");
    $("#logoid").prop("src", Utils.path + "images/logo.png");
    $("#skipBtn").prop("src", Utils.path + "images/Skip.png");
    $("#checkBtn").prop("src", Utils.path + "images/Done.png");
    $("#soundBtn").prop("src", Utils.path + "images/Sound.png");
    $("#answerImg").prop("src", Utils.path + "images/emoticons.png");
}
synonyms.gamePage = function() {
        synonyms.globalvariables();
        document.getElementById('questions').innerHTML = "";
        document.getElementById('ansid').innerHTML = "";
        document.getElementById("coverpage").style.display = "none";
        document.getElementById("endpage").style.display = "none";
        document.getElementById("gamepage").style.display = "block";
        document.body.style.backgroundImage = Utils.path + "url('images/BG.jpg')";
        synonyms.playInstruction();
        synonyms.populate();
    }
    //populate questions from json
synonyms.populate = function() {
        for (var j = 0; j < 20; j++) {
            var randomNumber = Math.floor(Math.random() * synonyms.data.length);
            while (synonyms.QuetionArray.includes(synonyms.data[randomNumber])) {
                randomNumber = Math.floor(Math.random() * synonyms.data.length);
            }
            synonyms.QuetionArray.push(synonyms.data[randomNumber]);
        }
        shuffleArray(synonyms.QuetionArray);
        synonyms.displayQuestions();
    }
    //suffle the array
function shuffleArray(array) {
    var i, j, temp;
    for (i = array.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
//used to display Question
synonyms.displayQuestions = function() {
        $("#checkBtn").css("visibility", "hidden");
        $("#answerImg").prop("src", Utils.path + "images/emoticons.png");
        d = new Date(); //date object
        startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); //to get the current date
        scoreFlag = false;
        synonyms.optionsArray = [];
        var droppableCounter = 0;
        for (var i = 0; i < 4; i++) {
            questionDiv = document.createElement("div");
            questionDiv.setAttribute("id", "quediv" + (i + 1));
            questionDiv.setAttribute("class", " nopadding quetions col-sm-5 col-lg-5 col-md-5 col-xs-5 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
            document.getElementById('questions').appendChild(questionDiv);
            document.getElementById("quediv" + (i + 1)).style.backgroundImage = Utils.path + "url('images/Small-Band.png')";
            for (var j = 0; j < 3; j++) {
                questionspan = document.createElement("span");
                questionspan.setAttribute("id", "quespan" + (i) + (j + 1));
                questionspan.setAttribute("class", " nopadding");
                questionDiv.appendChild(questionspan);
                if (j == 0)
                    questionspan.innerHTML = synonyms.QuetionArray[synonyms.QueCounter].word;
                else if (j == 1) {
                    questionspan.innerHTML = "=";
                    $("#quespan" + (i) + (j + 1)).css("marginLeft", "2vw");
                } else {
                    var word = synonyms.QuetionArray[synonyms.QueCounter].synonym;
                    synonyms.getOneSynonymsArray = word.split(",", 1);
                    questionspan.innerHTML = synonyms.getOneSynonymsArray[0];
                    questionspan.setAttribute("data", synonyms.getOneSynonymsArray[0]);
                    questionspan.setAttribute("onclick", "synonyms.setData(this)");
                    questionspan.style.borderBottom = "2px dashed black";
                    questionspan.style.color = "transparent";
                    $("#quespan" + (i) + (j + 1)).css("marginLeft", "2vw");
                    $("#quespan" + (i) + (j + 1)).data("value", "off");
                }
            }
            var word = synonyms.QuetionArray[synonyms.QueCounter].synonym;
            var arr = word.split(",", 1);
            synonyms.optionsArray.push(arr[0]);
            synonyms.QueCounter++;
        }
        synonyms.options();
        synonyms.displayOptions();
    }
    //choose the options
synonyms.options = function() {
        for (var j = 0; j < 2;) {
            var randomNumber = Math.floor(Math.random() * synonyms.data.length);
            while (synonyms.optionsArray.includes(synonyms.data[randomNumber])) {
                randomNumber = Math.floor(Math.random() * synonyms.data.length);
            }
            var word = synonyms.data[randomNumber].synonym;
            var arr = word.split(",", 1);
            if (!synonyms.optionsArray.includes(arr[0])) {
                synonyms.optionsArray.push(arr[0]);
                j++;
            }
        }
        shuffleArray(synonyms.optionsArray);
    }
    //to display options
synonyms.displayOptions = function() {
    synonyms.startTimer();
    document.getElementById("ansid").style.backgroundImage = Utils.path + "url('images/Long-Band.png')";
    for (var i = 0; i < synonyms.optionsArray.length; i++) {
        answerDiv = document.createElement("span");
        answerDiv.setAttribute("id", "ansdiv" + (i + 1));
        answerDiv.setAttribute("class", " nopadding words");
        document.getElementById('ansid').appendChild(answerDiv);
        if (i == synonyms.optionsArray.length - 1)
            answerDiv.innerHTML = synonyms.optionsArray[i];
        else
            answerDiv.innerHTML = synonyms.optionsArray[i] + ",";
        answerDiv.setAttribute("data", synonyms.optionsArray[i]);
        answerDiv.setAttribute("onclick", "synonyms.getData(this)");
    }
}
synonyms.playInstruction = function() { // plays instruction
    synonyms.seconds = 0;
    clearTimeout(synonyms.timeOut);
    clearInterval(synonyms.noResponseTimer);
    getDuration(Utils.path + 'sounds/Game_Instruction.mp3');
}

function getDuration(src) {
    var duration = 0;
    $('#playSound').on("loadedmetadata", function() {
        duration = $('#playSound').prop('duration');
        $('#playSound').unbind("loadedmetadata");
        synonyms.playNextSound(duration);
    });
    $('#playSound').prop('src', src);
}
synonyms.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('playSound').play();
        if (synonyms.instructionTimer) {
            clearTimeout(synonyms.instructionTimer);
            synonyms.instructionTimer = null;
        }
        synonyms.instructionTimer = setTimeout(function() {
            synonyms.startTimer();
        }, duration * 1000);
    }
synonyms.startTimer = function() {
        clearTimeout(synonyms.soundTimer);
        if (synonyms.noResponseTimer) {
            clearInterval(synonyms.noResponseTimer);
            synonyms.noResponseTimer = null;
            synonyms.seconds = 0;
        }
        synonyms.noResponseTimer = setInterval(function() {
            synonyms.seconds++;
            if (synonyms.seconds >= 7) {
                clearTimeout(synonyms.soundTimer);
                synonyms.soundTimer = null;
                document.getElementById("playSound").src = Utils.path + 'sounds/please_ans_the_ques.mp3';
                document.getElementById("playSound").play();
                clearInterval(synonyms.noResponseTimer);
                if (synonyms.timeOut) {
                    clearTimeout(synonyms.timeOut);
                    synonyms.timeOut = null;
                }
                synonyms.timeOut = setTimeout(function() {
                    synonyms.seconds = 0;
                    synonyms.startTimer();
                }, 2000);
            }
        }, 1000);
    }
    //get selected word
synonyms.getData = function(object) {
        document.getElementById('playSound').pause();
        clearInterval(synonyms.noResponseTimer);
        $(object).siblings().css("color", "black");
        synonyms.getDataFlag = true;
        synonyms.selectdWord = document.getElementById(object.id).getAttribute("data");
        document.getElementById(object.id).style.color = 'yellow';
    }
    //set selected word
synonyms.setData = function(object) {
        var counter = 0;
        if (synonyms.getDataFlag == true) {
            document.getElementById(object.id).innerHTML = synonyms.selectdWord;
            document.getElementById(object.id).style.color = "black";
            $("#" + object.id).data("value", "on");
        }
        for (var i = 0; i < 4; i++) {
            for (var j = 0; j < 3; j++) {
                if (j == 2) {
                    if ($("#quespan" + (i) + (j + 1)).data("value") == "on")
                        counter++;
                }
            }
        }
        if (counter == 4)
            $("#checkBtn").css("visibility", "visible");
    }
    //to check sentence are correct format or not
synonyms.checkAnswer = function() {
        clearInterval(synonyms.noResponseTimer);
        $("#checkBtn").css("pointer-Events", "none");
        synonyms.rightAnsCount = 0;
        totalMarks = 4
        scoreFlag = true;
        synonyms.correctWordArray = [];
        for (var i = 0; i < synonyms.optionsArray.length; i++) {
            $("#ansdiv" + (i + 1)).css("color", "black");
        }
        for (var i = 0; i < 4; i++) {
            synonyms.QuetionArray.splice(0, 1);
        }
        for (var i = 0; i < 4; i++) {
            for (var j = 0; j < 3; j++) {
                if (j == 2) {
                    var sentence = document.getElementById("quespan" + (i) + (j + 1)).textContent; // get the span text
                    var data = document.getElementById("quespan" + (i) + (j + 1)).getAttribute("data");
                    if (sentence == data && $("#quespan" + (i) + (j + 1)).data("value") == "on") {
                        document.getElementById("quespan" + (i) + (j + 1)).style.color = "green";
                        synonyms.correctWordArray.push(sentence);
                        scoredMarks++;
                    } else if ($("#quespan" + (i) + (j + 1)).data("value") == "on")
                        document.getElementById("quespan" + (i) + (j + 1)).style.color = "red";
                }
            }
        }
        if (scoredMarks == 4) {
            synonyms.correctCounter++;
            synonyms.scoreFunction();
            $("#playSound").prop("src", Utils.path + 'sounds/Brilent.mp3');
            $("#answerImg").prop("src", Utils.path + "images/emoticons_correct-ANS.png");
            document.getElementById("playSound").play();
            synonyms.timeout = setTimeout(function() {
                synonyms.nextQue()
            }, 2000);
        } else {
            synonyms.scoreFunction();
            $("#playSound").prop("src", Utils.path + 'sounds/Better_luck_next_time.mp3');
            $("#answerImg").prop("src", Utils.path + "images/emoticons_wrong-ANS.png");
            document.getElementById("playSound").play();
            synonyms.timeout = setTimeout(function() {
                synonyms.nextQue()
            }, 2000);
        }
    }
    //score Function
synonyms.scoreFunction = function() {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (synonyms.correctWordArray.length > 0) {
            for (var i = 0; i < synonyms.correctWordArray.length; i++) {
                console.log(synonyms.correctWordArray[i], synonyms.data.length, "word");
            }
        }
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
            if (synonyms.correctWordArray.length > 0) {
                for (var i = 0; i < synonyms.correctWordArray.length; i++) {
                    Android.addLearntData(synonyms.correctWordArray[i], synonyms.data.length, "word");
                }
            }
        }
    }
    //used to display next question
synonyms.nextQue = function() {
        synonyms.getDataFlag = false;
        document.getElementById("playSound").pause();
        $("#checkBtn").css("pointer-Events", "auto");
        clearInterval(synonyms.noResponseTimer);
        clearInterval(synonyms.timeout);
        synonyms.optionsArray = [];
        synonyms.correctWordArray = [];
        scoredMarks = 0;
        if (scoreFlag == true) {
            synonyms.QueCounter = 0;
        }
        $("#checkBtn").css("pointer-Events", "auto");
        if (synonyms.QuetionArray.length == 0) {
            synonyms.gameOver();
        } else if (synonyms.QueCounter == synonyms.QuetionArray.length) {
            document.getElementById("responseBoxDiv").style.display = "block";
            document.getElementById("confiramtionText").innerHTML = synonyms.hardcodedData.responseMsg;
            document.getElementById("Yes").innerHTML = synonyms.hardcodedData.yes;
            document.getElementById("No").innerHTML = synonyms.hardcodedData.no;
        } else {
            document.getElementById('ansid').innerHTML = "";
            document.getElementById('questions').innerHTML = "";
            synonyms.displayQuestions();
        }
    }
    //display skip questions
synonyms.showSkippedQuestions = function() {
        document.getElementById("responseBoxDiv").style.display = "none";
        document.getElementById('ansid').innerHTML = "";
        document.getElementById('questions').innerHTML = "";
        synonyms.getDataFlag = false;
        synonyms.flag = false;
        synonyms.optionsArray = [];
        synonyms.QueCounter = 0;
        document.getElementById("checkBtn").style.visibility = "hidden";
        $("#checkBtn").css("pointer-Events", "auto");
        synonyms.displayQuestions();
    }
    //game over
synonyms.gameOver = function() {
        document.getElementById("playSound").pause();
        document.getElementById("responseBoxDiv").style.display = "none";
        document.getElementById("coverpage").style.display = "none";
        document.getElementById("gamepage").style.display = "none";
        document.getElementById("endpage").style.display = "block";
        document.getElementById("bnext").src = Utils.path + "images/Next.png";
        document.getElementById("gameoverdiv").innerHTML = synonyms.hardcodedData.message;
        document.getElementById("gameover").style.backgroundImage = Utils.path + "url('images/Small-Band.png')";
        synonyms.createStars();
        synonyms.giveStars();
    }
    //function which creates star divs
synonyms.createStars = function() {
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= 5; i++) {
        newDiv = document.createElement("div");
        newDiv.setAttribute("id", "starDiv" + i);
        newDiv.setAttribute("class", "nopadding  col-xs-2 col-md-2 col-lg-2 col-sm-2");
        $("#starsDiv").append(newDiv);

        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/star1.png");
        $(newDiv).append(newImage);
    }
}
synonyms.giveStars = function() {
    var fractionVar, i, numberOfStars = 0,
        temp;
    synonyms.total_No_of_Questions = 5;
    ans = synonyms.total_No_of_Questions / 5;
    temp = synonyms.correctCounter / ans;
    numberOfStars = Math.floor(temp);
    temp = Math.round(temp);
    console.log(numberOfStars);
    console.log(temp);
    for (i = 1; i <= Math.floor(numberOfStars); i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.path + "images/star2.png");
    if (numberOfStars != 0) {
        document.getElementById("playSound").src = Utils.path + "sounds/" + "star" + numberOfStars + ".mp3";
        document.getElementById("playSound").play();
    }
    console.log(synonyms.correctCounter, synonyms.queCnt);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(synonyms.correctCounter, synonyms.queCnt, "1");
}
synonyms.goNext = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}