/* Testimonials.js
  Functions that select and display a random testimonial retrieved from an XML file. */

var tmRequest = null;
// Global variable to hold the id of the container to fill with a testimonial.
var testimonialContainerId = null;
// Invoke the getTestimonial function. The page must have a Testimonial div defined somewhere.
//getTestimonial("Testimonial");

/* getTestimonial
   Retrieve random testimonial.
   Parameters:
      containerId: The id of a div that will hold the testimonial.
  */
function getTestimonial(containerId) {
   testimonialContainerId = containerId;
   tmRequest = initRequest(handleTestimonialRequest);
   submitRequest(tmRequest, "GET", "inc/Testimonials.xml", true);
}

/* handleTestimonialRequest Function
  Event handler that retrieves testimonial XML and randomly selects a testimonial to display. */
function handleTestimonialRequest() {
  if (tmRequest.readyState == 4) {
    if (tmRequest.status == 200) {
      var responseXml = tmRequest.responseXML;
      insertTestimonial(responseXml)
    } else {
      alert("The application is unable to communicate with the server to retrieve a testimonial. Response status: " + request.status + " " + request.statusText);
    }
  }
}

/* insertTestimonial Function
  Assembles a testimonial from XML and inserts it into the specified page element. */
function insertTestimonial(xmlDoc) {
  var root = xmlDoc.documentElement;
  var html = "";
  var nodes;
  var foundNode = null;
  if (root.hasChildNodes()) {
    nodes = xmlDoc.getElementsByTagName("Testimonial");
    if (nodes == null) {
      alert("Unable to assemble testimonial. The testimonials file contains no Testimonial nodes.")
    } else {
      nodeIx = Math.round(nodes.length * Math.random());
      if (nodeIx == nodes.length)
         nodeIx = nodes.length - 1;
      foundNode = nodes.item(nodeIx);
      if (foundNode == null) {
        alert("Unable to assemble testimonial. Selected testimonial index does not exist: " + nodeIx);
      } else {
        var tQuote = foundNode.getAttribute("Quote");
        var tAttrib = foundNode.getAttribute("Attribution");
        html = "<p><span>#" + (nodeIx + 1) +"</span>&quot;" + tQuote + "&quot;<span>" + tAttrib + "</span></p>";
      }
      // Load the assembled testimonial into the container:
      var container = document.getElementById(testimonialContainerId);
      if (container == null) {
        alert("Unable to assemble testimonial. Container [" + testimonialContainerId + "] not found on page.");
      } else {
      	if (html.length > 0) container.innerHTML = html;
      }
    }
  } else {
    alert("Testimonial xml file is empty.");
  }
}


