
window.onload = attachFormHandlers;

//GLOBAL VARIABLES
var xml_number; //keep a track of which number XML file is being processed
var number_listed;
number_listed = 3; //set the total number of items that will be displayed from each XML file
var $outputHTML;

function attachFormHandlers()
{	
	if (document.getElementById)//make sure were on a newer browser
	{		
		getRSS(rss_list, '/rss-list.php', 'get_xml=1&type_id='+type_id);
	}
}

//PROCESSES
//uses xmlhttpreq to get the raw rss xml from location spcified in 'url' argument
//alternative data can be passed into the post vars using the 'data' arguemnt
//and then return to function specified in 'callback' argument
function getRSS(callback, url, data)
{
	var mozillaFlag = false;
	var XMLHttpRequestObject = false; 
	//call the right constructor for the browser being used		
	if (window.ActiveXObject) {
		XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
	}else if (window.XMLHttpRequest) {
		XMLHttpRequestObject = new XMLHttpRequest();
		//object only available to mozilla browsers
		if(XMLHttpRequestObject.overrideMimeType){
			XMLHttpRequestObject.overrideMimeType("text/xml");
			mozillaFlag = true;
		}else{
			//IE7
			XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	if(data){
		XMLHttpRequestObject.open("POST", url); 
		XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
	}else{
	//prepare the xmlhttprequest object
		XMLHttpRequestObject.open('GET',url,true);
		XMLHttpRequestObject.setRequestHeader("Cache-Control", "no-cache");
		XMLHttpRequestObject.setRequestHeader("Pragma", "no-cache");
	}
	
	XMLHttpRequestObject.onreadystatechange = function() {
		
		if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
		{
				
				if (XMLHttpRequestObject.responseText != null){
				
					var xmlDocument = XMLHttpRequestObject.responseXML;
					//debug, echo out the entire XML document;
					//alert(xmlDocument.xml)
					//remove all whitespace from XML file for mozilla browsers
					if(mozillaFlag){
						removeWhitespace(xmlDocument);
					}				
					
					if(callback(xmlDocument)){					
						document.getElementById('feedback').style.display = 'none';
						document.getElementById('rss_feeds').style.display = 'block';
					}
				}
				else
				{
					alert("Failed to receive RSS file from the server - file not found.");
					return false;
				}
			
		}else{
			document.getElementById('feedback').style.display = 'block';
			document.getElementById('rss_feeds').style.display = 'none';
			document.getElementById('feedback').innerHTML = 'Please wait while the page loads...<br /><br /><img src="/img/site/ajax-loader.gif" alt="Please wait while the latest news loads..." align="center" />';
		}
		
	}

	if(data){
		//send the request
		XMLHttpRequestObject.send(data);
	}else{
		//send the request
		XMLHttpRequestObject.send(null);
	}
}

function removeWhitespace(xml) 
{
    var loopIndex;

	for (loopIndex = 0; loopIndex < xml.childNodes.length; loopIndex++) {

		var currentNode = xml.childNodes[loopIndex];

		if (currentNode.nodeType == 1) {
			removeWhitespace(currentNode);
		}

        if (((/^\s+$/.test(currentNode.nodeValue))) &&   (currentNode.nodeType == 3)) {
        	xml.removeChild(xml.childNodes[loopIndex--]);
		}
	}
}

//get the list of RSS feeds and relative XML files from get_xml.php
function rss_list(xmldoc)
      {
	  	var displayText = "";
		var err_msg;
		var num_feeds = null;
		
		document.getElementById('rss_feeds').innerHTML = '';

		if(xmldoc){
			
			//get the number of matches from the XML file
			if(xmldoc.getElementsByTagName('feeds').length > 0){
				num_feeds = xmldoc.getElementsByTagName("feeds")[0].firstChild.nodeValue;
			}
			//alert(num_feeds);
			if(num_feeds > 0 && num_feeds != null){
				
				//get attrbutes from results node
				feed = xmldoc.getElementsByTagName("feed");
				
				for (feed_loopIndex = 0; feed_loopIndex < feed.length; feed_loopIndex++ )
				{
					
					if(feed[feed_loopIndex].getElementsByTagName("err_msg")[0].firstChild){
						err_msg = feed[feed_loopIndex].getElementsByTagName("err_msg")[0].firstChild.nodeValue;
					}
					
					if(err_msg == null){
						if(feed[feed_loopIndex].getElementsByTagName("name").length > 0){
							feed_name = feed[feed_loopIndex].getElementsByTagName("name")[0].firstChild.nodeValue;
						}
						if(feed[feed_loopIndex].getElementsByTagName("url").length > 0){
							xml_url = feed[feed_loopIndex].getElementsByTagName("url")[0].firstChild.nodeValue;
						}
						if(feed[feed_loopIndex].getElementsByTagName("file").length > 0){
							xml_file = feed[feed_loopIndex].getElementsByTagName("file")[0].firstChild.nodeValue;
						}
						
						//output XML using customised listing funciton
						getRSS(showRSS, xml_file);
					
					}else{
						/*//debug
						alert(err_msg);
						*/
					}
				}
				
			}else{
				//create results string
				displayText = "No RSS feeds could be found";
				document.getElementById('feedback').innerHTML = displayText;
				return false;
			}
		}else{
			//output message if no XML is returned
			displayText = "No response from the search server";
			document.getElementById('feedback').innerHTML = displayText;
			return false;
		}		
}


//shows the RSS content in the browser
function showRSS(xmldoc)
{
	//increment count to keep number of function calls
	if(xml_number == null){
		xml_number = 0;
	}else{
		xml_number++;
	}
	
	$outputHTML = null;
	$outputHTML = '<div class=\"channel\" id=\"chan_'+xml_number+'\">';
	
	//document.getElementById('rss_feeds').innerHTML += '<div class=\"channel\" id=\"chan_'+xml_number+'\">';					
	
	//default values for html tags used
	var imageTag = "<img id='chan_image'";
	var startItemTag = "<div id='item' class='item'>";
	var startTitle = "<div id='item_title' class='item'>";
	var startLink = "<div id='item_link' class='item'>";
	var startDescription = "<div id='item_description' class='item'>";
	var endTag = "</div>";
	
	//channel variables
	channel_title = null;
	channel_link = null;
	channel_description = null;
	
	//item variables
	item_title = null;
	item_link = null;
	item_description = null;

	//populate channel data
	channel = xmldoc.getElementsByTagName("channel");
	for (loopIndex = 0; loopIndex < channel.length; loopIndex++ )
	{
		if(channel[loopIndex].getElementsByTagName("title").length > 0){
			channel_title = channel[loopIndex].getElementsByTagName("title")[0].firstChild.nodeValue;
		}
		
		if(channel[loopIndex].getElementsByTagName("link").length > 0){
			channel_link = channel[loopIndex].getElementsByTagName("link")[0].firstChild.nodeValue;
		}
		
		//channel_description = channel[loopIndex].getElementsByTagName("description")[0].firstChild.nodeValue;
		if (channel[loopIndex].getElementsByTagName("description").length > 0)
		{
			channel_description = channel[loopIndex].getElementsByTagName("description")[0].firstChild.nodeValue;
			
			//alert(type_id);
			//dont want the channel_description title for the feed for type=2 as it contains a url and looks silly
			//for the FT World News financialtimes feed - so dont show it
			if (type_id == 2)
			{
				channel_description = null;
			}
			
		}
		//alert(title);

		if (channel_title != null && channel_link != null)
		{			
			/*if(channel_title && channel_link)
			{
				//handle the title & link node
				$outputHTML += '<div class=\"details\" id=\"chan_title\">';
				$outputHTML += '<a href=\"'+channel_link+'\" target=\"_blank\">'+channel_title+'</a>' + endTag;
				//document.getElementById('chan_'+xml_number+'').innerHTML += '<div class=\"details\" id=\"chan_title\">';
				//document.getElementById('chan_'+xml_number+'').innerHTML += '<a href=\"'+channel_link+'\" target=\"_blank\">'+channel_title+'</a>' + endTag;
			}*/
			
			//handle the description node
			if(channel_description && channel_title != null){
				$outputHTML += '<div class=\"details\" id=\"chan_description\">';
				$outputHTML += channel_description + endTag;
				//document.getElementById('chan_'+xml_number+'').innerHTML += '<div class=\"details\" id=\"chan_description\">';
				//document.getElementById('chan_'+xml_number+'').innerHTML += channel_description + endTag;
			}
		}		
		
	}
	
	
	//populate the items
	xml_item = xmldoc.getElementsByTagName("item");
	
	$outputHTML += '<div class=\"items\" id=\"chan_items_'+xml_number+'\">';
	
	//document.getElementById('chan_'+xml_number+'').innerHTML += '<div class=\"items\" id=\"chan_items_'+xml_number+'\">';
	
	for (loopIndex = 0; loopIndex < number_listed; loopIndex++ )
	{
		if(xml_item[loopIndex].getElementsByTagName("title").length > 0){
			item_title = xml_item[loopIndex].getElementsByTagName("title")[0].firstChild.nodeValue;
		}
		
		if(xml_item[loopIndex].getElementsByTagName("link").length > 0){
			item_link = xml_item[loopIndex].getElementsByTagName("link")[0].firstChild.nodeValue;
		}
		
		if(xml_item[loopIndex].getElementsByTagName("description").length > 0){
			item_description = xml_item[loopIndex].getElementsByTagName("description")[0].firstChild.nodeValue;
		}
		
		$outputHTML += startItemTag;
		item_html = startItemTag;
		
		if (item_link != null && item_title != null){			
			if(item_link && item_title){
				$outputHTML +=  startTitle + '<a href=\"'+ item_link +'\" target=\"_blank\">' + item_title + '</a>' + endTag;
				item_html += startTitle + '<a href=\"'+ item_link +'\" target=\"_blank\">' + item_title + '</a>' + endTag;
			}			
		}
		
		if(item_description && item_description != null){
			$outputHTML += startDescription + item_description + endTag;
			item_html += startDescription + item_description + endTag;
		}
		
		$outputHTML += endTag;
		item_html += endTag;
		
		//document.getElementById('chan_items_'+xml_number+'').innerHTML += item_html;
	}
	
	$outputHTML += endTag;
	//document.getElementById('chan_'+xml_number+'').innerHTML += endTag;
	
	$outputHTML += endTag;
	//document.getElementById('rss_feeds').innerHTML += endTag;
	
	//document.getElementById('rss_feeds').innerHTML += endTag;
	document.getElementById('rss_feeds').innerHTML += $outputHTML;
	//alert($outputHTML);
	//we're done
	//document.getElementById("chan").style.visibility = "visible";
	return true;
}

//function showFullRSS shows the entire RSS content in the browser
//must out to page with follwing XTHML
/*
	<div class="rss" id="chan">
		<div id="chan_title"></div>
		<div id="chan_link"></div>
		<div id="chan_description"></div>
		<a id="chan_image_link" href=""></a>
		<div id="chan_items"></div>
		<div id="chan_pubDate"></div>
		<div id="chan_copyright"></div>
	</div>
*/
function showFullRSS(RSS)
{
	//default values for html tags used
	var imageTag = "<img id='chan_image'";
	var startItemTag = "<div id='item'>";
	var startTitle = "<div id='item_title'>";
	var startLink = "<div id='item_link'>";
	var startDescription = "<div id='item_description'>";
	var endTag = "</div>";

	//populate channel data
	var properties = new Array("title","link","description","pubDate","copyright");
	for (var i=0; i<properties.length; i++)
	{
		eval("document.getElementById('chan_"+properties[i]+"').innerHTML = ''");
		curProp = eval("RSS."+properties[i]);
		if (curProp != null)
			eval("document.getElementById('chan_"+properties[i]+"').innerHTML = curProp");
	}

	//show the image
	document.getElementById("chan_image_link").innerHTML = "";
	if (RSS.image.src != null)
	{
		document.getElementById("chan_image_link").href = RSS.image.link;
		document.getElementById("chan_image_link").innerHTML = imageTag
			+" alt='"+RSS.image.description
			+"' width='"+RSS.image.width
			+"' height='"+RSS.image.height
			+"' src='"+RSS.image.url
			+"' "+"/>";
	}

	//populate the items
	document.getElementById("chan_items").innerHTML = "";
	for (var i=0; i<RSS.items.length; i++)
	{
		item_html = startItemTag;
		item_html += (RSS.items[i].title == null) ? "" : startTitle + RSS.items[i].title + endTag;
		item_html += (RSS.items[i].link == null) ? "" : startLink + RSS.items[i].link + endTag;
		item_html += (RSS.items[i].description == null) ? "" : startDescription + RSS.items[i].description + endTag;
		item_html += endTag;
		document.getElementById("chan_items").innerHTML += item_html;
	}

	//we're done
	//document.getElementById("chan").style.visibility = "visible";
	return true;
}

