var AksharKhadi = {};
var Utils = {};
Utils.Path = '';
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 90,
    resId;
AksharKhadi.rightcnt = 0;
AksharKhadi.index = 0;
AksharKhadi.scoredMarks = 0;
AksharKhadi.rightcntForSLD = 0;
AksharKhadi.attempted = 0;
AksharKhadi.timeStatus = 0;
AksharKhadi.counter = 0;
AksharKhadi.starcnt = 1;
AksharKhadi.queArray = [];
AksharKhadi.optionArray = [];
AksharKhadi.quePos = -1;
$(document).ready(function() {
    if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
        Utils.mobileDeviceFlag = true;

    if (Utils.mobileDeviceFlag) {
        //Utils.Path = Android.getMediaPath('Aksharkhadi_KS');
        AksharKhadi.queArray = (Android.getTodaysLetters()).split(",");
    } else {
        AksharKhadi.queArray = getTodaysLetters();
    } 
	
	console.log(AksharKhadi.queArray);
	//AksharKhadi.queArray = ["प", "त"];
    $(".se-pre-con").fadeOut("slow");
    setTimeout(function() {
        AksharKhadi.setAllImages();
        AksharKhadi.init();
        AksharKhadi.getGameDataAfterTimeOut();
    }, 200);

});
function getTodaysLetters()
{
	var randomIndex;
	while (AksharKhadi.queArray.length !== 2) 
	{
	randomIndex = Math.floor(Math.random()*AksharKhadi.barakhadi.length);
	if($.inArray(AksharKhadi.barakhadi[randomIndex].suffix,AksharKhadi.queArray) === -1)
	AksharKhadi.queArray.push(AksharKhadi.barakhadi[randomIndex].suffix);
	}
}
AksharKhadi.setAllImages = function() {
    $('#playGame').prop('src', Utils.Path + 'Images/Aksharkhadi_Play.png');
    $('#home').prop('src', Utils.Path + 'Images/Aksharkhadi_Home.png');
    $('#speaker').prop('src', Utils.Path + 'Images/Aksharkhadi_Sound.png');
    $('#next').prop('src', Utils.Path + 'Images/Aksharkhadi_Next.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() {
    $('#playGame').text(AksharKhadi.hardCodeddata.play);
    $('#Flip').hide();
    $('#coverPage').show();
    $('#background').css({ 'backgroundImage': 'url(' + Utils.Path + 'Images/' + AksharKhadi.hardCodeddata['coverPage'] + ')' });
};

AksharKhadi.getGameDataAfterTimeOut = function() {

    AksharKhadi.permanantArray = JSON.parse(JSON.stringify(AksharKhadi.barakhadi));
    document.getElementById('playSound').src = Utils.Path + 'sounds/ting.mp3';
    document.getElementById('playSound').play();
    AksharKhadi.getGameData();
    AksharKhadi.createStars();
    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,#speaker').show();
    $('#wrongimg1,#wrongimg2').hide();
    var randomIndex = 0,
        temparr = [];
    AksharKhadi.arrOfSelectedWords = [];
    $('.slide').addClass('clickable');
    $('.optionForFlip').css({ 'display': 'block' });
    $('.clickable').css({ 'pointer-events': 'none' });
    $('.defaultImage').removeClass('flipIt');
    $('#lastGamePage,#divContainingFullImage').hide();
    $('#soundDiv,#divContainingSplitImages').fadeIn('slow');
    var queNo = AksharKhadi.findIndexOfWord(AksharKhadi.barakhadi, 'suffix', AksharKhadi.queArray[AksharKhadi.index]);
    randomIndex = Math.floor(Math.random() * AksharKhadi.barakhadi[queNo].list.length);
    if (AksharKhadi.counter == 0) {
        AksharKhadi.optionArray = AksharKhadi.barakhadi[queNo].list.slice();
    }
    if (AksharKhadi.barakhadi[queNo].list.length === 0) {
        AksharKhadi.barakhadi[queNo].list = JSON.parse(JSON.stringify(AksharKhadi.permanantArray[queNo].list));
        AksharKhadi.optionArray = AksharKhadi.barakhadi[queNo].list.slice();
    }
    var que = AksharKhadi.barakhadi[queNo].list.splice(randomIndex, 1);
    AksharKhadi.que = que[0];
    AksharKhadi.arrOfSelectedWords = [];
    AksharKhadi.arrOfSelectedWords = AksharKhadi.arrOfSelectedWords.concat(AksharKhadi.que);
    AksharKhadi.arrOfSelectedWords = populate(AksharKhadi.optionArray, AksharKhadi.arrOfSelectedWords, 9);
    AksharKhadi.arrOfSelectedWords = shuffleArray(AksharKhadi.arrOfSelectedWords);
    AksharKhadi.tempArray = AksharKhadi.arrOfSelectedWords.slice();
    AksharKhadi.fillGrid();
};

AksharKhadi.findIndexOfWord = function(array, path, letter) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][path] == letter)
            return i;
    }
};

function populate(array1, array2, length) {
    var randomIndex, flag;
    while (array2.length !== length) {
        flag = false;
        randomIndex = Math.floor(Math.random() * array1.length);
        for (var i = 0; i < array2.length; i++) {
            if (array1[randomIndex].word == array2[i].word)
                flag = true;
        }
        if (flag === false)
            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() {
    clearTimeout(AksharKhadi.timeStatus);
    AksharKhadi.randomQuestion = AksharKhadi.findIndexOfWord(AksharKhadi.tempArray, 'word', AksharKhadi.que.word);
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + "dikhao_h.mp3";
    document.getElementById('playSound').play();
    AksharKhadi.timeStatus = setTimeout(function() {
        var time = document.getElementById('playSound').duration;
        AksharKhadi.timeStatus = setTimeout(function() {
            document.getElementById('playSound').src = Utils.Path + 'sounds/' + AksharKhadi.tempArray[AksharKhadi.randomQuestion]['sound'];
            document.getElementById('playSound').play();
            setTimeout(function() {
                time = document.getElementById('playSound').duration;
                setTimeout(function() {
                    $('.clickable').css({ 'pointer-events': 'auto' });
                }, time * 500);
            }, 100);
        }, time * 1050);

    }, 100);
};


AksharKhadi.showQuestions = function(tempArray) {
    AksharKhadi.counter++;
    var d = new Date();
    $('#speaker').show();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

    AksharKhadi.randomQuestion = AksharKhadi.findIndexOfWord(AksharKhadi.tempArray, 'word', AksharKhadi.que.word);
    //Math.floor(Math.random()*AksharKhadi.tempArray.length);
    //AksharKhadi.findIndexOfWord(AksharKhadi.queArray[AksharKhadi.index]);

    document.getElementById('playSound').src = Utils.Path + 'sounds/' + "dikhao_h.mp3";
    $('#title').data('question', AksharKhadi.tempArray[AksharKhadi.randomQuestion]['word'].trim());
    questionId = AksharKhadi.tempArray[AksharKhadi.randomQuestion]['questionId'];

    document.getElementById('playSound').play();
    AksharKhadi.timeStatus = setTimeout(function() {
        var time = document.getElementById('playSound').duration;
        AksharKhadi.timeStatus = setTimeout(function() {
            document.getElementById('playSound').src = Utils.Path + 'sounds/' + AksharKhadi.tempArray[AksharKhadi.randomQuestion]['sound'];
            document.getElementById('playSound').play();
            setTimeout(function() {
                time = document.getElementById('playSound').duration;
                setTimeout(function() {
                    $('.clickable').css({ 'pointer-events': 'auto' });
                }, time * 500);
            }, 100);
        }, time * 1050);

    }, 100);
}

AksharKhadi.fillGrid = function() {
    var i = 1,
        imagePath;
    //AksharKhadi.randomImg=Math.floor(Math.random()*AksharKhadi.imageSet.length);
    for (var j = 1; j < 4; j++) {
        for (var k = 0; k < 3; k++) {
            AksharKhadi.randomQuestion = Math.floor(Math.random() * AksharKhadi.arrOfSelectedWords.length);
            $('#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']);
            /*if(AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['img']=="none")
            {*/
            $('#option' + (i - 1)).text(AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['word'].trim());
            $('#img' + j + '_' + k).hide();
            /*}
            else
            {
            	$('#img'+j+'_'+k).prop('src','Images/'+AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['img']);
            	$('#option'+(i-1)).hide();
            }*/
            i++;
            AksharKhadi.arrOfSelectedWords.splice(AksharKhadi.randomQuestion, 1);
        }
    }
}

AksharKhadi.checkAns = function(evt) {
    var source, frontImg, time = 0;
    AksharKhadi.attempted++;
    clearTimeout(AksharKhadi.timeStatus);
    AksharKhadi.gameOpened = true;
    $('#next,#speaker').hide();
    $('.clickable').css({ 'pointer-events': 'none' });
    wrongImgArray = ['backWrong1.png', 'backWrong2.png'];
    if ($('#' + evt).data('answer') == $('#title').data('question')) {
        scoredMarks = 1;
        totalMarks = 1;
        AksharKhadi.rightcnt++;
        AksharKhadi.rightcntForSLD++;
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);

        document.getElementById('playSound').src = Utils.Path + "sounds/thats_right.mp3";
        setTimeout(function() {
            time = document.getElementById('playSound').duration;
            document.getElementById('playSound').play();
            setTimeout(function() {
                if ((AksharKhadi.rightcnt) == 3) {
                    $('#next').hide();
                    AksharKhadi.scoredMarks = 10;
                    AksharKhadi.giveStars(AksharKhadi.starcnt++);
                    setTimeout(function() {
                        AksharKhadi.showNextQuestion();
                        $('#next').show();
                    }, 200);
                    return 0;
                }
                AksharKhadi.tempArray.splice(AksharKhadi.randomQuestion, 1);
                if (AksharKhadi.nextQuestionTimer) {
                    clearTimeout(AksharKhadi.nextQuestionTimer);
                    AksharKhadi.nextQuestionTimer = null;
                }
                AksharKhadi.nextQuestionTimer = setTimeout(function() {
                    $('#' + evt).removeClass("shake");
                    AksharKhadi.showQuestions();

                }, 200);
                if (AksharKhadi.counter >= 9) {
                    AksharKhadi.showNextQuestion();
                    $('#next').show();
                    return 0;
                }
                AksharKhadi.getGameData();
            }, time * 1050);
        }, 100);

    } else {
        scoredMarks = 0;
        totalMarks = 1;
        AksharKhadi.rightcnt = 0;
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);

        $('#' + evt).addClass("shake");
        document.getElementById('playSound').src = Utils.Path + "sounds/wrongSoundAksharkhadi.mp3";
        setTimeout(function() {
            time = document.getElementById('playSound').duration;
            document.getElementById('playSound').play();
            setTimeout(function() {
                AksharKhadi.tempArray.splice(AksharKhadi.randomQuestion, 1);
                if (AksharKhadi.nextQuestionTimer) {
                    clearTimeout(AksharKhadi.nextQuestionTimer);
                    AksharKhadi.nextQuestionTimer = null;
                }
                AksharKhadi.nextQuestionTimer = setTimeout(function() {
                    $('#' + evt).removeClass("shake");
                    AksharKhadi.showQuestions();

                }, 200);
                if (AksharKhadi.counter >= 9) {
                    AksharKhadi.showNextQuestion();
                    $('#next').show();
                    return 0;
                }
                AksharKhadi.getGameData();
            }, time * 1050);
        }, 100);

    }


};

AksharKhadi.createStars = function() {
    var temp, newImage, newDiv, i, numberOfStars = 2;
    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 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1");

        newImage = document.createElement("img");
        newImage.setAttribute("id", "starImg" + i);
        newImage.setAttribute("class", "img-responsive");
        newImage.setAttribute("src", Utils.Path + "images/star1.png");
        $(newDiv).append(newImage);
        $("#starDiv").append(newDiv);
    }
};

AksharKhadi.giveStars = function(id) {
    $("#starImg" + id).prop("src", Utils.Path + "images/star2.png");
};

AksharKhadi.showNextQuestion = function() {
    AksharKhadi.index++;

    console.log(AksharKhadi.rightcntForSLD, AksharKhadi.attempted);
  /*  if (Utils.mobileDeviceFlag)
        Android.StudentLevelDetection(AksharKhadi.rightcntForSLD, AksharKhadi.attempted);  */

    AksharKhadi.rightcntForSLD = 0;
    AksharKhadi.counter = 0;
    AksharKhadi.attempted = 0;
    clearTimeout(AksharKhadi.timeStatus);

    clearTimeout(AksharKhadi.nextQuestionTimer);

    if (AksharKhadi.index == 2) {
        AksharKhadi.shoMessage();
        return;
    }
    clearTimeout(AksharKhadi.nextQuestionTimer);
    if (AksharKhadi.gameOpened == true) {
        //console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
        //Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
    }
    AksharKhadi.rightcnt = 0;
    AksharKhadi.getGameData();
    AksharKhadi.showQuestions();

};

AksharKhadi.callHome = function() {
    clearTimeout(AksharKhadi.timeStatus);
    clearTimeout(AksharKhadi.nextQuestionTimer);
    if (AksharKhadi.gameOpened == true) {
        //console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
        //Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
    }
    setTimeout(function() {
        location.reload(true);
    }, 200);
}
AksharKhadi.shoMessage = function() {
    $("#game").hide();
    document.getElementById("mainGamePage").innerHTML = AksharKhadi.hardCodeddata.msg;
    document.getElementById("mainGamePage").style = "font-size: 5vw; text-align:center;margin-top:12%;";
}