// loader.js
//
// implements note loading and unloading for the 
// "Burnin: The Missing Manual" document

// we'll be needing network access
var xhr = new XMLHttpRequest();

// this is the callback function from spans with onClick
// set in the main document. it assembles a relative uri
// and fires it off across the network. there is no
// error checking/handling.
function getNote() {
    var note = './notes/' + arguments[0] + '.txt';
    xhr.open("GET", note, true);
    xhr.onreadystatechange = updateNote; // callback for receipt of data
    xhr.send(null);
}

// our XMLHttpRequest object calls this routine when it has a
// response from the remote server. that response COULD be an error,
// but we won't know it. that's a problem for someone later on,
// turning this into robust, general-purpose code.
function updateNote() {
    // '4' is 'done'. we don't care otherwise.
    if (xhr.readyState == 4) {
	var response = xhr.responseText;
	
	// get the node id of the div which actually holds the notes
	var noteDiv = document.getElementById("note");
	// and clear out whatever's inside it
	clearNotes(noteDiv);
	
	// now set up a regex of two or more newlines. the note file
	// format is plaintext, with blank lines separating
	// paragraphs.
	var re = /\n{2,}/;
	// and split the response from the server into an array on them
	var paraArray = response.split(re);
	// then for each element of the array (i.e. "paragraph")
	for (var i = 0; i < paraArray.length; ++i) {
	    // create a new 'p' element
	    var para = document.createElement("p");
	    // fill it with the paragraph text
	    para.innerHTML = paraArray[i];
	    // and make it belong to the notes div
	    noteDiv.appendChild(para);
	}

	// add that kicky little red close box
	makeCloseBox(noteDiv);
    }
}

// utility function to empty out whatever's inside the note-holder div.
// it gets caled by updateNote and from the closebox callback that
// makeCloseBox constructs
function clearNotes(node) {
    // get node id if we don't have one. we should when populating a new
    // note, and won't when the close box has been clicked
    if (node == undefined) {
	node = document.getElementById("note");
    }
    // remove existing children, if any
    while (node.firstChild) {
	node.removeChild(node.firstChild);
    }
}


// utility function to build cute little boxes that users can click
// to clear out their notes area
function makeCloseBox(node) {
    // we need a new div
    var closeBox = document.createElement("div");
    // and it needs two attributes set: a class (for styling)
    closeBox.setAttribute("class", "closebox");
    // and onClick, for a handler, so it'll do something
    // damn, rewriting documents from the inside is fun :D
    closeBox.setAttribute("onClick", 
                          "clearNotes()");
    // its actual content is just a capital X
    closeBox.innerHTML = 'X';
    // and finally, make it be the last child of the note div
    node.appendChild(closeBox);
}
