var antonyms = {}; // 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() {
        antonyms.setimage();
    }, 100);
    if (antonyms.hardcodedData.languageFont != null)
        setFontFamilyForLang(antonyms.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");
}
antonyms.globalvariables = function() {
        antonyms.QuetionArray = []; //to store the questions
        antonyms.QueCounter = 0; //question counter 
        antonyms.timeout;
        antonyms.getDataFlag = false; //used for get data 
        antonyms.optionsArray = []; //used to store options
        antonyms.seconds = 0;
        antonyms.correctCounter = 0;
        antonyms.correctWordArray = [];
    }
    //set the all images
antonyms.setimage = function() {
    document.body.style.backgroundImage = "url(" + Utils.path + antonyms.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");
}
antonyms.gamePage = function() {
        antonyms.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')";
        antonyms.playInstruction();
        antonyms.populate();
    }
    //populate questions from json
antonyms.populate = function() {
        for (var j = 0; j < 20; j++) {
            var randomNumber = Math.floor(Math.random() * antonyms.data.length);
            while (antonyms.QuetionArray.includes(antonyms.data[randomNumber])) {
                randomNumber = Math.floor(Math.random() * antonyms.data.length);
            }
            antonyms.QuetionArray.push(antonyms.data[randomNumber]);
        }
        shuffleArray(antonyms.QuetionArray);
        antonyms.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
antonyms.displayQuestions = function() {
        $("#checkBtn").css("visibility", "hidden");
        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;
        antonyms.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");
            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 = antonyms.QuetionArray[antonyms.QueCounter].Words;
                else if (j == 1) {
                    questionspan.innerHTML = "X";
                    $("#quespan" + (i) + (j + 1)).css("marginLeft", "2vw");
                } else {
                    questionspan.innerHTML = antonyms.QuetionArray[antonyms.QueCounter].Antonym;
                    questionspan.setAttribute("data", antonyms.QuetionArray[antonyms.QueCounter].Antonym);
                    questionspan.setAttribute("onclick", "antonyms.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");
                }
            }
            antonyms.optionsArray.push(antonyms.QuetionArray[antonyms.QueCounter].Antonym);
            antonyms.QueCounter++;
        }
        antonyms.options();
        antonyms.displayOptions();
    }
    //choose the options
antonyms.options = function() {
        for (var j = 0; j < 2;) {
            var randomNumber = Math.floor(Math.random() * antonyms.data.length);
            while (antonyms.optionsArray.includes(antonyms.data[randomNumber])) {
                randomNumber = Math.floor(Math.random() * antonyms.data.length);
            }
            if (!antonyms.optionsArray.includes(antonyms.data[randomNumber].Antonym)) {
                antonyms.optionsArray.push(antonyms.data[randomNumber].Antonym);
                j++;
            }
        }
        shuffleArray(antonyms.optionsArray);
    }
    //to display options
antonyms.displayOptions = function() {
    antonyms.startTimer();
    document.getElementById("ansid").style.backgroundImage = Utils.path + "url('images/Long-Band.png')";
    for (var i = 0; i < antonyms.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 == antonyms.optionsArray.length - 1)
            answerDiv.innerHTML = antonyms.optionsArray[i];
        else
            answerDiv.innerHTML = antonyms.optionsArray[i] + ",";
        answerDiv.setAttribute("data", antonyms.optionsArray[i]);
        answerDiv.setAttribute("onclick", "antonyms.getData(this)");
    }
}
antonyms.playInstruction = function() { // plays instruction
    antonyms.seconds = 0;
    clearTimeout(antonyms.timeOut);
    clearInterval(antonyms.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");
        antonyms.playNextSound(duration);
    });
    $('#playSound').prop('src', src);
}
antonyms.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('playSound').play();
        if (antonyms.instructionTimer) {
            clearTimeout(antonyms.instructionTimer);
            antonyms.instructionTimer = null;
        }
        antonyms.instructionTimer = setTimeout(function() {
            antonyms.startTimer();
        }, duration * 1000);
    }
antonyms.startTimer = function() {
        clearTimeout(antonyms.soundTimer);
        if (antonyms.noResponseTimer) {
            clearInterval(antonyms.noResponseTimer);
            antonyms.noResponseTimer = null;
            antonyms.seconds = 0;
        }
        antonyms.noResponseTimer = setInterval(function() {
            antonyms.seconds++;
            if (antonyms.seconds >= 7) {
                clearTimeout(antonyms.soundTimer);
                antonyms.soundTimer = null;
                document.getElementById("playSound").src = Utils.path + 'sounds/please_ans_the_ques.mp3';
                document.getElementById("playSound").play();
                clearInterval(antonyms.noResponseTimer);
                if (antonyms.timeOut) {
                    clearTimeout(antonyms.timeOut);
                    antonyms.timeOut = null;
                }
                antonyms.timeOut = setTimeout(function() {
                    antonyms.seconds = 0;
                    antonyms.startTimer();
                }, 2000);
            }
        }, 1000);
    }
    //get selected word
antonyms.getData = function(object) {
        document.getElementById('playSound').pause();
        clearInterval(antonyms.noResponseTimer);
        $(object).siblings().css("color", "black");
        antonyms.getDataFlag = true;
        antonyms.selectdWord = document.getElementById(object.id).getAttribute("data");
        document.getElementById(object.id).style.color = 'yellow';
    }
    //set selected word
antonyms.setData = function(object) {
        var counter = 0;
        if (antonyms.getDataFlag == true) {
            document.getElementById(object.id).innerHTML = antonyms.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
antonyms.checkAnswer = function() {
        clearInterval(antonyms.noResponseTimer);
        antonyms.rightAnsCount = 0;
        totalMarks = 4;
        antonyms.correctWordArray = [];
        scoreFlag = true;
        $("#checkBtn").css("pointer-Events", "none");
        for (var i = 0; i < antonyms.optionsArray.length; i++) {
            $("#ansdiv" + (i + 1)).css("color", "black");
        }
        for (var i = 0; i < 4; i++) {
            antonyms.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";
                        antonyms.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) {
            antonyms.correctCounter++;
            antonyms.scoreFunction();
            $("#playSound").prop("src", Utils.path + 'sounds/Brilent.mp3');
            $("#answerImg").prop("src", Utils.path + "images/emoticons_correct-ANS.png");
            document.getElementById("playSound").play();
            antonyms.timeout = setTimeout(function() {
                antonyms.nextQue()
            }, 2000);
        } else {
            antonyms.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();
            antonyms.timeout = setTimeout(function() {
                antonyms.nextQue()
            }, 2000);
        }
    }
    //score Function
antonyms.scoreFunction = function() {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (antonyms.correctWordArray.length > 0) {
            for (var i = 0; i < antonyms.correctWordArray.length; i++) {
                console.log(antonyms.correctWordArray[i], antonyms.data.length, "word");
            }
        }
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
            if (antonyms.correctWordArray.length > 0) {
                for (var i = 0; i < antonyms.correctWordArray.length; i++) {
                    Android.addLearntData(antonyms.correctWordArray[i], antonyms.data.length, "word");
                }
            }
        }
    }
    //used to display next question
antonyms.nextQue = function() {
        document.getElementById("playSound").pause();
        clearInterval(antonyms.noResponseTimer);
        clearInterval(antonyms.timeout);
        $("#answerImg").prop("src", Utils.path + "images/emoticons.png");
        $("#checkBtn").css("pointer-Events", "auto");
        antonyms.getDataFlag = false;
        antonyms.flag = false;
        scoredMarks = 0;
        antonyms.optionsArray = [];
        antonyms.correctWordArray = [];
        if (scoreFlag == true) {
            antonyms.QueCounter = 0;
        }
        if (antonyms.QuetionArray.length == 0) {
            antonyms.gameOver();
        } else if (antonyms.QueCounter == antonyms.QuetionArray.length) {
            document.getElementById("responseBoxDiv").style.display = "block";
            document.getElementById("confiramtionText").innerHTML = antonyms.hardcodedData.responseMsg;
            document.getElementById("Yes").innerHTML = antonyms.hardcodedData.yes;
            document.getElementById("No").innerHTML = antonyms.hardcodedData.no;
        } else {
            document.getElementById('ansid').innerHTML = "";
            document.getElementById('questions').innerHTML = "";
            antonyms.displayQuestions();
        }
    }
    //display skip questions
antonyms.showSkippedQuestions = function() {
        document.getElementById("responseBoxDiv").style.display = "none";
        document.getElementById('ansid').innerHTML = "";
        document.getElementById('questions').innerHTML = "";
        antonyms.getDataFlag = false;
        antonyms.flag = false;
        antonyms.optionsArray = [];
        antonyms.QueCounter = 0;
        $("#checkBtn").css("pointer-Events", "auto");
        antonyms.displayQuestions();
    }
    //game over
antonyms.gameOver = function() {
        clearInterval(antonyms.noResponseTimer);
        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 = antonyms.hardcodedData.message;
        document.getElementById("gameover").style.backgroundImage = Utils.path + "url('images/Small-Band.png')";
        antonyms.createStars();
        antonyms.giveStars();
    }
    //function which creates star divs
antonyms.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);
        }
    }
    //give credit stars
antonyms.giveStars = function() {
    var fractionVar, i, numberOfStars = 0,
        temp;
    antonyms.total_No_of_Questions = 5;
    ans = antonyms.total_No_of_Questions / 5;
    temp = antonyms.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(antonyms.correctCounter, antonyms.queCnt);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(antonyms.correctCounter, antonyms.queCnt, "1");
}
antonyms.goNext = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}