var GaltiMaafSci = {};
var Utils = {}
Utils.Path = "";
Utils.mobileDeviceFlag = false;
GaltiMaafSci.noOfQuestions = 5;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0;
GaltiMaafSci.queArr=[];
GaltiMaafSci.queCount=0;
GaltiMaafSci.nextQueTimer = 0;
GaltiMaafSci.correctCnt=0;
GaltiMaafSci.noResponseTimer=0
GaltiMaafSci.seconds=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 = "";
    $(".se-pre-con").fadeOut("slow");
    setTimeout(function() {
        GaltiMaafSci.setAllImages();
		GaltiMaafSci.createStars();
        //GaltiMaafSci.startGame();
    }, 200);
});

/* to set source to all images in the game*/
GaltiMaafSci.setAllImages = function() {
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'images/skin/Cover.jpg)' });
    $('#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/skip.png');
    $('#nextGame').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');
    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)' });
	$('#question').css({'visibility':'visible'});
	$('#coverPage').hide();
    $('#gamePage').show();
    for(var i=0;i<GaltiMaafSci.queArr.length;i++)
    {
        GaltiMaafSci.arrOfOptions = GaltiMaafSci.queArr[i]['options'].split(',');
        GaltiMaafSci.arrOfOptions.push(GaltiMaafSci.queArr[i]['answer']);
        GaltiMaafSci.queArr[i].options=GaltiMaafSci.arrOfOptions;
        GaltiMaafSci.queArr[i].queOption=GaltiMaafSci.arrOfOptions[(Math.floor(Math.random() * GaltiMaafSci.arrOfOptions.length))];
    }
    console.log(GaltiMaafSci.queArr);
    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;
	GaltiMaafSci.startTimer();
	$('#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.queArr[GaltiMaafSci.queCount]['queOption']);
            $(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;
    shuffle(GaltiMaafSci.queArr[GaltiMaafSci.queCount].options);
    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.queArr[GaltiMaafSci.queCount].options.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.queArr[GaltiMaafSci.queCount].options[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());
    $(element).css({'pointer-events':'none'});
	clearTimeout(GaltiMaafSci.timer);
    clearInterval(GaltiMaafSci.noResponseTimer);
    document.getElementById('playSound').pause();
};

/* called on click of check answer button to check the answer.*/
GaltiMaafSci.checkAnswer = function() {
    $('#checkAnswer,#next').css({ 'visibility': 'hidden' });
    GaltiMaafSci.gamePlayedFlag = true;
	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.correctCnt++;
    } else {
        $('#span' + GaltiMaafSci.index).css({ 'color': 'red' });
        document.getElementById('playSound').src = Utils.Path + "sound/wrongBeat.mp3";
		scoredMarks = 0;
    }
    document.getElementById('playSound').play();
    GaltiMaafSci.queArr.splice(GaltiMaafSci.queCount,1);
    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);
    clearInterval(GaltiMaafSci.noResponseTimer);
    document.getElementById('playSound').pause();
	if(!GaltiMaafSci.gamePlayedFlag)
		GaltiMaafSci.queCount++;
	else
    {
        GaltiMaafSci.addScore();
        
    }
	
    if(GaltiMaafSci.queArr.length==0)
		GaltiMaafSci.showLastPage();
	else if(GaltiMaafSci.queCount>=GaltiMaafSci.queArr.length && GaltiMaafSci.queArr.length!=0)
		GaltiMaafSci.showPopup();
	else	
	{
		GaltiMaafSci.addSentence();
	}
};
GaltiMaafSci.addScore = function () {
    if (GaltiMaafSci.gamePlayedFlag && Utils.mobileDeviceFlag)
       Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime,GaltiMaafSci.queArr[GaltiMaafSci.queCount].definition);
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime,GaltiMaafSci.queArr[GaltiMaafSci.queCount].definition);
}
/* function to call at the end of the game*/
GaltiMaafSci.showLastPage = function() {
    $('#coverPage,#gamePage,#responseBoxDiv').hide();
	GaltiMaafSci.giveStars();
	$('#question').css({'visibility':'hidden'});
    GaltiMaafSci.gamePlayedFlag = false;
    $('#gameOver').text(GaltiMaafSci.hardcodeddata['gameOver']);
    $('#endpage').show();
	clearInterval(GaltiMaafSci.noResponseTimer);
	clearTimeout(GaltiMaafSci.timeOut);
	document.getElementById('nextDiv').classList.add('blink_me');
	if(GaltiMaafSci.correctCnt>0)
	{
		document.getElementById('playSound').src="sound/instruction/star"+GaltiMaafSci.correctCnt+".mp3";
		document.getElementById('playSound').play();
	}
	if(Utils.mobileDeviceFlag)
	Android.StudentCertification(GaltiMaafSci.correctCnt,GaltiMaafSci.totalQue,"6");
}

GaltiMaafSci.showSkippedQuestions=function()
{
	$('#responseBoxDiv').hide();
	GaltiMaafSci.queCount=0;
	GaltiMaafSci.addSentence();
}

GaltiMaafSci.showPopup=function()
{
	document.getElementById('playSound').pause();
	clearInterval(GaltiMaafSci.noResponseTimer);
	clearTimeout(GaltiMaafSci.timeOut);
	GaltiMaafSci.timeOut=null;
	$('#responseBoxDiv').show();
	$('#questionMsg').text(GaltiMaafSci.modalData.responseMsg);
	$('#Yes').text(GaltiMaafSci.modalData.yes);
	$('#No').text(GaltiMaafSci.modalData.no);
}


GaltiMaafSci.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=5;
	for(i=1;i<=Math.floor(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/star5.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
};

GaltiMaafSci.giveStars=function()
{
	var fractionVar,i,numberOfStars=GaltiMaafSci.correctCnt;
	fractionVar=numberOfStars-Math.floor(numberOfStars);
	for(i=1;i<=Math.floor(numberOfStars);i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/skin/star1.png");
	$("#starDiv").css("visibility","visible");
};

GaltiMaafSci.goNext=function()
{
	clearInterval(GaltiMaafSci.noResponseTimer);
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}

GaltiMaafSci.startTimer=function()
{
	if(GaltiMaafSci.noResponseTimer)
	{
        clearInterval(GaltiMaafSci.noResponseTimer);
        GaltiMaafSci.noResponseTimer=null;
        GaltiMaafSci.seconds=0;
	}	
	GaltiMaafSci.noResponseTimer=setInterval(function() 
	{
		GaltiMaafSci.seconds++;
		if(GaltiMaafSci.seconds>=5)
		{
			document.getElementById("playSound").src=Utils.Path+"sound/instruction/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(GaltiMaafSci.noResponseTimer);
			GaltiMaafSci.timeOut=setTimeout(function()
			{
				GaltiMaafSci.seconds=0;
				GaltiMaafSci.startTimer();
			},2000);
		}
	},5000);
}