var SentenceOrdering = {}; // namespace name
var Utils = {};
Utils.path = '';
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 0,
    resId = 0,
    mobileDeviceFlag = false,
    label = "",
    level = 1;
var scoreFlag;
$(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() {
        SentenceOrdering.setimage();
    }, 100);
    if (SentenceOrdering.hardcodedData.languageFont != null)
        setFontFamilyForLang(SentenceOrdering.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");
}
SentenceOrdering.globalvariables = function() {
        SentenceOrdering.QuetionArray = []; //to store the questions
        SentenceOrdering.flag = false; //used to call home
        SentenceOrdering.QueCounter = 0; //question counter 
        SentenceOrdering.timeout; //used to display correct wrong timer
        SentenceOrdering.answerArray = []; //used to store answer
        SentenceOrdering.punctuationArray = ["?", ".", "।", "!"];
        SentenceOrdering.sentenceArray = []; //used to store sentence
        SentenceOrdering.correctCounter = 0;
        SentenceOrdering.seconds = 0;
    }
    //set the all images
SentenceOrdering.setimage = function() {
    document.body.style.backgroundImage = "url(" + Utils.path + SentenceOrdering.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/Check.png");
    $("#ansImg").prop("src", Utils.path + "images/Star.png");
    $("#soundBtn").prop("src", Utils.path + "images/Sound.png");
}
SentenceOrdering.gamePage = function() {
        SentenceOrdering.globalvariables();
        document.getElementById('questions').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')";
        SentenceOrdering.playInstruction();
        SentenceOrdering.populate();
    }
    //populate questions from json
SentenceOrdering.populate = function() {
        for (var j = 0; j < 5; j++) {
            var randomNumber = Math.floor(Math.random() * SentenceOrdering.data.length);
            while (SentenceOrdering.QuetionArray.includes(SentenceOrdering.data[randomNumber])) {
                randomNumber = Math.floor(Math.random() * SentenceOrdering.data.length);
            }
            SentenceOrdering.QuetionArray.push(SentenceOrdering.data[randomNumber]);
        }
        shuffleArray(SentenceOrdering.QuetionArray);
        SentenceOrdering.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
SentenceOrdering.displayQuestions = function() {
    scoreFlag = false;
    var storeParaWordsArray = [],
        cnt = 0,
        checkPositionArray = [];
    SentenceOrdering.sentenceArray = [""];
    label = SentenceOrdering.QuetionArray[SentenceOrdering.QueCounter].Paragraphs;
    var str = SentenceOrdering.QuetionArray[SentenceOrdering.QueCounter].Paragraphs;
    d = new Date(); //date object
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); //to get the current date
    totalMarks = 10;
    scoreFlag = false;
    var storeParaWordsArray = str.split(" ");
    for (var i = 0; i < storeParaWordsArray.length; i++) {
        SentenceOrdering.sentenceArray[cnt] = SentenceOrdering.sentenceArray[cnt] + " " + storeParaWordsArray[i];
        for (var j = 0; j < SentenceOrdering.punctuationArray.length; j++) {
            if (storeParaWordsArray[i].includes(SentenceOrdering.punctuationArray[j])) {
                cnt++;
                SentenceOrdering.sentenceArray[cnt] = [""];
            }
        }
    }
    SentenceOrdering.sentenceArray.pop();
    SentenceOrdering.answerArray = SentenceOrdering.sentenceArray.slice(); //used to copy the array
    shuffleArray(SentenceOrdering.sentenceArray);
    for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
        questionDiv = document.createElement("div");
        questionDiv.setAttribute("id", "quediv" + (j + 1));
        questionDiv.setAttribute("class", " nopadding quetions drop text-center col-sm-12 col-lg-12 col-md-12 col-xs-12");
        document.getElementById('questions').appendChild(questionDiv);

        questionSpan = document.createElement("span");
        questionSpan.setAttribute("id", "quespan" + (j + 1));
        questionSpan.setAttribute("class", " nopadding quetions drag  bottomSentences animated fadeInUp");
        questionDiv.appendChild(questionSpan);
        questionSpan.setAttribute("onclick", "SentenceOrdering.getData(this)");
        questionSpan.style.backgroundColor = "transparent";
        document.getElementById('questionDiv').style.backgroundImage = Utils.path + "url('images/Box.png')";
        document.getElementById("quespan" + (j + 1)).onmouseover = function() { mouseOver(this) };
        document.getElementById("quespan" + (j + 1)).onmouseout = function() { mouseOut() };
        var word = SentenceOrdering.sentenceArray[j];
        questionSpan.innerHTML = word;
        questionSpan.setAttribute("worddata", word);
    }
    SentenceOrdering.startTimer();

    function mouseOver(object) {
        document.getElementById('audio').pause();
        document.getElementById(object.id).style.backgroundColor = "#ccffff";
    }

    function mouseOut() {
        for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
            document.getElementById("quespan" + (j + 1)).style.backgroundColor = "transparent";
        }
    }
    $(".drag").draggable({
        revert: "invalid", //text is not drop anywhere
        helper: "clone", // create "copy" with original properties
        start: function(event, ui) {
            clearInterval(SentenceOrdering.noResponseTimer);
            clearInterval(SentenceOrdering.timeout);
            document.getElementById("audio").pause();
        }
    });
    $(".drop").droppable({
        drop: function(event, ui) {
            var src = ui.draggable;
            var srcdiv = src.parent();
            var destdiv = $(this);
            var dest = destdiv.children();
            $(destdiv).append(src);
            $(srcdiv).append(dest);

            $(src).css({ "top": 0, "left": 0 });
            $(dest).css({ "top": 0, "left": 0 });
        }
    });
    $('.bottomSentences').draggable({
        cursor: 'move',
        helper: 'clone',
        start: function(e, ui) {
            $(ui.helper).addClass("ui-draggable-helper"); //used to change the font size text is drappable
        }
    });
}
SentenceOrdering.playInstruction = function() { // plays instruction
    SentenceOrdering.seconds = 0;
    clearTimeout(SentenceOrdering.timeOut);
    clearInterval(SentenceOrdering.noResponseTimer);
    getDuration(Utils.path + 'sounds/Game_Instruction.mp3');
}

function getDuration(src) {
    var duration = 0;
    $('#audio').on("loadedmetadata", function() {
        duration = $('#audio').prop('duration');
        $('#audio').unbind("loadedmetadata");
        SentenceOrdering.playNextSound(duration);
    });
    $('#audio').prop('src', src);
}
SentenceOrdering.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('audio').play();
        if (SentenceOrdering.instructionTimer) {
            clearTimeout(SentenceOrdering.instructionTimer);
            SentenceOrdering.instructionTimer = null;
        }
        SentenceOrdering.instructionTimer = setTimeout(function() {
            SentenceOrdering.startTimer();
        }, duration * 1000);
    }
SentenceOrdering.startTimer = function() {
        if (SentenceOrdering.noResponseTimer) {
            clearInterval(SentenceOrdering.noResponseTimer);
            SentenceOrdering.noResponseTimer = null;
            SentenceOrdering.seconds = 0;
        }
        SentenceOrdering.noResponseTimer = setInterval(function() {
            SentenceOrdering.seconds++;
            if (SentenceOrdering.seconds >= 7) {
                document.getElementById("audio").src = Utils.path + 'sounds/please_ans_the_ques.mp3';
                document.getElementById("audio").play();
                clearInterval(SentenceOrdering.noResponseTimer);
                if (SentenceOrdering.timeOut) {
                    clearTimeout(SentenceOrdering.timeOut);
                    SentenceOrdering.timeOut = null;
                }
                SentenceOrdering.timeOut = setTimeout(function() {
                    SentenceOrdering.seconds = 0;
                    SentenceOrdering.startTimer();
                }, 2000);
            }
        }, 1000);
    }
    //get selected word
SentenceOrdering.getData = function(object) {
        clearInterval(SentenceOrdering.noResponseTimer);
        SentenceOrdering.startTimer();
        for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
            document.getElementById("quespan" + (j + 1)).style.backgroundColor = "transparent";
        }
        document.getElementById(object.id).style.backgroundColor = "#ccffff";
    }
    //to check sentence are correct format or not
SentenceOrdering.checkAnswer = function() {
        clearInterval(SentenceOrdering.noResponseTimer);
        SentenceOrdering.QuetionArray.splice(0, 1);
        $("#checkBtn").css("pointer-Events", "none");
        var checkArray = []; //used to check the answer
        for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
            var sentence = document.getElementById("quediv" + (j + 1)).textContent; // get the span text
            checkArray.push(sentence);
        }
        if (JSON.stringify(checkArray) == JSON.stringify(SentenceOrdering.answerArray)) // used to check two array are equal or not 
        {
            SentenceOrdering.correctCounter++;
            scoredMarks = 10;
            scoreFlag = true;
            $("#audio").prop("src", Utils.path + 'sounds/Brilent.mp3');
            document.getElementById("audio").play();
            $("#ansImg").prop("src", Utils.path + "images/Star_correct-ANS.png");
            SentenceOrdering.scoreFunction();
            if (Utils.mobileDeviceFlag) {
                Android.addLearntData(SentenceOrdering.answerArray, SentenceOrdering.data.length, "sentence");
            }
            SentenceOrdering.timeout = setTimeout(function() {
                SentenceOrdering.nextQue()
            }, 2000);
        } else {
            scoredMarks = 0;
            scoreFlag = true;
            $("#audio").prop("src", Utils.path + 'sounds/Better_luck_next_time.mp3');
            document.getElementById("audio").play();
            $("#ansImg").prop("src", Utils.path + "images/Star_wrong-ANS.png");
            SentenceOrdering.scoreFunction();
            SentenceOrdering.timeout = setTimeout(function() {
                SentenceOrdering.nextQue()
            }, 2000);
        }
    }
    //score Function
SentenceOrdering.scoreFunction = function() {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
        }
    }
    //used to display next question
SentenceOrdering.nextQue = function() {
        clearInterval(SentenceOrdering.noResponseTimer);
        clearInterval(SentenceOrdering.timeout);
        document.getElementById("audio").pause();
        $("#checkBtn").css("pointer-Events", "auto");
        $("#ansImg").prop("src", Utils.path + "images/Star.png");
        scoredMarks = 0;
        if (scoreFlag == false) {
            SentenceOrdering.QueCounter++;
        }
        SentenceOrdering.answerArray = [];
        if (SentenceOrdering.QuetionArray.length == 0) {
            SentenceOrdering.gameOver();
        } else if (SentenceOrdering.QueCounter == SentenceOrdering.QuetionArray.length) {
            document.getElementById("responseBoxDiv").style.display = "block";
            document.getElementById("confiramtionText").innerHTML = SentenceOrdering.hardcodedData.responseMsg;
            document.getElementById("Yes").innerHTML = SentenceOrdering.hardcodedData.yes;
            document.getElementById("No").innerHTML = SentenceOrdering.hardcodedData.no;
        } else {
            document.getElementById('questions').innerHTML = "";
            SentenceOrdering.displayQuestions();
        }
    }
    //display skip questions
SentenceOrdering.showSkippedQuestions = function() {
        document.getElementById("responseBoxDiv").style.display = "none";
        document.getElementById('questions').innerHTML = "";
        SentenceOrdering.answerArray = [];
        SentenceOrdering.QueCounter = 0;
        document.getElementById("checkBtn").style.pointerEvents = "auto";
        SentenceOrdering.displayQuestions();
    }
    //game over
SentenceOrdering.gameOver = function() {
        document.getElementById("audio").pause();
        clearInterval(SentenceOrdering.noResponseTimer);
        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("gameover").innerHTML = SentenceOrdering.hardcodedData.message;
        SentenceOrdering.createStars();
        SentenceOrdering.giveStars();
    }
    ///function which creates star divs
SentenceOrdering.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
SentenceOrdering.giveStars = function() {
    var fractionVar, i, numberOfStars = 0,
        temp;
    SentenceOrdering.total_No_of_Questions = 5;
    ans = SentenceOrdering.total_No_of_Questions / 5;
    temp = SentenceOrdering.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("audio").src = Utils.path + "sounds/" + "star" + numberOfStars + ".mp3";
        document.getElementById("audio").play();
    }
    console.log(SentenceOrdering.correctCounter, SentenceOrdering.queCnt);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(SentenceOrdering.correctCounter, SentenceOrdering.queCnt, "1");
}
SentenceOrdering.goNext = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}