/**
* quoteview.js - loads a random quote from an XML document and refreshes a page element.
* author - Karl Martino
* license - do whatever you want with this...
*/

// set the following varibles to configure quoteview
var refreshSeconds = -1; // set to -1 to disable auto-refresh
var quoteViewEndPoint = 'http://www.terzoocchio.org/js/quoteview.xml'; // where to find the xml doc

// prepare the request object and set refresh period
var browser = navigator.appName;
var XMLRequestObject = false; // XMLHttpRequest Object
if (browser == "Microsoft Internet Explorer") {
  XMLRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  XMLRequestObject = new XMLHttpRequest();
}    
if (refreshSeconds > -1) {
  window.setInterval("update_timer()", refreshSeconds*1000); // update the data every 20 mins
}

/**
* Updates when XMLHttpRequest readystate changes.
*/
function reqChange() {

  // if data received correctly...
  if (XMLRequestObject.readyState==4) {   
    var quotes = new Array();   
    var node = XMLRequestObject.responseXML.documentElement;    
    var items = node.getElementsByTagName('item');
    for (var n=0; n < items.length; n++) {
      var itemQuote = items[n].getElementsByTagName('quote').item(0).firstChild.data;
      var itemSource = items[n].getElementsByTagName('source').item(0).firstChild.data;       
      quotes[n] = {source: itemSource, quote: itemQuote};
    }	
    
    // show a quote!
    changeQuote(quotes);
  }
	
}

/**
* Changes the quote that is displayed in the quoteview page element
*/
function changeQuote(quotes) {  

  var ranNum = Math.round(Math.random()*quotes.length+1);
  var quote = quotes[ranNum];
  var content = '<p class="quote">'+quote.quote+'</p><p class="quote-source">'+quote.source+'</p>';

  document.getElementById("quoteview").innerHTML = content;     
}

/**
* Starts the AJAX reader
*/
function quoteViewXmlRequest() {
 
  // let folks know we are doing something
  document.getElementById("quoteview").innerHTML = '<p class="quote">sto scegliendo una citazione per te ...</p>';

  XMLRequestObject.open("GET", quoteViewEndPoint , true);

  // set the onreadystatechange function
  XMLRequestObject.onreadystatechange = reqChange;

  // send
  XMLRequestObject.send(null); 
}

/*
* Runs at configured time
*/
function update_timer() {
  quoteViewXmlRequest();
}

