var xmlhttp;
var gBookName = "";
var gBookNumber = -1; // prefix 'g' means it is a global variable

/**
 *
 * @param url string The URL to make the AJAX call to
 * @param cbfunc function The callback function to use with the AJAX call
 * @returns nothing
 */
function loadXMLDoc(url, cbfunc) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = cbfunc;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

/** Retrieve the HTML for the bookID/chapter combination that was selected */
function ajGetVerses(bkID, chptNum, which) {

    var reqUrl = "chapters/"; // Chapter html files should be named like: book_1_chapter_1.html

    // Set up the request URL
    var opUrl = reqUrl + "book_" + bkID + "_chpt_" + chptNum + ".html";

    // Perform the request, passing in the handler function
    loadXMLDoc(opUrl, function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {

        // Depending on which pane we do, put the returned HTML into the corresponding pane
        switch(which) {
            case "left":
                document.getElementById("sw_traverse").innerHTML = xmlhttp.responseText;
                activateVerses(which);
                break;
            case "right":
                document.getElementById("right_pane").innerHTML = xmlhttp.responseText;
                break;
        }
    }
    });

}

/** Resets the background color of a bunch of divs in a parent div */
function resetBackground(whichDiv){

    parentDiv = document.getElementById(whichDiv);

    divs = Array.from(parentDiv.children).filter(element => element.tagName === "DIV");

    for (var i = 0; i < divs.length; i++) {
        divs[i].style.backgroundColor = "";
    }
}

/** Retrieve the HTML for the list of matches */
function ajGetMatches(matchId) {

    var reqUrl = "matches/";

    // Set up the request URL
    var opUrl = reqUrl + "match_" + matchId + ".html";

    // Perform the request, passing in the handler function
    loadXMLDoc(opUrl, function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            document.getElementById("middle_pane").innerHTML = "<h2>Most Similar Verses</h2>\n" + xmlhttp.responseText;
            activateMatches();
    }
    });
}



/** Build out the navigation */
function buildNav(section, book, chapter) {
    buildBreadCrumb(section, book, chapter);
    buildLeft(section, book, chapter);
}

/** Build out the bread crumb at the top */
function buildBreadCrumb(section, book, chapter) {

    /** Start with a navigation that takes us home */
    var bc_cts = "<a onClick='javascript:buildNav();'>Home</a>";

    /** If we have no section, display and exit. */
    if (section === undefined) {
        document.getElementById("breadcrumb").innerHTML = bc_cts;
        // document.getElementById("instructions").innerHTML = "Select one of the Standard Works.";
        return;
    }

    /** If we have a section, add it on */
    bc_cts += " &raquo; <a onClick='javascript:buildNav(" + section + ");'>" + sw[section].name + "</a>";

    /** If we have no book, display and exit. */
    if (book === undefined) {
        document.getElementById("breadcrumb").innerHTML = bc_cts;
        // document.getElementById("instructions").innerHTML = "Select a book.";
        return;
    }
    
    // global access to the last book name the user selected
    gBookName = sw[section].books[book].name;
    
    // global access to the last book number the user selected
    gBookNum = sw[section].books[book].bkid;
    
    /** If we have a book, add it on */
    bc_cts += " &raquo; <a onClick='javascript:buildNav(" + section + "," + book + ");'>" + gBookName + "</a>";

    /** If we have no chapter, display and exit. */
    if (chapter === undefined) {
        document.getElementById("breadcrumb").innerHTML = bc_cts;
        // document.getElementById("instructions").innerHTML = "Select a chapter.";
        return;
    }

    /** If we have a chapter, add it on */
    chapter_string = "Chapter";
    if (section === 3){
        chapter_string = "Section"; // Doctrine and Covenants
    }

    bc_cts += " &raquo; <span>" + chapter_string + " " + chapter + "</span>";

    document.getElementById("breadcrumb").innerHTML = bc_cts;
    // document.getElementById("instructions").innerHTML = "Select a verse.";
    
}

/** Build out the contents of our left column */
function buildLeft(section, book, chapter) {

    var navTable = "<div>\n";

    if (section === undefined) { // When "home" is picked, do this.

        var swsize = Object.size(sw);

        for (var i = 0; i < swsize; i++) {
            navTable += "<a class='left-nav' onClick='javascript:buildNav(" + i + ");'>" + sw[i].name + "</a><br />\n";
        }

    } else if (book === undefined) { // When a "section" is picked, do this.

        // How many books in this section?
        var sectsize = Object.size(sw[section].books);

        // Display a book entry for each book in the JSON
        for (var j = 0; j < sectsize; j++) {

            // Show the book entry - include the section and book index (not id) for the next level
            navTable += "<a class='left-nav' onClick='javascript:buildNav(" + section + "," + j + ");'>" + sw[section].books[j].name + "</a><br />\n";
        }

    } else if (chapter === undefined){ // When a "book" is picked, do this.
        
        var numchapts = sw[section].books[book].chpt;
        
        var chptname = "Chapter";

        if (section === 3) { // for the D&C
            chptname = "Section";
        }

        // List out all of the chapters
        for (var n = 1; n <= numchapts; n++) {
            navTable += " <a onClick='javascript:buildNav(" + section + "," + book + "," + n + ");'>" + n + "</a> \n";
        }

    } else { // If a chapter has been selected, load it up

        // Grab the book ID from the JSON object
        bookid = sw[section].books[book].bkid;

        // Clear out our chapter
        document.getElementById("sw_traverse").innerHTML = "";

        // Load up the selected chapter
        ajGetVerses(bookid, chapter, "left");

        // We don't need anything in the rest of this function, so return
        return;

    }

    // Close out the table
    navTable += "</div>\n";



    // Apply the HTML
    document.getElementById("sw_traverse").innerHTML = navTable;
    
    document.getElementById("middle_pane").innerHTML = "";

    resetRightPane();

}

/** Make sure the instructions show in the right pane. */
function resetRightPane(){

    // Tell the user how to use this
    instructions = "<h2>What Is This?</h2>\n";
    instructions += "<p>Throughout your study, you may wish to find verses similar to the one you are reading.</p>\n";
    instructions += "<p>That is the purpose of this tool.</p>\n";
    instructions += "<p>Think of it as a computer-generated version of the footnotes as found in the Standard Works.</p>\n";
    instructions += "<p>To begin, browse to the chapter you are studying.  Then, select your verse.</p>\n";
    instructions += "<p>A list of similar verses will appear in the middle. The most similar verse will be at the top.</p>\n";
    instructions += "<p>Then, select one of the suggested verses to see its entire chapter appear here on the right.</p>\n";

    document.getElementById("right_pane").innerHTML = instructions;

}

/** Runs after we retrieve the verses and put them into the left nav */
function activateVerses(which){

    if( which === "left" ){ // only apply if we're putting verses in the left pane
        // Attach the CSS and onClick() to the child DIVs of "sw_traverse"
        parentDiv = document.getElementById("sw_traverse");
        divs = Array.from(parentDiv.children).filter(element => element.tagName === "DIV");

        for (var i = 0; i < divs.length; i++) {
            var div = divs[i];
            div.classList.add("verse-hover");
            div.addEventListener("click", clickVerse, false);
        }
    }
}

/** Runs after we retrieve the matches and put them into the middle column */
function activateMatches(){
    parentDiv = document.getElementById("middle_pane");
    divs = Array.from(parentDiv.children).filter(element => element.tagName === "DIV");

    for (var i = 0; i < divs.length; i++) {
        var div = divs[i];
        div.classList.add("match-hover");
        div.addEventListener("click", clickMatch, false);
    }
}

/** When the user selects a verse in the left pane, this gets triggered */
function clickVerse(event) {

    // Which object triggered the event?
    const clickedDiv = event.target;

    resetBackground("sw_traverse");

    clickedDiv.style.backgroundColor = "#ceebce";

    resetRightPane();

    // Load up the matches
    ajGetMatches(clickedDiv.id);
}

/** When the user selects a match in the middle pane, this gets triggered */
function clickMatch(event) {

    // Which object triggered the event?
    var clickedDiv = event.target;

    // We clicked on the verse reference, but want its containing div
    if(clickedDiv.hasAttribute("id") == false){
        clickedDiv = clickedDiv.parentNode;
    }

    // Clear out the contents of the middle pane
    resetBackground("middle_pane");

    // Grab our DIV's ID
    rawId = clickedDiv.id;

    // Separate the contents by the dash
    pieces = rawId.split("-");

    // BookID of the clicked match
    bookid = pieces[0];

    // Chapter number of the clicked match
    chapter = pieces[1];

    // Visual cue to the user that they've clicked the matching verse
    clickedDiv.style.backgroundColor = "#ceebce";

    // Load up that match's whole chapter on the right
    ajGetVerses(bookid, chapter, "right");

}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key))
            size++;
    }
    return size;
};

var sw = {
    0: {
        columns: 4,
        name: "Old Testament",
        books: {
            0: {
                name: "Genesis",
                chpt: 50,
                bkid: 1
            },
            1: {
                name: "Exodus",
                chpt: 40,
                bkid: 2
            },
            2: {
                name: "Leviticus",
                chpt: 27,
                bkid: 3
            },
            3: {
                name: "Numbers",
                chpt: 36,
                bkid: 4
            },
            4: {
                name: "Deuteronomy",
                chpt: 34,
                bkid: 5
            },
            5: {
                name: "Joshua",
                chpt: 24,
                bkid: 6
            },
            6: {
                name: "Judges",
                chpt: 21,
                bkid: 7
            },
            7: {
                name: "Ruth",
                chpt: 4,
                bkid: 8
            },
            8: {
                name: "1 Samuel",
                chpt: 31,
                bkid: 9
            },
            9: {
                name: "2 Samuel",
                chpt: 24,
                bkid: 10
            },
            10: {
                name: "1 Kings",
                chpt: 22,
                bkid: 11
            },
            11: {
                name: "2 Kings",
                chpt: 25,
                bkid: 12
            },
            12: {
                name: "1 Chronicles",
                chpt: 29,
                bkid: 13
            },
            13: {
                name: "2 Chronicles",
                chpt: 36,
                bkid: 14
            },
            14: {
                name: "Ezra",
                chpt: 10,
                bkid: 15
            },
            15: {
                name: "Nehemiah",
                chpt: 13,
                bkid: 16
            },
            16: {
                name: "Esther",
                chpt: 10,
                bkid: 17
            },
            17: {
                name: "Job",
                chpt: 42,
                bkid: 18
            },
            18: {
                name: "Psalms",
                chpt: 150,
                bkid: 19
            },
            19: {
                name: "Proverbs",
                chpt: 31,
                bkid: 20
            },
            20: {
                name: "Ecclesiastes",
                chpt: 12,
                bkid: 21
            },
            21: {
                name: "Song of Solomon",
                chpt: 8,
                bkid: 22
            },
            22: {
                name: "Isaiah",
                chpt: 66,
                bkid: 23
            },
            23: {
                name: "Jeremiah",
                chpt: 52,
                bkid: 24
            },
            24: {
                name: "Lamentations",
                chpt: 5,
                bkid: 25
            },
            25: {
                name: "Ezekiel",
                chpt: 48,
                bkid: 26
            },
            26: {
                name: "Daniel",
                chpt: 12,
                bkid: 27
            },
            27: {
                name: "Hosea",
                chpt: 14,
                bkid: 28
            },
            28: {
                name: "Joel",
                chpt: 3,
                bkid: 29
            },
            29: {
                name: "Amos",
                chpt: 9,
                bkid: 30
            },
            30: {
                name: "Obadiah",
                chpt: 1,
                bkid: 31
            },
            31: {
                name: "Jonah",
                chpt: 4,
                bkid: 32
            },
            32: {
                name: "Micah",
                chpt: 7,
                bkid: 33
            },
            33: {
                name: "Nahum",
                chpt: 3,
                bkid: 34
            },
            34: {
                name: "Habakkuk",
                chpt: 3,
                bkid: 35
            },
            35: {
                name: "Zephaniah",
                chpt: 3,
                bkid: 36
            },
            36: {
                name: "Haggai",
                chpt: 2,
                bkid: 37
            },
            37: {
                name: "Zechariah",
                chpt: 14,
                bkid: 38
            },
            38: {
                name: "Malachi",
                chpt: 4,
                bkid: 39
            }
        }
    },
    1: {
        columns: 4,
        name: "New Testament",
        books: {
            0: {
                name: "Matthew",
                chpt: 28,
                bkid: 40
            },
            1: {
                name: "Mark",
                chpt: 16,
                bkid: 41
            },
            2: {
                name: "Luke",
                chpt: 24,
                bkid: 42
            },
            3: {
                name: "John",
                chpt: 21,
                bkid: 43
            },
            4: {
                name: "Acts",
                chpt: 28,
                bkid: 44
            },
            5: {
                name: "Romans",
                chpt: 16,
                bkid: 45
            },
            6: {
                name: "1 Corinthians",
                chpt: 16,
                bkid: 46
            },
            7: {
                name: "2 Corinthians",
                chpt: 13,
                bkid: 47
            },
            8: {
                name: "Galatians",
                chpt: 6,
                bkid: 48
            },
            9: {
                name: "Ephesians",
                chpt: 6,
                bkid: 49
            },
            10: {
                name: "Philippians",
                chpt: 4,
                bkid: 50
            },
            11: {
                name: "Colossians",
                chpt: 4,
                bkid: 51
            },
            12: {
                name: "1 Thessalonians",
                chpt: 5,
                bkid: 52
            },
            13: {
                name: "2 Thessalonians",
                chpt: 3,
                bkid: 53
            },
            14: {
                name: "1 Timothy",
                chpt: 6,
                bkid: 54
            },
            15: {
                name: "2 Timothy",
                chpt: 4,
                bkid: 55
            },
            16: {
                name: "Titus",
                chpt: 3,
                bkid: 56
            },
            17: {
                name: "Philemon",
                chpt: 1,
                bkid: 57
            },
            18: {
                name: "Hebrews",
                chpt: 13,
                bkid: 58
            },
            19: {
                name: "James",
                chpt: 5,
                bkid: 59
            },
            20: {
                name: "1 Peter",
                chpt: 5,
                bkid: 60
            },
            21: {
                name: "2 Peter",
                chpt: 3,
                bkid: 61
            },
            22: {
                name: "1 John",
                chpt: 5,
                bkid: 62
            },
            23: {
                name: "2 John",
                chpt: 1,
                bkid: 63
            },
            24: {
                name: "3 John",
                chpt: 1,
                bkid: 64
            },
            25: {
                name: "Jude",
                chpt: 1,
                bkid: 65
            },
            26: {
                name: "Revelation",
                chpt: 22,
                bkid: 66
            }
        }
    },
    2: {
        columns: 2,
        name: "Book of Mormon",
        books: {
            0: {
                name: "1 Nephi",
                chpt: 22,
                bkid: 67
            },
            1: {
                name: "2 Nephi",
                chpt: 33,
                bkid: 68
            },
            2: {
                name: "Jacob",
                chpt: 7,
                bkid: 69
            },
            3: {
                name: "Enos",
                chpt: 1,
                bkid: 70
            },
            4: {
                name: "Jarom",
                chpt: 1,
                bkid: 71
            },
            5: {
                name: "Omni",
                chpt: 1,
                bkid: 72
            },
            6: {
                name: "Words of Mormon",
                chpt: 1,
                bkid: 73
            },
            7: {
                name: "Mosiah",
                chpt: 29,
                bkid: 74
            },
            8: {
                name: "Alma",
                chpt: 63,
                bkid: 75
            },
            9: {
                name: "Helaman",
                chpt: 16,
                bkid: 76
            },
            10: {
                name: "3 Nephi",
                chpt: 30,
                bkid: 77
            },
            11: {
                name: "4 Nephi",
                chpt: 1,
                bkid: 78
            },
            12: {
                name: "Mormon",
                chpt: 9,
                bkid: 79
            },
            13: {
                name: "Ether",
                chpt: 15,
                bkid: 80
            },
            14: {
                name: "Moroni",
                chpt: 10,
                bkid: 81
            }
        }
    },
    3: {
        columns: 1,
        name: "Doctrine & Covenants",
        books: {
            0: {
                name: "Sections",
                chpt: 138,
                bkid: 82
            }
        }
    },
    4: {
        columns: 1,
        name: "Pearl of Great Price",
        books: {
            0: {
                name: "Moses",
                chpt: 8,
                bkid: 83
            },
            1: {
                name: "Abraham",
                chpt: 5,
                bkid: 84
            },
            2: {
                name: "Joseph Smith\u2014Matthew",
                chpt: 1,
                bkid: 85
            },
            3: {
                name: "Joseph Smith\u2014History",
                chpt: 1,
                bkid: 86
            },
            4: {
                name: "Articles of Faith",
                chpt: 1,
                bkid: 87
            }
        }
    }
};