// Javascript containing all functions used

//============================================
// GLOBAL VARIABLES FOR HOLDING TEXT FROM BOOK
//============================================

// Holds the title of every chapter. [0] is chapter 1 title, [1] is chapter 2 title, etc.
var arrayOfChapterTitles = [];

// After being initialized, will become 2D array. Formated as [chapter][topic].
var arrayOfTopics = [];

//============================================
// FUNCTIONS
//============================================

function FileHelper() {}
{
    // Reads raw text from chapter file
    FileHelper.readRawTextFromFile = function(file)
    {
        var rawFile = new XMLHttpRequest();
        var allText ="";
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    allText = rawFile.responseText;
                }
            }
        }
        rawFile.send(null);
        return allText;
    }

    // Reads chapter name from titles.txt, storing them sequentially in arrayOfChapterTitles[]
    FileHelper.readChaptersNames = function()
    {
        var pathOfChapters = "text/titles.txt";
        var chapterTitlesRawText = FileHelper.readRawTextFromFile(pathOfChapters);
        arrayOfChapterTitles = chapterTitlesRawText.split("\n");
        return arrayOfChapterTitles;
    }

    // Reads topics from appropriate chapter file. Create 2D array in arrayOfTopics[][], where [chapter][topic].
    FileHelper.readTopics = function()
    {
        var arrayOfChapters = FileHelper.readChaptersNames();
        var numberOfChapters = arrayOfChapters.length;

        for(var i = 0; i < numberOfChapters; i++)
        {
            arrayOfTopics[i] = [];
            var chapterNumber = i + 1;
            var chapterTopicsRawText = FileHelper.readRawTextFromFile("text/chapter_" + chapterNumber + ".txt");
            var chapterTopicsArray = chapterTopicsRawText.split("\n");
            arrayOfTopics[i] = chapterTopicsArray;
        }
        return arrayOfTopics;
    }
}

function createChaptersList(elementID)
{
    var list = "<ol>";
    for(var i =0; i < arrayOfChapterTitles.length; i++) {
        console.log(arrayOfChapterTitles[i]);
        list += "<li><a href='topic.html' value='" + i + "' >"+arrayOfChapterTitles[i].trim()+"</a></li>";
    }
    list += "</ol>";
    console.log(list);
    console.log($("#" + elementID));
    $("#" + elementID).html(list);
}

function prepareData() {
    if (arrayOfChapterTitles.length == 0)
    {
        FileHelper.readChaptersNames();
    }
    if (arrayOfTopics.length == 0)
    {
        FileHelper.readTopics();
    }
}

function printTopicText() {
    var topicText = "";
    if($.cookie('topicIndex')) {
        var index = $.cookie('topicIndex');
        if(!index) index = 1;
        var chapterIndex = $.cookie('chapterIndex');
        if(!chapterIndex) chapterIndex = 1;
        console.log('Topic: ', index);
        console.log('Chapter: ', chapterIndex);
        topicText = "<h1 class='title'>" + arrayOfChapterTitles[chapterIndex] + "</h1>";
        topicText += "<p id='topicBody'>" + arrayOfTopics[chapterIndex][index] + "</p>";

    } else {
        navigateRandom();
    }
    $("#paragraph-title-content").fadeOut(500, function () {
        $("#paragraph-title-content").html(topicText);
        });
    $("#paragraph-title-content").fadeIn(750, 'linear');
    placeFavorite();
}

//0 = forward, 1 = backword
function withinTopic(index) {
    var currentTopicIndex = $.cookie('topicIndex');
    var currentChapterIndex = $.cookie('chapterIndex');
    if(index==0) {
        var curr = arrayOfTopics[currentChapterIndex].length - 1;
        var result = false;
        if(curr > currentTopicIndex) result = true;
    } else {
        var curr = arrayOfTopics[currentChapterIndex].length - 1;
        var result = false;
        if(currentTopicIndex > 0) result = true;
    }

    console.log('within chapter: ', curr, ' topic: ', currentTopicIndex, result);
    return result;
}

function topicChoosen(chap) {
    $.cookie('topicIndex', 0);
    console.log('topicIndex', $.cookie('topicIndex'));
    $.cookie('chapterIndex', chap);
    console.log('chapterIndex', $.cookie('chapterIndex'));
    printTopicText();
}

function favoriteChoosen(chap, top) {
    $.cookie('topicIndex', top);
    console.log('topicIndex', $.cookie('topicIndex'));
    $.cookie('chapterIndex', chap);
    console.log('chapterIndex', $.cookie('chapterIndex'));
    printTopicText();
}

function navigateRandom() {
    var randomChapterindex = Math.floor(Math.random() * arrayOfChapterTitles.length);
    var randomTopicIndex = Math.floor(Math.random() * arrayOfTopics[randomChapterindex].length);

    $.cookie('topicIndex', randomTopicIndex);
    console.log('topicIndex', $.cookie('topicIndex'));
    $.cookie('chapterIndex', randomChapterindex);
    console.log('chapterIndex', $.cookie('chapterIndex'));

    topicText = "<h1 class='title'>" + arrayOfChapterTitles[randomChapterindex] + "</h1>";
    topicText += "<p>" + arrayOfTopics[randomChapterindex][randomTopicIndex] + "</p>";
    $("#paragraph-title-content").fadeOut(500, function () {
        $("#paragraph-title-content").html(topicText);
        });
    $("#paragraph-title-content").fadeIn(750, 'linear');
    placeFavorite();
}

//0 = forward, 1 = backword
function navigate(index) {
    if(index == 0) {
        forward();
    } else {
        backward();
    }
}

function backward() {
    var currentTopicIndex = $.cookie('topicIndex');
    var currentChapterIndex = $.cookie('chapterIndex');
    if(currentChapterIndex == 0 && currentTopicIndex == 0) {
        $.cookie('topicIndex', 8);
        console.log('topicIndex', $.cookie('topicIndex'));
        $.cookie('chapterIndex', 21);
        console.log('chapterIndex', $.cookie('chapterIndex'));
    } else if (withinTopic(1)) {
        $.cookie('topicIndex', --currentTopicIndex);
        console.log('topicIndex', $.cookie('topicIndex'));
    } else {
        $.cookie('chapterIndex', --currentChapterIndex);
        console.log('chapterIndex', $.cookie('chapterIndex'));
        var lastTopicIndex = arrayOfTopics[currentChapterIndex].length - 1;
        $.cookie('topicIndex', lastTopicIndex);
        console.log('topicIndex', $.cookie('topicIndex'));
    }
    printTopicText();
}

function forward() {
    var currentTopicIndex = $.cookie('topicIndex');
    var currentChapterIndex = $.cookie('chapterIndex');
    if(currentChapterIndex == 21 && currentTopicIndex == 8) {
        $.cookie('topicIndex', 0);
        console.log('topicIndex', $.cookie('topicIndex'));
        $.cookie('chapterIndex', 0);
        console.log('chapterIndex', $.cookie('chapterIndex'));
    } else if (withinTopic(0)) {
            $.cookie('topicIndex', ++currentTopicIndex);
            console.log('topicIndex', $.cookie('topicIndex'));
    } else {
            $.cookie('chapterIndex', ++currentChapterIndex);
            console.log('chapterIndex', $.cookie('chapterIndex'));
            $.cookie('topicIndex', 0);
            console.log('topicIndex', $.cookie('topicIndex'));
    } 
    printTopicText();
}

var topicIndex = $.cookie('topicIndex');
var chapterIndex = $.cookie('chapterIndex');
var favorites = JSON.parse($.cookie('favorites')) != null ? JSON.parse($.cookie('favorites')) : [];
var currentItem = [];
currentItem.push(chapterIndex);
currentItem.push(topicIndex);

function toggleFavorite(item) {
    if(favorites) {
        if(isFavorite()) {
            removeFavorite();
            return false;
        } else {
            addFavorite();
            return true;
        }
    } else {
        addFavorite();
        return true;
    }
}

function addFavorite() {
    var currentItem = [$.cookie('chapterIndex'), $.cookie('topicIndex')];
    if(favorites) {
        console.log(favorites);
        favorites.push(currentItem);
        $.cookie('favorites', JSON.stringify(favorites));
    } else {
        var favs =[];
        favs.push(currentItem);
        console.log(favs);
        $.cookie('favorites',  JSON.stringify(favs));
        favorites = favs;
    }
    console.log(currentItem, ' added');
}

function removeFavorite() {
    var currentItem = [$.cookie('chapterIndex'), $.cookie('topicIndex')];
    var index = 0;
    for(var i = 0; i < favorites.length; i++) {
        var myArray = favorites[i];
        if(myArray && myArray[0] == $.cookie('chapterIndex') && myArray[1] == $.cookie('topicIndex'))
            {index = i; break;}
    }
    if(index > -1) {
        console.log(favorites);
        if(favorites.splice) {
            favorites.splice(index, 1);
        } else {
            favorites = "";
        }
        $.cookie('favorites', JSON.stringify(favorites));
    }
}

function placeFavorite() {
    if(favorites) {
        console.log(currentItem, isFavorite());
        if(isFavorite()) {
            $("#favorite").html("<img class='heart' src='res/RedHeart.png' value='"+ topicIndex +"'></img>");
        } else {
            $("#favorite").html("<img class='heart' src='res/Heart.png' value='"+ topicIndex +"'></img>");
        }
    } else {
        $("#favorite").html("<img class='heart' src='res/Heart.png' value='"+ topicIndex +"'></img>");
    }
    console.log('placed fav ', isFavorite());
}

function loadFavoriteList() {
    var favList = "";
    console.log(favorites);
    if(favorites) {
        for(var i = 0; i < favorites.length; i++) {
            var myArray = favorites[i];
            if(myArray) {
                var chap = myArray[0];
                var topic = myArray[1];
                console.log("<li chapter='" + chap + "' topic='" + topic + "'>");
                favList += "<li chapter='" + chap + "' topic='" + topic + "'>" + arrayOfTopics[chap][topic].substring(0,20) + "...</li>"    
            }
        }
        console.log('filled fav ', favList);
        $('#favoritesSideList').html(favList);
    }
}

function loadTopicsList() {
    var topicList = "";
    for(var i = 0; i < arrayOfChapterTitles.length; i++) {
        topicList += "<li class='topicList' chapter='" + i + "'>"+ arrayOfChapterTitles[i] + "</li>";   
    }
    console.log('filled topics ', topicList);
    $('#topicsSideList').html(topicList);
}

function isFavorite() {
    if(favorites) {
        for(var i = 0; i < favorites.length; i++) {
            var myArray = favorites[i];
            if(myArray && myArray[0] == $.cookie('chapterIndex') && myArray[1] == $.cookie('topicIndex')) {
                return true;
        }
    }
    return false;
    }   
}

