var SentenceOrdering = {}; // namespace name
var Utils = {};
Utils.path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 0,
    resId = 0,
    label = "",
    level = 1;
var scoreFlag = false,
    helpFlag = 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() {
        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 = []; //to check the answer
        SentenceOrdering.punctuationArray = ["?", ".", "।", "!"]; //punctuation Array
        SentenceOrdering.sentenceArray = []; //used to store sentence
        SentenceOrdering.Attempt = 0;
        SentenceOrdering.practice = false;
        SentenceOrdering.helpClick = true;
        SentenceOrdering.helpCounter = 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");
    $("#homeid").prop("src", Utils.path + "images/Home.png");
    $("#logoid").prop("src", Utils.path + "images/logo.png");
    $("#bnext").prop("src", Utils.path + "images/Next.png");
    $("#helpBtn").prop("src", Utils.path + "images/Show-Help.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();
        if (Utils.mobileDeviceFlag == true)
            SentenceOrdering.practice = Android.isPractice();
        document.getElementById("acknowledgementDiv").innerHTML = "";
        document.getElementById('questions').innerHTML = "";
        document.getElementById("coverpage").style.display = "none";
        document.getElementById("endpage").style.display = "none";
        document.getElementById("gamepage").style.display = "block";
        document.getElementById("homeid").style.visibility = "visible";
        document.body.style.backgroundImage = Utils.path + "url('images/BG.jpg')";
        if (SentenceOrdering.practice == true)
            document.getElementById("helpBtn").style.visibility = "hidden";
        else
            document.getElementById("helpBtn").style.visibility = "visible";
        SentenceOrdering.playInstructions();
        $("#helpBtn").prop("src", Utils.path + "images/Show-Help.png");
        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() {
    var storeParaWordsArray = [],
        cnt = 0,
        checkPositionArray = [];
    SentenceOrdering.sentenceArray = [""];
    var str = SentenceOrdering.QuetionArray[SentenceOrdering.QueCounter].Paragraphs;
    label = 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;
    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();
    var sentenceNumber = 1;
    for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
        SentenceOrdering.sentenceArray[j] = sentenceNumber + ")" + SentenceOrdering.sentenceArray[j];
        SentenceOrdering.answerArray.push(SentenceOrdering.sentenceArray[j]);
        sentenceNumber++;
    }
    checkPositionArray = SentenceOrdering.sentenceArray.slice(); //used to copy the array
    shuffleArray(SentenceOrdering.sentenceArray);
    for (var i = 0; i < checkPositionArray.length; i++) {
        if (checkPositionArray[i] == SentenceOrdering.sentenceArray[i]) {
            shuffleArray(SentenceOrdering.sentenceArray);
        } else {
            break;
        }
    }
    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 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];
        var arr = word.split(")");
        for (var i = 0; i < arr.length; i++) {
            Div = document.createElement("span");
            Div.setAttribute("id", "div" + j + i);
            Div.setAttribute("class", " nopadding ");
            questionSpan.appendChild(Div);
            if (i == 0) {
                Div.style.visibility = "hidden";
                Div.innerHTML = arr[i] + ")";
            } else {
                Div.innerHTML = arr[i];
            }
            Div.setAttribute("worddata", arr[i]);
        }
    }

    function mouseOver(object) {
        document.getElementById('playSound').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
    });
    $(".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.playInstructions = function() {
        document.getElementById("playSound").pause();
        document.getElementById('playSound').src = Utils.path + "sounds/Game_Instruction.mp3";
        document.getElementById("playSound").play();
    }
    //get selected word
SentenceOrdering.getData = function(object) {
        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() {
        var checkArray = []; //used to check the answer
        scoreFlag = true;
        helpFlag = false;
        SentenceOrdering.Attempt++;
        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 
        {
            $("#playSound").prop("src", Utils.path + 'sounds/Brilent.mp3');
            document.getElementById("playSound").play();
            $("#ansImg").prop("src", Utils.path + "images/Star_correct-ANS.png");
            if (SentenceOrdering.Attempt == 1 && SentenceOrdering.helpCounter == 0) {
                scoredMarks = 10;
                SentenceOrdering.scoreFunction();
            } else if (SentenceOrdering.helpCounter == 0) {
                scoredMarks = 5;
                SentenceOrdering.scoreFunction();
            }
            if (Utils.mobileDeviceFlag) {
                Android.addLearntData(SentenceOrdering.answerArray, SentenceOrdering.data.length, "sentence");
            }
            $("#questionDiv ,#helpBtn,#checkBtn,#soundBtn").css("pointer-Events", "none");
            $("#nextDiv").addClass("blink_me");
        } else {
            if (SentenceOrdering.Attempt == 2 && SentenceOrdering.helpCounter == 0) {
                scoredMarks = 0;
                //helpFlag=false;
                //SentenceOrdering.scoreFunction ();
            }
            if (SentenceOrdering.Attempt == 1) {
                //helpFlag=true;
                $("#playSound").prop("src", Utils.path + 'sounds/Try_again.mp3');
            } else if (SentenceOrdering.Attempt == 2 && SentenceOrdering.helpCounter == 0) {
                $("#playSound").prop("src", Utils.path + 'sounds/Better_luck_next_time.mp3');
                $("#nextDiv").addClass("blink_me");
            }
            document.getElementById("playSound").play();
            $("#ansImg").prop("src", Utils.path + "images/Star_wrong-ANS.png");
            setTimeout(function() {
                $("#ansImg").prop("src", Utils.path + "images/Star.png");
            }, 2000);
        }
        if (SentenceOrdering.Attempt == 2 /* && helpFlag==false */ && SentenceOrdering.helpCounter == 0) {
            $("#questionDiv ,#checkBtn").css("pointer-Events", "none");
        }
    }
    //show the answer 
SentenceOrdering.help = function() {
        scoreFlag = true;
        helpFlag = true;
        /* if( SentenceOrdering.helpCounter==0)
        	$("#nextDiv").addClass("blink_me");
        else
        	$("#nextDiv").removeClass("blink_me"); */
        SentenceOrdering.helpCounter++;
        document.getElementById("playSound").pause();
        document.getElementById("checkBtn").style.visibility = "hidden";
        document.getElementById("soundBtn").style.visibility = "hidden";
        if (SentenceOrdering.helpClick == true) {
            $("#helpBtn").prop("src", Utils.path + "images/Hide-Help.png");
            $("#nextDiv").addClass("blink_me");
            if (SentenceOrdering.helpCounter == 1) {
                scoredMarks = 0;
                SentenceOrdering.scoreFunction();
            }
            SentenceOrdering.helpClick = false;
            $("#questionDiv").css("pointer-Events", "none");
            for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
                document.getElementById("div" + j + 0).style.visibility = "visible";
            }
        } else {
            $("#helpBtn").prop("src", Utils.path + "images/Show-Help.png");
            $("#nextDiv").removeClass("blink_me");
            SentenceOrdering.helpClick = true;
            for (var j = 0; j < SentenceOrdering.sentenceArray.length; j++) {
                document.getElementById("div" + j + 0).style.visibility = "hidden";
            }
            $("#questionDiv").css("pointer-Events", "auto");
            $("#checkBtn,#soundBtn").css("visibility", "visible");
        }
    }
    //score Function
SentenceOrdering.scoreFunction = function() {

        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        }
    }
    //used to display next question
SentenceOrdering.nextQue = function() {
        $("#helpBtn").prop("src", Utils.path + "images/Show-Help.png");
        document.getElementById("playSound").pause();
        $("#nextDiv").removeClass("blink_me");
        if (scoreFlag == false) {
            scoredMarks = -1;
            SentenceOrdering.scoreFunction();
        }
        if (helpFlag == false && SentenceOrdering.helpCounter == 0 && scoreFlag == true) {
            scoredMarks = 0;
            SentenceOrdering.scoreFunction();
        }
        scoreFlag = false;
        helpFlag = false;
        SentenceOrdering.helpClick = true;
        SentenceOrdering.helpCounter = 0;
        SentenceOrdering.Attempt = 0;
        SentenceOrdering.QueCounter++;
        SentenceOrdering.answerArray = [];
        document.getElementById("checkBtn").style.visibility = "visible";
        document.getElementById("soundBtn").style.visibility = "visible";
        $("#ansImg").prop("src", Utils.path + "images/Star.png");
        $("#questionDiv ,#helpBtn,#checkBtn,#soundBtn").css("pointer-Events", "auto");
        document.getElementById('questions').innerHTML = "";
        if (SentenceOrdering.QueCounter == 5)
            SentenceOrdering.gameOver();
        else
            SentenceOrdering.displayQuestions();
    }
    //go return back to cover page
SentenceOrdering.callHome = function() {
        if (scoreFlag == true && SentenceOrdering.Attempt == 1 && helpFlag == true) {
            SentenceOrdering.scoreFunction();
        }
        document.getElementById("playSound").pause();
        location.reload(true);
    }
    //credit 
SentenceOrdering.showCredits = function() {
        document.getElementById("acknowledgementDiv").style.display = "block";
    }
    //display game over page
SentenceOrdering.gameOver = function() {
    document.getElementById("playSound").pause();
    document.getElementById("coverpage").style.display = "none";
    document.getElementById("gamepage").style.display = "none";
    document.getElementById("endpage").style.display = "block";
    document.getElementById("acknowledgementDiv").style.display = "none";
    document.getElementById("resetbtnid").src = Utils.path + "images/Replay.png";
    document.getElementById("creditbtnid").src = Utils.path + "images/Credits.png";
    document.getElementById('acknowledgementDiv').style.backgroundImage = Utils.path + "url('images/Box.png')";
    document.getElementById("gameover").innerHTML = SentenceOrdering.hardcodedData.message;
    for (i = 0; i < Object.keys(SentenceOrdering.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "fontClass nopadding col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(SentenceOrdering.AcknowledgementPageData)[i] + " : " + Object.values(SentenceOrdering.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "fontClass col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = SentenceOrdering.hardcodedData['createdOn'];
    acknowledgementDiv.appendChild(div);
}