//
// JavaScript functions for loading a poem.
//

    function loadPoem(defYear, defName) {
    	
    	// get requested poem year and name.
    	var qs = new QueryString();
    	var year = qs.get("year");
    	var name = qs.get("name");
    	
    	// If no query param was provided for either year or name,
    	// use the default value passed.
    	if (year == null) year = defYear;
    	if (name == null) name = defName;
    	
    	// Load the request poem.
    	loadXML(parsePoemXML, siteURL + "poems/" + year + "/" + name + ".xml");
    }

    function parsePoemXML(xmlDoc) {

		// Clear the previous contents
		var poemDiv = document.getElementById("poem");
		var poemDivChildren = poemDiv.childNodes;
		var nPoemDivChildren = poemDivChildren.length;
		for (var i = 0; i < nPoemDivChildren; i++) {
			poemDiv.removeChild(poemDivChildren[0]);
		}

		// Get the new contents
		var poem = xmlDoc.documentElement;
        var poemTitle = poem.getElementsByTagName("title")[0].firstChild.nodeValue;
		var stanzas = poem.getElementsByTagName("stanza");
		var date = poem.getElementsByTagName("date")[0];

		// Display the title
        var titleDiv = document.createElement("p");
        titleDiv.className = "poemTitle";
        var titleText = document.createTextNode(poemTitle);
        titleDiv.appendChild(titleText);
        poemDiv.appendChild(titleDiv);

        // Display the poem body
        for (var i = 0; i < stanzas.length; i++) {
            showStanza(poemDiv, stanzas[i]);
        }
        
        // Display the signature, release date and copyright.
        addFooter(poemDiv, date)
        
        // Display the dedication if there is one.
        var dedication = poem.getElementsByTagName("dedication")[0];
        if (dedication != null) {
        	showDedication(poemDiv, dedication);
        }
    }

    function showStanza(poemDiv, stanza) {
        var stanzaDiv = document.createElement("p");
        stanzaDiv.className = "poemText";
		var lines = stanza.getElementsByTagName("line");
		var i; for (i = 0; i < lines.length - 1; i++) {
			showLine(stanzaDiv, lines[i], true);
		}
		showLine(stanzaDiv, lines[i], false);
        poemDiv.appendChild(stanzaDiv);
    }
    
    function showDedication(poemDiv, dedication) {
    	var dedDiv = document.createElement("p");
    	dedDiv.className = "dedicationText";
    	var lines = dedication.getElementsByTagName("line");
    	var i;
    	for (i = 0; i < lines.length - 1; i++) {
    		showLine(dedDiv, lines[i], true);
    	}
		showLine(dedDiv, lines[i], false);
        poemDiv.appendChild(dedDiv);
    }

    function showLine(div, line, lineBreak) {
        lineText = document.createTextNode(line.firstChild.nodeValue);
        div.appendChild(lineText);
        if (lineBreak) {
            div.appendChild(document.createElement("br"));
        }  
    }
