var GaltiMaafSci = {};
var Utils = {}
Utils.Path = "";
Utils.mobileDeviceFlag = false;
GaltiMaafSci.levelOfData = 0;
GaltiMaafSci.noOfQuestions = 5;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0;
GaltiMaafSci.queArr=[];
GaltiMaafSci.queCount=0;

$(document).ready(function() {
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
        Utils.mobileDeviceFlag = true;
    Utils.Path = "";
    GaltiMaafSci.levelOfData = Math.floor(Math.random() * GaltiMaafSci.jsonData.length);

    $(".se-pre-con").fadeOut("slow");
    setTimeout(function() {
        GaltiMaafSci.setAllImages();
		GaltiMaafSci.AcknowledgementPage();
        //GaltiMaafSci.startGame();
    }, 200);
});

/* to set source to all images in the game*/
GaltiMaafSci.setAllImages = function() {
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'images/skin/Cover.png)' });
    $('#playImage').prop('src', Utils.Path + 'images/skin/Play.png');
    $('#checkAnswer').prop('src', Utils.Path + 'images/skin/Done.png');
    $('#logo').prop('src', Utils.Path + 'images/skin/logo.png');
    $('#next').prop('src', Utils.Path + 'images/skin/Next.png');
    $('#logo').prop('src', Utils.Path + 'images/skin/logo.png');
    $('#home').prop('src', Utils.Path + 'images/skin/Home.png');
    $('#playAgain').prop('src', Utils.Path + 'images/skin/playAgain.png');
	$('#credit').prop('src',Utils.Path + 'images/skin/Credits.png');
    GaltiMaafSci.score = 0, GaltiMaafSci.noOfCorrectAns = 0;
    $('#coverPage').show();
    $('#gamePage,#lastPage').hide();
    $('#instruction').text(GaltiMaafSci.hardcodeddata.instruction);
	getUniqueValArr(GaltiMaafSci.jsonData[0].level,GaltiMaafSci.queArr,5);
	console.log(GaltiMaafSci.queArr);
};

/* to initialize variables*/
GaltiMaafSci.initializeVariables = function() {
    GaltiMaafSci.arrOfOptions = [], GaltiMaafSci.index = 0, GaltiMaafSci.answerClicked = false;
    GaltiMaafSci.startIndex = 0, GaltiMaafSci.noOfSpans = 0,GaltiMaafSci.gamePlayedFlag=false;
};


/* called on click of play button*/
GaltiMaafSci.startGame = function() {
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'images/skin/BG.jpg)' });
	$('#homeDiv,#question').css({'visibility':'visible'});
	$('#coverPage').hide();
    $('#gamePage').show();
    GaltiMaafSci.addSentence();
};



/*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.queArr[GaltiMaafSci.queCount]['answer']);
    GaltiMaafSci.queArr[GaltiMaafSci.queCount]['answer'] = GaltiMaafSci.queArr[GaltiMaafSci.queCount]['answer'].trim();
    splitedAnswr = GaltiMaafSci.queArr[GaltiMaafSci.queCount]['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;
    var d = new Date();
	GaltiMaafSci.gamePlayedFlag=false;
	$('#sentence').empty();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    $('#next,#checkAnswer').css({ 'visibility': 'visible' });

    GaltiMaafSci.initializeVariables();
    arr = GaltiMaafSci.queArr[GaltiMaafSci.queCount]['definition'].split(' ');
    GaltiMaafSci.getIndex(arr, GaltiMaafSci.queCount);

    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.queArr[GaltiMaafSci.queCount]['answer'], arr);

    GaltiMaafSci.arrOfOptions = GaltiMaafSci.queArr[GaltiMaafSci.queCount]['options'].split(',');
    GaltiMaafSci.arrOfOptions.push(GaltiMaafSci.queArr[GaltiMaafSci.queCount]['answer']);
    shuffle(GaltiMaafSci.arrOfOptions);
    questionId = GaltiMaafSci.queArr[GaltiMaafSci.queCount].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.queArr[GaltiMaafSci.queCount]['answer'].trim());
            $(span).on('click', function() {
                GaltiMaafSci.addOptions(this);
            });
        }
        $('#sentence').append(span);
    }
   
};

/* 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) {
	GaltiMaafSci.gamePlayedFlag = true;
    $(element).text($(spanElement).text());
};

/* called on click of check answer button to check the answer.*/
GaltiMaafSci.checkAnswer = function() {
    $('#checkAnswer,#next').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;
    } else {
        $('#span' + GaltiMaafSci.index).css({ 'color': 'red' });
        document.getElementById('playSound').src = Utils.Path + "sound/wrongBeat.mp3";
		scoredMarks = 0;
    }
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
    else
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);

    document.getElementById('playSound').play();
    if (GaltiMaafSci.timer) {
        GaltiMaafSci.timer = null;
        clearTimeout(GaltiMaafSci.timer);
    }
    GaltiMaafSci.timer = setTimeout(function() {
        GaltiMaafSci.nextQuestion();
    }, 2000);
};

/* show next question after check answer is clicked / skip button clicked. */
GaltiMaafSci.nextQuestion = function() {
	clearTimeout(GaltiMaafSci.timer);
	document.getElementById('playSound').pause();
	GaltiMaafSci.queCount++;
	if(!GaltiMaafSci.gamePlayedFlag && Utils.mobileDeviceFlag)
	{
		scoredMarks=-1;
		Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime,GaltiMaafSci.queArr[GaltiMaafSci.queCount].definition);
	}
	
    if (GaltiMaafSci.queCount < 5)  {
            $('#sentence,#wrongWordsDiv').empty();
            GaltiMaafSci.addSentence();
        }
		else {
            GaltiMaafSci.showLastPage();
        }
    
};

/* function to call at the end of the game*/
GaltiMaafSci.showLastPage = function() {
    $('#coverPage,#gamePage').hide();
    $('#lastPage,#msgDiv').show();
	$('#question').css({'visibility':'hidden'});
    GaltiMaafSci.gamePlayedFlag = false;
    $('#gameOver').text(GaltiMaafSci.hardcodeddata['gameOver']);
    $('#gamePage').hide();
    $('.scorePage').hide();
    $('#endpage').show();
}
GaltiMaafSci.playAgain = function () {
    GaltiMaafSci.queArr = [];
    GaltiMaafSci.queCount = 0;
    GaltiMaafSci.count = 0;
    $('#question').css('visibility', 'visible');
    $('#gamePage').show();
    $("#acknowledgementDiv").css('visibility', 'hidden');
    $('#endpage').hide();
	getUniqueValArr(GaltiMaafSci.jsonData[0].level,GaltiMaafSci.queArr,5);
	GaltiMaafSci.addSentence();
}

/* on home button clicked*/
GaltiMaafSci.returnHome = function() {
	if(GaltiMaafSci.gamePlayedFlag && Utils.mobileDeviceFlag)
	{
		GaltiMaafSci.gamePlayedFlag=false;
		Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime,GaltiMaafSci.queArr[GaltiMaafSci.queCount].definition);
	}
    location.reload(true);
};

GaltiMaafSci.AcknowledgementPage = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(GaltiMaafSci.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(GaltiMaafSci.AcknowledgementPageData)[i] + " : " + Object.values(GaltiMaafSci.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = GaltiMaafSci.hardcodeddata['createdOn'];
    acknowledgementDiv.appendChild(div);
}

GaltiMaafSci.showCredits = function () {
    $("#acknowledgementDiv").css('visibility', 'visible');
}