var GaltiMaafSci = {};
var Utils = {}
Utils.Path = "";
Utils.mobileDeviceFlag = false;
GaltiMaafSci.levelOfData = 0;
GaltiMaafSci.noOfQuestions = 5;
GaltiMaafSci.questionData = [], GaltiMaafSci.skippedQuestionArr = [], GaltiMaafSci.questionCounter = 0, GaltiMaafSci.totalAttempted = 9;
GaltiMaafSci.correctAnsCnt = 0;
GaltiMaafSci.wrongAnsCnt = 0, GaltiMaafSci.skippedCnt = 0, GaltiMaafSci.limit = 9;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0;
GaltiMaafSci.showAllData = 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;
    // if(Utils.mobileDeviceFlag)
    // {
    // 	Utils.Path=Android.getMediaPath('GaltimaafSudharoScience');
    // 	GaltiMaafSci.levelOfData=Android.getLevel();
    // 	if(GaltiMaafSci.levelOfData==null)
    // 		GaltiMaafSci.showAllData=true;
    // }	
    // else
    // {

    // }
    Utils.Path = "";
    GaltiMaafSci.levelOfData = Math.floor(Math.random() * GaltiMaafSci.jsonData.length);

    $(".se-pre-con").fadeOut("slow");
    $('#home').css({ 'visibility': 'hidden' });
    setTimeout(function() {
        GaltiMaafSci.setAllImages();
        //GaltiMaafSci.startGame();
    }, 200);
});

/* to set source to all images in the game*/
GaltiMaafSci.setAllImages = function() {
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'Images/Cover.jpg)' });
    $('#playGame').prop('src', Utils.Path + 'Images/Play.png');
    $('#checkAnswer').prop('src', Utils.Path + 'Images/Done.png');
    $('#logo').prop('src', Utils.Path + 'Images/logo.png');
    $('#skip').prop('src', Utils.Path + 'Images/skip.png');
    $('#logo').prop('src', Utils.Path + 'Images/logo.png');
    $('#home').prop('src', Utils.Path + 'Images/Home.png');
    $('#playAgain').prop('src', Utils.Path + 'Images/Home.png');
    GaltiMaafSci.score = 0, GaltiMaafSci.noOfCorrectAns = 0;
    $('#coverPage').show();
    $('#gamePage,#lastPage').hide();
    $('#instruction').text(GaltiMaafSci.hardcodeddata.instruction);
};

/* to initialize variables*/
GaltiMaafSci.initializeVariables = function() {
    GaltiMaafSci.arrOfOptions = [], GaltiMaafSci.index = 0, GaltiMaafSci.answerClicked = false;
    GaltiMaafSci.startIndex = 0, GaltiMaafSci.noOfSpans = 0;
    $('#questionMsg').text(GaltiMaafSci.hardcodeddata.responseMsg);
    $('#Yes').text(GaltiMaafSci.hardcodeddata.yes);
    $('#No').text(GaltiMaafSci.hardcodeddata.no);
};


/* called on click of play button*/
GaltiMaafSci.startGame = function() {
    var counter = 0,
        tempArr = [],
        level = 0;
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'Images/BG.jpg)' });
    // add any 8 questions at a time
    if (GaltiMaafSci.showAllData == true) {
        for (var i = 0; i < GaltiMaafSci.totalAttempted; i++) {
            level = Math.floor(Math.random() * GaltiMaafSci.jsonData.length);
            counter = Math.floor(Math.random() * GaltiMaafSci.jsonData[level]['level'].length);
            while ($.inArray(GaltiMaafSci.jsonData[level]['level'][counter], tempArr) >= 0) {
                counter = Math.floor(Math.random() * GaltiMaafSci.jsonData[level]['level'].length);
            }
            tempArr.push(GaltiMaafSci.jsonData[level]['level'][counter]);
        }
        shuffleWords(tempArr);
        for (var i = 0; i < tempArr.length; i++) {
            GaltiMaafSci.questionData.push(tempArr[i]);
        }
    } else {
        for (var i = 0; i < GaltiMaafSci.totalAttempted; i++) {
            counter = Math.floor(Math.random() * GaltiMaafSci.jsonData[GaltiMaafSci.levelOfData]['level'].length);
            while ($.inArray(GaltiMaafSci.jsonData[GaltiMaafSci.levelOfData]['level'][counter], tempArr) >= 0) {
                counter = Math.floor(Math.random() * GaltiMaafSci.jsonData[GaltiMaafSci.levelOfData]['level'].length);
            }
            tempArr.push(counter);
        }
        for (var i = 0; i < tempArr.length; i++) {
            GaltiMaafSci.questionData.push(GaltiMaafSci.jsonData[GaltiMaafSci.levelOfData]['level'][tempArr[i]]);
        }
    }
    $('#coverPage').hide();
    $('#gamePage').show();
    GaltiMaafSci.addSentence();

};

function shuffleWords(array) {
    var i = 0,
        j = 0,
        temp = 0;
    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;
    }
};

/*to get an index of answer in the sentence.*/
GaltiMaafSci.getIndex = function(arr, counter) {
    var splitedAnswr = [],
        j = 0,
        i = 0;
    GaltiMaafSci.startIndex = 0, GaltiMaafSci.noOfSpans = 0;
    console.log(GaltiMaafSci.questionData[counter]['answer']);
    GaltiMaafSci.questionData[counter]['answer'] = GaltiMaafSci.questionData[counter]['answer'].trim();
    splitedAnswr = GaltiMaafSci.questionData[counter]['answer'].split(' ');
    if (splitedAnswr.length > 1) {
        while (i < splitedAnswr.length) {
            while (j < arr.length) {
                if (splitedAnswr[i] == arr[j]) {
                    if (GaltiMaafSci.noOfSpans == 0)
                        GaltiMaafSci.startIndex = j;
                    GaltiMaafSci.noOfSpans++;
                    break;
                }
                j++;
            }
            i++;
        }
    } else
        GaltiMaafSci.noOfSpans = 1;
};

/*add sentence to the screen and color the given answer*/
GaltiMaafSci.addSentence = function() {
    var arr = [],
        tempWord;
    GaltiMaafSci.limit--;
    $('#skip,#checkAnswer').css({ 'visibility': 'visible' });

    GaltiMaafSci.initializeVariables();
    arr = GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]['definition'].split(' ');
    GaltiMaafSci.getIndex(arr, GaltiMaafSci.questionCounter);

    tempWord = arr.slice(GaltiMaafSci.startIndex, GaltiMaafSci.startIndex + GaltiMaafSci.noOfSpans);
    tempWord = tempWord.join(' ');
    arr.splice(GaltiMaafSci.startIndex, GaltiMaafSci.noOfSpans);
    arr.splice(GaltiMaafSci.startIndex, 0, tempWord);

    GaltiMaafSci.index = $.inArray(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]['answer'], arr);

    GaltiMaafSci.arrOfOptions = GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]['options'].split(',');
    GaltiMaafSci.arrOfOptions.push(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]['answer']);
    shuffleWords(GaltiMaafSci.arrOfOptions);
    questionId = GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]['questionId'];
    for (var i = 0; i < arr.length; i++) {
        var span = $('<span id="span' + i + '" style="display:inline-block" class="spans">' + arr[i].trim() + '</span>');
        if (GaltiMaafSci.index == i) {
            $(span).css({ 'color': 'rgb(139, 4, 102)', 'font-weight': 'bolder' });
            $(span).text(GaltiMaafSci.arrOfOptions[(Math.floor(Math.random() * GaltiMaafSci.arrOfOptions.length))]);
            $(span).data('answer', GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]['answer'].trim());
            $(span).on('click', function() {
                GaltiMaafSci.addOptions(this);
            });
        }
        $('#sentence').append(span);
    }
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
};

/* add options to the box*/
GaltiMaafSci.addOptions = function(element) {
    var div, outerDiv, k = 0;
    shuffleWords(GaltiMaafSci.arrOfOptions);
    if (!GaltiMaafSci.answerClicked) {
        for (var i = 0; i < 2; i++) {
            outerDiv = $('<div class="text-center noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12" ></div>');
            for (var j = 0; j < 2; j++) {
                if (k < GaltiMaafSci.arrOfOptions.length) {
                    div = $('<div class="text-center noPadding col-md-6 col-xs-6 col-lg-6 col-sm-6" style="padding:0px !important;display:inline;"><div id="option' + k + '" style="display:inline-block;word-wrap:break-word;" class="options text-center col-md-10 col-xs-10 col-lg-10 col-sm-10 col-lg-offset-1 col-md-offset-1 col-xs-offset-1 col-sm-offset-1">' + GaltiMaafSci.arrOfOptions[k].trim() + '</div></div>');
                    $(div).on('click', function() {
                        GaltiMaafSci.changeText(this, element);
                    });
                    $(outerDiv).append(div);
                    k++;
                }
            }
            $('#wrongWordsDiv').append(outerDiv);
        }
        $('#myModal').show();
    }
};

GaltiMaafSci.modalClicked = function() {
    $('#myModal').hide();
    $('#wrongWordsDiv').empty();
};


/* called on click of option in the option box to change the text in sentence*/
GaltiMaafSci.changeText = function(spanElement, element) {
    $(element).text($(spanElement).text());
};

/* called on click of check answer button to check the answer.*/
GaltiMaafSci.checkAnswer = function() {
    if ($.inArray(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter], GaltiMaafSci.skippedQuestionArr) >= 0)
        GaltiMaafSci.skippedQuestionArr.splice($.inArray(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter], GaltiMaafSci.skippedQuestionArr), 1);
    $('#checkAnswer,#skip').css({ 'visibility': 'hidden' });
    GaltiMaafSci.answerClicked = true;
    if ($('#span' + GaltiMaafSci.index).text() == $('#span' + GaltiMaafSci.index).data('answer')) {
        $('#span' + GaltiMaafSci.index).css({ 'color': 'green' });
        document.getElementById('playSound').src = Utils.Path + "sound/ting.mp3";
        scoredMarks = 10;
        GaltiMaafSci.correctAnsCnt++;
    } else {
        $('#span' + GaltiMaafSci.index).css({ 'color': 'red' });
        document.getElementById('playSound').src = Utils.Path + "sound/wrongBeat.mp3";
        GaltiMaafSci.wrongAnsCnt++;
    }
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
    else
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);

    document.getElementById('playSound').play();
    console.log(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]);
    GaltiMaafSci.noOfQuestions--;
    if (GaltiMaafSci.timer) {
        GaltiMaafSci.timer = null;
        clearTimeout(GaltiMaafSci.timer);
    }
    GaltiMaafSci.timer = setTimeout(function() {
        GaltiMaafSci.questionCounter++;
        GaltiMaafSci.nextQuestion();
    }, 2000);
};

/* show next question after check answer is clicked / skip button clicked. */
GaltiMaafSci.nextQuestion = function() {
    if (GaltiMaafSci.limit > 0) {
        if (GaltiMaafSci.noOfQuestions > 0) {
            $('#sentence,#wrongWordsDiv').empty();
            GaltiMaafSci.addSentence();
        } else {
            GaltiMaafSci.showLastPage();
        }
    } else {
        $('#responseBoxDiv').show();
    }
};

/* function to call at the end of the game*/
GaltiMaafSci.showLastPage = function() {
    $('#coverPage,#gamePage,#responseBoxDiv,#scoreBoard').hide();
    $('#lastPage,#msgDiv').show();
    $('#gamePage').empty();
    grade((GaltiMaafSci.correctAnsCnt + GaltiMaafSci.wrongAnsCnt), GaltiMaafSci.skippedQuestionArr.length, 'msgImg', 'msgText');

}

/* on home button clicked*/
GaltiMaafSci.returnHome = function() {
    location.reload(true);
};


/* on skip button clicked. */
GaltiMaafSci.skipQuestion = function() {
    clearTimeout(GaltiMaafSci.timer);
    if (!GaltiMaafSci.answerClicked) {

        if ($.inArray(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter], GaltiMaafSci.skippedQuestionArr) == -1)
            GaltiMaafSci.skippedQuestionArr.push(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]);
        if (GaltiMaafSci.limit > 0) {
            GaltiMaafSci.questionData.push(GaltiMaafSci.questionData[GaltiMaafSci.questionCounter]);
            GaltiMaafSci.questionData.splice(GaltiMaafSci.questionCounter, 1);
            GaltiMaafSci.nextQuestion();
        } else {
            $('#responseBoxDiv').show();
        }
    }
};

GaltiMaafSci.showSkippedQuestions = function() {
    $('#responseBoxDiv').hide();
    GaltiMaafSci.limit = GaltiMaafSci.questionData.length - GaltiMaafSci.questionCounter;
    GaltiMaafSci.nextQuestion();
};