var AksharKhadi = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0,
    label = "",
    level = 1;
var scoreFlag = false;
var word = "",
    totalNos = 0,
    type = "letter";
AksharKhadi.queCnt = 0;
AksharKhadi.nextSound = 0;
AksharKhadi.ansClicked = false;
AksharKhadi.seconds = 0;
AksharKhadi.total_No_of_Questions = 5;
AksharKhadi.correctCounter = 0;

$(document).ready(function() {
    $(".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() {
        AksharKhadi.setAllImages();
        AksharKhadi.init();
    }, 200);
});

AksharKhadi.setAllImages = function() {
    $('#playGame').prop('src', Utils.Path + 'Images/Aksharkhadi_Play.png');
    $('#creditbtn').prop('src', Utils.Path + 'Images/Aksharkhadi_Next.png');
    $('#speaker').prop('src', Utils.Path + 'Images/Aksharkhadi_Sound.png');
    $('#next').prop('src', Utils.Path + 'Images/Skip_AKSHARKHADI.png');
    $('#logo').prop('src', Utils.Path + 'Images/logo.png');
    $('#wrongimg1').prop('src', Utils.Path + 'Images/Wrong_02.png');
    $('#wrongimg2').prop('src', Utils.Path + 'Images/Wrong_01.png');
    $('#wrongImg').prop('src', Utils.Path + 'Images/joker.png');
    $('#playAgain').prop('src', Utils.Path + 'Images/Aksharkhadi_Play-Again.png');
};

AksharKhadi.init = function() {
     document.title = AksharKhadi.hardCodedData.title;
    $('#playGame').text(AksharKhadi.hardCodeddata.play);
    $('#Flip,#title').hide();
    $('#coverPage').show();
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'Images/' + AksharKhadi.hardCodeddata['coverPage'] + ')' });
    $("#mainGamePage,#finalPage").hide();
};

AksharKhadi.getGameDataAfterTimeOut = function() {
    $("#mainGamePage").show();
    document.getElementById('playSound').src = Utils.Path + 'sounds/ting.mp3';
    document.getElementById('playSound').play();
    AksharKhadi.getGameData();
    setTimeout(function() {
        AksharKhadi.showQuestions();
    }, 1000);
}

AksharKhadi.getGameData = function() {
    AksharKhadi.gameOpened = false;
    scoredMarks = 0;
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'Images/' + AksharKhadi.hardCodeddata['BG'] + ')' });
    $('#Flip').show();
    $('#coverPage').hide();
    $('#next,#homeDiv,#home,#speaker').show();
    $('#wrongimg1,#wrongimg2').hide();
    var randomIndex = 0,
        tempArray = [];
    AksharKhadi.counter = 0, AksharKhadi.correctAnswerCount = 0;

    $('.slide').addClass('clickable');
    $('.optionForFlip').css({ 'display': 'block' });
    $('.clickable').css({ 'pointer-events': 'none' });
    $('.defaultImage').removeClass('flipIt');
    $('#lastGamePage,#divContainingFullImage').hide();
    $('#soundDiv,#homeDiv,#divContainingSplitImages').fadeIn('slow');

    AksharKhadi.arrOfSelectedWords = [];
    AksharKhadi.fiveQueArray = [];
    AksharKhadi.arrOfSelectedWords = populate(AksharKhadi.wordsData, AksharKhadi.arrOfSelectedWords, 9);
    AksharKhadi.fiveQueArray = populate(AksharKhadi.arrOfSelectedWords, AksharKhadi.fiveQueArray, 5);
    AksharKhadi.arrOfSelectedWords = shuffleArray(AksharKhadi.arrOfSelectedWords);
    AksharKhadi.tempArray = AksharKhadi.arrOfSelectedWords.slice();

    console.log(AksharKhadi.arrOfSelectedWords);
    console.log(AksharKhadi.fiveQueArray);
    AksharKhadi.fillGrid();
}

function populate(array1, array2, length) {
    var randomIndex;
    while (array2.length !== length) {
        randomIndex = Math.floor(Math.random() * array1.length);
        if ($.inArray(array1[randomIndex], array2) === -1)
            array2.push(array1[randomIndex]);
    }
    return array2;
}

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;
}

AksharKhadi.playSoundAgain = function() {
    clearInterval(AksharKhadi.noResponseTimer);
    clearTimeout(AksharKhadi.nextQueTimer);
    clearTimeout(AksharKhadi.nextQuestionTimer);
    AksharKhadi.startTimer();
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + AksharKhadi.fiveQueArray[AksharKhadi.queCnt]['sound'];
    document.getElementById('playSound').play();
};

AksharKhadi.showQuestions = function() {
    scoreFlag = false;
    AksharKhadi.ansClicked = false;
    clearInterval(AksharKhadi.noResponseTimer);
    clearTimeout(AksharKhadi.nextQueTimer);
    clearTimeout(AksharKhadi.nextQuestionTimer);
    AksharKhadi.startTimer();
    questionId = AksharKhadi.fiveQueArray[AksharKhadi.queCnt].questionId;
    word = label = AksharKhadi.fiveQueArray[AksharKhadi.queCnt].word;
    totalNos = AksharKhadi.wordsData.length;
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + AksharKhadi.fiveQueArray[AksharKhadi.queCnt]['sound'];
    $('#title').data('question', AksharKhadi.fiveQueArray[AksharKhadi.queCnt]['word'].trim());
    AksharKhadi.fiveQueArray[AksharKhadi.queCnt]['questionId'];
    document.getElementById('playSound').play();
    $('.clickable').css({ 'pointer-events': 'auto' });
}

AksharKhadi.fillGrid = function() {
    var i = 1,
        imagePath;
    AksharKhadi.randomQuestion = 0;
    //AksharKhadi.randomImg=Math.floor(Math.random()*AksharKhadi.imageSet.length);
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    for (var j = 1; j < 4; j++) {
        for (var k = 0; k < 3; k++) {
            $('#imgDiv' + (i - 1)).data('answer', AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['word'].trim());
            //imagePath=Utils.Path+''+AksharKhadi.imageSet[AksharKhadi.randomImg]['img'];
            /* $('#imgDiv'+(i-1)).data('backImg',imagePath+''+i+''+AksharKhadi.imageSet[AksharKhadi.randomImg]['type']); */
            $('#imgDiv' + (i - 1)).data('frontImg', Utils.Path + '' + AksharKhadi.frontimageSet['img'] + '' + i + '' + AksharKhadi.frontimageSet['type']);

            $('#option' + (i - 1)).text(AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['word'].trim());
            $('#img' + j + '_' + k).hide();

            i++;
            AksharKhadi.randomQuestion++;
            //	AksharKhadi.mainArray[i].splice(AksharKhadi.randomQuestion,1);
        }
    }
}

AksharKhadi.checkAns = function(evt) {
    clearInterval(AksharKhadi.noResponseTimer);
    clearTimeout(AksharKhadi.nextQueTimer);
    clearTimeout(AksharKhadi.nextQuestionTimer);
    var source, frontImg;
    AksharKhadi.ansClicked = true;
    AksharKhadi.gameOpened = true;
    AksharKhadi.counter++;
    scoreFlag = true;
    $('.clickable').css({ 'pointer-events': 'none' });
    wrongImgArray = ['backWrong1.png', 'backWrong2.png'];
    if ($('#' + evt).data('answer') == $('#title').data('question')) {
        console.log(word, totalNos, type);
        if (Utils.mobileDeviceFlag) {
            Android.addLearntData(word, totalNos, type);
        }
        AksharKhadi.correctCounter++;
        $('#' + evt).find('img').show();
        $('#' + evt).find('p').hide();
        $('#' + evt).removeClass('clickable');
        source = $('#' + evt).data('backImg');
        frontImg = $('#' + evt).data('frontImg');
        $('#' + evt).find('img').prop('src', frontImg);
        document.getElementById('playSound').src = Utils.Path + 'sounds/CorrectAksharkhadi.mp3';
        document.getElementById('playSound').play();
        scoredMarks = 10;
        AksharKhadi.scoreFunction();
    } else {
        $('#' + evt).addClass("shake");
        randomImg = Math.floor(Math.random() * wrongImgArray.length);
        $('#wrongimg1,#wrongimg2').show();
        document.getElementById('playSound').src = Utils.Path + 'sounds/wrongSoundAksharkhadi.mp3';
        document.getElementById('playSound').play();
        for (var i = 0; i < 9; i++) {
            if ($('#title').data('question') == $('#imgDiv' + i).data('answer')) {
                $('#imgDiv' + i).css({ "pointer-event": "none" });
                $('#imgDiv' + i).removeClass("clickable");
                var offsetOfImage = $('#imgDiv' + i).offset();
                break;
            }
        }
        $('#imgDiv' + i).find('img').prop('src', Utils.Path + 'Images/' + wrongImgArray[randomImg]);
        $('#imgDiv' + i).find('img').show();
        $('#imgDiv' + i).find('p').hide();
        scoredMarks = 0;
        AksharKhadi.scoreFunction();
    }
    AksharKhadi.fiveQueArray.splice(AksharKhadi.queCnt, 1);
    console.log(AksharKhadi.fiveQueArray);
    AksharKhadi.tempArray.splice(AksharKhadi.randomQuestion, 1);
    if (AksharKhadi.nextQuestionTimer) {
        clearTimeout(AksharKhadi.nextQuestionTimer);
        AksharKhadi.nextQuestionTimer = null;
    }
    AksharKhadi.nextQuestionTimer = setTimeout(function() {
        AksharKhadi.showNextQuestion();
        AksharKhadi.gameOpened = false;

    }, 2000);
}


AksharKhadi.scoreFunction = function() //score Function
    {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
        }
    }

AksharKhadi.showNextQuestion = function() {
    clearInterval(AksharKhadi.noResponseTimer);
    clearTimeout(AksharKhadi.nextQueTimer);
    clearTimeout(AksharKhadi.nextQuestionTimer);
    if (scoreFlag != true) {
        AksharKhadi.queCnt++;
    }
    if (AksharKhadi.fiveQueArray.length == 0) {

        document.getElementById("mainGamePage").style.display = "none";
        AksharKhadi.gameOver();
    } else if (AksharKhadi.queCnt == AksharKhadi.fiveQueArray.length) {
        clearInterval(AksharKhadi.noResponseTimer);
        document.getElementById("responseBoxDiv").style.display = "block";
        document.getElementById("No").innerHTML = AksharKhadi.modalData.no;
        document.getElementById("Yes").innerHTML = AksharKhadi.modalData.yes;
        document.getElementById("confiramtionText").innerHTML = AksharKhadi.modalData.responseMsg;
    } else {
        AksharKhadi.showQuestions();
    }
}

/* assessement stars*/
//display game over msg after solve all questions
AksharKhadi.gameOver = function() {
    clearInterval(AksharKhadi.noResponseTimer);
    clearTimeout(AksharKhadi.nextQueTimer);
    clearTimeout(AksharKhadi.nextQuestionTimer);
    document.getElementById("acknowledgementDiv").innerHTML = "";
    document.getElementById("mainGamePage").style.display = "none";
    document.getElementById("finalPage").style.display = "block";
    document.getElementById('gameOver').innerHTML = AksharKhadi.hardCodedData.gameOver;
    document.getElementById("responseBoxDiv").style.display = "none";

    for (var i = 0; i < Object.keys(AksharKhadi.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(AksharKhadi.AcknowledgementPageData)[i] + " : " + Object.values(AksharKhadi.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = AksharKhadi.hardCodedData['createdOn'];
    acknowledgementDiv.appendChild(div);
    document.getElementById("acknowledgementDiv").style.display = "none";
    AksharKhadi.createStars();
    AksharKhadi.giveStars();
}

AksharKhadi.showSkippedQuestions = function() {
    document.getElementById("responseBoxDiv").style.display = "none";
    AksharKhadi.queCnt = 0;
    AksharKhadi.showQuestions();
}

//function which creates star divs
AksharKhadi.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/star1.png");
        $(newDiv).append(newImage);
        $("#starsDiv").append(newDiv);
    }
};

AksharKhadi.giveStars = function() {
    var fractionVar, i, numberOfStars = 0,
        temp;
    ans = AksharKhadi.total_No_of_Questions / 5;
    temp = AksharKhadi.correctCounter / ans;
    numberOfStars = Math.floor(temp);
    temp = Math.round(temp);
    console.log(numberOfStars);
    console.log(temp);
    for (i = 1; i <= Math.floor(numberOfStars); i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/star2.png");
    /* if(temp>numberOfStars)
    document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/halfStar.png"); */
    $("#starsDiv").css("visibility", "visible");
    if (numberOfStars != 0) {
        document.getElementById("playSound").src = Utils.Path + "sounds/Instructions/" + "Star" + numberOfStars + ".mp3";
        document.getElementById("playSound").play();
    }
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(AksharKhadi.correctCounter, AksharKhadi.total_No_of_Questions, "3");
};

AksharKhadi.goNext = function() {
    clearInterval(AksharKhadi.skipTimer);
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}

AksharKhadi.startTimer = function() {
    if (AksharKhadi.noResponseTimer) {
        clearInterval(AksharKhadi.noResponseTimer);
        AksharKhadi.noResponseTimer = null;
        AksharKhadi.seconds = 0;
    }
    AksharKhadi.noResponseTimer = setInterval(function() {
        AksharKhadi.seconds++;
        if (AksharKhadi.seconds >= 7) {
            document.getElementById("playSound").src = Utils.Path + "sounds/instructions/please_ans_the_ques.mp3";
            document.getElementById("playSound").play();
            clearInterval(AksharKhadi.noResponseTimer);
            if (AksharKhadi.timeOut) {
                clearTimeout(AksharKhadi.timeOut);
                AksharKhadi.timeOut = null;
            }
            AksharKhadi.timeOut = setTimeout(function() {
                AksharKhadi.seconds = 0;
                AksharKhadi.startTimer();
            }, 2000);
        }
    }, 1000);
};