var color = 1;

function loadQuote()
{
	var url = 'get_quote.new.php';
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				onComplete: showResponse,
				onFailure: reportError
			});
}

function showResponse(originalRequest)
{
	var xml = originalRequest.responseXML;
	
	var quote;
	var speaker;
	var position;
	var organization;
	var date;
	
	try{
		quote = xml.getElementsByTagName("text")[0].firstChild.nodeValue;
	}
	catch(err){
		quote = "";
	}
	try{
		speaker = xml.getElementsByTagName("speaker")[0].firstChild.nodeValue;
	}
	catch(err){
		speaker = "";
	}
	try{
		position = xml.getElementsByTagName("position")[0].firstChild.nodeValue;
	}
	catch(err){
		position = "";
	}
	try{
		organization = xml.getElementsByTagName("organization")[0].firstChild.nodeValue;
	}
	catch(err){
		organization = "";
	}
	try{
		date = xml.getElementsByTagName("date")[0].firstChild.nodeValue;
	}
	catch(err){
		date = "";
	}
	
	var speaker_text = speaker;
	if(position != "")
	{
		speaker_text += ", " + position;
	}
	if(organization != "" || date != "")
	{
		speaker_text += "<br />\n";
	}
	if(organization != "")
	{	
		speaker_text += organization;
		if(date != "")
		{
			speaker_text += ", ";
		}
	}
	if(date != "")
	{
		speaker_text += date;
	}
	if(organization != "" || date != "")
	{
		speaker_text += "\n";
	}
	
	var lines = quote.length / 85;
	var text_size = 16;
	if(lines > 5 && lines < 8)
		text_size = 14;
	else if(lines > 7)
		text_size = 12;
	
	var html = "<div class=\"color" + color + "\">\n";
	html += "\t<div id=\"quote-text\" style=\"font-size: " + text_size + "px;\">\n";
	html += "\t\t\"" + quote + "\"\n";
	html += "\t</div>\n";
	if(lines < 6)
		html += "<br />\n";
	html += "\t<div id=\"quote-speaker\">\n";
	html += "\t\t" + speaker_text + "\n";
	html += "\t</div>\n";
	html += "</div>\n";

	$('header-right').innerHTML = html;
	if(color >= 3 || color < 1)
	{
		color = 1;
	}
	else
	{
		color++;
	}
}

function reportError(request)
{
	$('header-right').innerHTML = "Sorry. There was an error loading the quotes.";
}

function runQuotes()
{
	loadQuote();
	setInterval("loadQuote()",(12*1000));
}