//4th May 2019
var ShowMe = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    resId = 0,
    totalMarks = 10,
    totalLength = 0,
    type = "word",
    correctCnt = 0;
ShowMe.skipedQ = 5;
ShowMe.alreadyShownLevel = []; //get unique 5 levels
ShowMe.tempArr = []; //level data
ShowMe.skipFlag = true;
ShowMe.objPointerFlag = true; //image clicked flag
ShowMe.levelNumber = 0;
ShowMe.uniqueImageArr = [];
ShowMe.mainArr = [];
queCnt = 0;
ShowMe.seconds = 0; //5 sec variable
//function for loader
$(document).ready(function() {
    $('title').text(ShowMe.gameTitle);
    $(".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;
    /* if(Utils.mobileDeviceFlag)
    	Utils.Path=Android.getMediaPath("Aksharkhadi");  */
    setTimeout(function() {
        $("#gamepage,#endpage,#homeImg").hide();
        $("#coverpage").show();
        $("#Yes").text(ShowMe.hardcoded.yes);
        $("#No").text(ShowMe.hardcoded.no);
        ShowMe.setImages();
    }, 300);
});
ShowMe.setImages = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + ShowMe.coverImage + ")";
    document.getElementById("showMePageDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/board.png)";
    $("#homeImg").prop("src", Utils.Path + "images/skin/Home.png");
    $("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
    $("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
    $("#nextImage").prop("src", Utils.Path + "images/skin/Skip.png");
    $("#nextGameImage").prop("src", Utils.Path + "images/skin/Next.png");
    $("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
    $("#credit").prop("src", Utils.Path + "images/skin/credits.png");
    $("#sound,#optionDiv1,#optionDiv2,#optionDiv3").prop('src', Utils.Path + "images/skin/Sound.png");
}
ShowMe.playGame = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
    $("#homeImg,#gamepage").show();
    $("#coverpage").hide();
    ShowMe.createDivs(showMePageDiv, "picture", "pictureClass pointerClass pointers noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3", 3);
    //$(".borderClass").css("backgroundImage", "url(images/skin/blue_pach.png)");
    for (var k = 0; k < ShowMe.data.list.length; k++)
        totalLength += ShowMe.data.list[k].data.length;
    for (var i = 0; i < 5; i++) {
        var queObj = {};
        queObj['combineQue'] = [];
        ShowMe.uniqueImageArr = [];
        ShowMe.levelNumber = Math.floor(Math.random() * ShowMe.data.list.length);
        while ($.inArray(ShowMe.levelNumber, ShowMe.alreadyShownLevel) != -1)
            ShowMe.levelNumber = Math.floor(Math.random() * ShowMe.data.list.length);
        ShowMe.alreadyShownLevel.push(ShowMe.levelNumber);

        ShowMe.tempArr = ShowMe.data.list[ShowMe.levelNumber].data.slice();
        ShowMe.uniqueImageArr = populate(ShowMe.tempArr, ShowMe.uniqueImageArr, ShowMe.hardcoded.number);
        queObj['ques'] = ShowMe.uniqueImageArr[0];
        queObj['combineQue'].push(ShowMe.uniqueImageArr[0]);
        queObj['options'] = [];
        for (var j = 0; j < 2; j++) {
            queObj['options'].push(ShowMe.uniqueImageArr[j + 1]);
            queObj['combineQue'].push(ShowMe.uniqueImageArr[j + 1]);
        }
        ShowMe.mainArr.push(queObj);
    }
    ShowMe.createStars();
    ShowMe.selectLevel();
}
ShowMe.createStars = function() {
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= numberOfStars; i++) {
        newDiv = document.createElement("div");
        newDiv.setAttribute("id", "starDiv" + i);
        newDiv.setAttribute("class", "noPadding stars col-xs-2 col-md-2 col-lg-2 col-sm-2");

        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/skin/star1.png");
        $(newDiv).append(newImage);
        $("#starDiv").append(newDiv);
    }
    $("#starDiv").css("visibility", "hidden");
};
//creates No. of Divs
ShowMe.createDivs = function(parentDiv, id, className, no) { //create Divs for level page & Main game page
    var pictureDiv, img, imgDiv, textDiv, levelNo = 1;
    for (var j = 0; j < no; j++, levelNo++) {
        pictureDiv = document.createElement("div");
        pictureDiv.setAttribute("id", id + j);
        pictureDiv.setAttribute("class", className);
        parentDiv.appendChild(pictureDiv);

        img = document.createElement('img');
        img.setAttribute("id", id + "img" + j);
        img.setAttribute("class", " borderClass img-responsive col-lg-12 col-md-12 col-xs-12 col-sm-12");
        pictureDiv.appendChild(img);
        img.setAttribute("onclick", "ShowMe.checkAnswer(this)");
    }
}
ShowMe.selectLevel = function(element) { //selects level
        ShowMe.alreadyShownObject = [];
        ShowMe.internalLevelNumber = $(element).data("internalLevel"); //sub level number
        ShowMe.tempArr = JSON.parse(JSON.stringify(ShowMe.data.list[ShowMe.levelNumber].data));
        ShowMe.showObjects();
    }
    //Show Objects on the screen
ShowMe.showObjects = function() { //display  images levelwise 
    var d;
    ShowMe.skipFlag = true;
    ShowMe.objPointerFlag = true;
    clearTimeout(ShowMe.instructionTimer);
    shuffleArray(ShowMe.mainArr[queCnt].combineQue);
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    for (var j = 0; j < 3; j++) { //display images & set data to images
        $("#pictureimg" + j).prop("src", Utils.Path + "images/" + ShowMe.mainArr[queCnt].combineQue[j].imgName);
        $("#pictureimg" + j).data("ans", ShowMe.mainArr[queCnt].combineQue[j].name);
    }
    questionId = parseInt(ShowMe.mainArr[queCnt].ques.questionId);
    ShowMe.playInstruction();
}
ShowMe.playInstruction = function() { // plays sound of instruction/options
    ShowMe.soundFlag = true;
    ShowMe.seconds = 0;
    clearTimeout(ShowMe.timeOut);
    clearInterval(ShowMe.noResponseTimer);
    $(".optionClass").css("pointer-events", "none");
    if (ShowMe.objPointerFlag)
        $(".pointerClass").css({ "pointer-events": "none" });
    getDuration(Utils.Path + 'sounds/instruction/' + ShowMe.hardcoded.instruction);
}

function getDuration(src) {
    var duration = 0;
    if (ShowMe.soundFlag) {
        $('#playSound').on("loadedmetadata", function() {
            ShowMe.soundFlag = false;
            duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
            ShowMe.playNextSound(duration);
        });
        $('#playSound').prop('src', src);
    }
}
ShowMe.playNextSound = function(duration) //function for instruction
    {
        $(".optionClass").css("pointer-events", "auto");
        document.getElementById('playSound').play();
        if (ShowMe.instructionTimer) {
            clearTimeout(ShowMe.instructionTimer);
            ShowMe.instructionTimer = null;
        }
        ShowMe.instructionTimer = setTimeout(function() {
            document.getElementById('playSound').pause();
            document.getElementById('playSound').src = Utils.Path + 'sounds/' + ShowMe.mainArr[queCnt].ques.sound;
            document.getElementById('playSound').play();
            setTimeout(function() {
                if (ShowMe.objPointerFlag) {
                    ShowMe.objPointerFlag = false;
                    $(".pointerClass").css({ "pointer-events": "auto" });
                }
            }, duration * 800);
            ShowMe.startTimer();
        }, duration * 1000);
    }
ShowMe.startTimer = function() {
    clearTimeout(ShowMe.instructionTimer);
    $("#nextImage").css({ "pointer-events": "auto" });
    if (ShowMe.noResponseTimer) {
        clearInterval(ShowMe.noResponseTimer);
        ShowMe.noResponseTimer = null;
        ShowMe.seconds = 0;
    }
    ShowMe.noResponseTimer = setInterval(function() {
        ShowMe.seconds++;
        if (ShowMe.seconds >= 7) {
            clearTimeout(ShowMe.soundTimer);
            ShowMe.soundTimer = null;
            document.getElementById("playSound").src = Utils.Path + "sounds/instruction/" + ShowMe.hardcoded.noResponce;
            document.getElementById("playSound").play();
            $(".pointerClass").css("pointer-events", "auto");
            clearInterval(ShowMe.noResponseTimer)
            if (ShowMe.timeOut) {
                clearTimeout(ShowMe.timeOut);
                ShowMe.timeOut = null;
            }
            ShowMe.timeOut = setTimeout(function() {
                ShowMe.seconds = 0;
                ShowMe.startTimer();
            }, 2000);
        }
    }, 1000);
}
ShowMe.checkAnswer = function(element) { //Check Answer
    var randomSound;
    ShowMe.skipFlag = false;
    clearTimeout(ShowMe.instructionTimer);
    clearInterval(ShowMe.noResponseTimer);
    $(".pointerClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
    if ($(element).data('ans') == ShowMe.mainArr[queCnt].ques.name) {
        scoredMarks = 10;
        correctCnt++;
        $(element).addClass("animated zoomIn");
        randomSound = Math.floor(Math.random() * (ShowMe.correctAns.length));
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + ShowMe.correctAns[randomSound];
        document.getElementById('playSound').play();
        if (ShowMe.nextQ) {
            clearTimeout(ShowMe.nextQ);
            ShowMe.nextQ = null;
        }

        console.log(ShowMe.mainArr[queCnt].ques.name, totalLength, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(ShowMe.mainArr[queCnt].ques.name, totalLength, type);
    } else {
        scoredMarks = 0;
        $(element).addClass("animated shake");
        $(element).parent().css({ "opacity": "0.5" });
        randomSound = Math.floor(Math.random() * (ShowMe.wrongAns.length));
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + ShowMe.wrongAns[randomSound];
        document.getElementById('playSound').play();
        setTimeout(function() {
            $(element).removeClass("animated shake");
        }, 1500);
    }

    ShowMe.calculateScore();
    ShowMe.mainArr.splice(queCnt, 1);
    ShowMe.nextQ = setTimeout(function() {
        ShowMe.nextQuestion();
        $(element).removeClass("animated zoomIn");
    }, 3000);
}
ShowMe.nextQuestion = function() { //Loads Next Question
    if (ShowMe.skipFlag)
        queCnt++;
    $(".borderClass").removeClass("animated zoomIn animated shake");
    clearTimeout(ShowMe.nextQ);
    clearTimeout(ShowMe.instructionTimer);
    clearInterval(ShowMe.noResponseTimer);
    clearTimeout(ShowMe.timeOut);
    document.getElementById('playSound').pause();
    $(".pointerClass").css({ "pointer-events": "auto", "opacity": "1" });
    if (ShowMe.mainArr.length == 0)
        ShowMe.lastPage();
    else if (queCnt == ShowMe.mainArr.length) {
        $('#responseBoxDiv').show();
        $('#questionMsg').text(ShowMe.hardcoded.message);
    } else
        ShowMe.showObjects();
}
ShowMe.showNext = function(element) {
    if ($(element).text() == ShowMe.hardcoded.no)
        ShowMe.lastPage();
    else
        ShowMe.showRemaining();
}
ShowMe.lastPage = function() {
    clearTimeout(ShowMe.instructionTimer);
    clearInterval(ShowMe.noResponseTimer);
    clearTimeout(ShowMe.nextQ);
    document.getElementById('playSound').pause();
    $('#endpage').show();
    $('#responseBoxDiv,#gamepage').hide();
    $("#gameOverDiv").text(ShowMe.hardcoded.gameOver);
    ShowMe.giveStars();
    console.log(correctCnt, ShowMe.skipedQ);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(correctCnt, ShowMe.skipedQ, "7");
}
ShowMe.giveStars = function() {
    var i, numberOfStars = correctCnt;
    for (i = 1; i <= numberOfStars; i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
    $("#starDiv").css("visibility", "visible");
    if (correctCnt != 0) {
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + 'Star' + correctCnt + '.mp3';
        document.getElementById('playSound').play();
    }
};
ShowMe.showRemaining = function() {
    queCnt = 0;
    $('#responseBoxDiv').hide();
    $('#gamepage').show();
    $("#soundDiv").css("visibility", "visible");
    ShowMe.showObjects();
}
ShowMe.calculateScore = function() {
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, ShowMe.mainArr[queCnt].ques.name);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, ShowMe.mainArr[queCnt].ques.name);
}
ShowMe.nextGame = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}