/*	Simple Cross-Browser Javascript RSS Reader
	Based on the script Simple Javascript RSS Reader 1.0 written by Christoff Truter
	And revised for Cross-Browser and multiple feed support by Micheal Leavitt */

var theFeed = new Array();
var index = 0; // Index of feeds
var totalFeeds; // Number of feeds
var rssTitle; // HTML Element to contain title of RSS feed
var rssBody; // HTML Element to contain items of RSS feed
var items; // Items nodes
var totalItems; // Number of RSS items requested
var req; // HttpRequest
var xmlDoc; // DOM-compatible XML document
var errorMessage; // Error message
var errorDescription = "An unknown error occurred"; // Error Description

/* Get total feeds 
       then read the first */

function ProcessRSS(feeds) 
{
	theFeed = feeds;
	totalFeeds = theFeed.length;
	ReadRSS();
}



/* Replace all occurances of a string
  (Parameters) totalValue:'complete string' 
		oldValue:'value to be replaced' newValue:'value used for replace' */

function Replace(totalValue,oldValue,newValue,isPubDate)
{
	// Reformat the publish date for display in the website
	//    Use everything preceding the time and zone
	//    Find the first index of a colon (:) character and move two characters back to exclude the time from the substring
	if(isPubDate)
	{
		newValue = newValue.substr(0, newValue.indexOf(':')-2);	
	}
	// If the old value wrapped in parenthesis doesn't return a result 
	//     then try the url encoded characters for left and right parenthesis
	//     this is needed for at least Firefox
	oldValue = (totalValue.indexOf("("+oldValue+")") > -1) ? "("+oldValue+")" : "%28"+oldValue+"%29";
	// Replace all matches of the old value with the new value
	while(totalValue.indexOf(oldValue) > -1)
		totalValue=totalValue.replace(oldValue,newValue);
			return totalValue;
}

/* Get XML Node
   (Parameters) TagName:'XML Element' node:'Element row number' */

function getNode(TagName, node)
{
	var currentNode = (node == null) ? xmlDoc.getElementsByTagName(TagName) : 
					items[node].getElementsByTagName(TagName);
	if(currentNode.length > 0)
		return currentNode[0].firstChild.nodeValue;
}

/* Load XML Object
   (Parameters) rssFeed:'RSS File' Body:'Layer for RSS Body' Title:'Layer for RSS Title' */

function ReadRSS() 
{
	rssTitle = document.getElementById(theFeed[index][2]);	
	rssBody = document.getElementById(theFeed[index][1]);
	totalItems = theFeed[index][3];
	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
			errorMessage = e.message;
			errorDescription = "Apparently one cannot read remote xml via firefox, please copy the file to your server";
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
				errorMessage = e.message;
				errorDescription = "Check Browser and security settings";
        	}
		}
    }
	if(req) {
		req.onreadystatechange = processReqChange;
		req.open("GET", theFeed[index][0], true);
		req.send("");
	} else {
		rssTitle.innerHTML = 'Error occured';
		rssBody.innerHTML = 'Thrown Error:'+errorMessage+"<br/>Note: "+errorDescription;
	}
}

function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
			xmlDoc = req.responseXML;
			items=xmlDoc.getElementsByTagName('item');
			SetRSSTemplates(totalItems);
        } else {
            alert("There was a problem retrieving the RSS data.");
        }
    }
}

/* Set HTML Template
	Did it this way to make the look and feel of the feed easy customizable, dont like mixing
	layout with code. */

function SetRSSTemplates()
{
	
	if (!totalItems || totalItems > items.length)
	{
		totalItems = items.length;
	}
	
	if (rssBody)
	{
		var buffer = "";
		for(var i=0; i<totalItems; i++) 
		{
			var output = Replace(rssBody.innerHTML,"::Link::",getNode('link',i));
			output = Replace(output,"::Title::",getNode('title',i));
			output = Replace(output,"::Pubdate::",getNode('pubDate',i),true);
			output = Replace(output,"::Description::",getNode('description',i));
			buffer+=output;
		}
		rssBody.innerHTML = buffer;
	}

	if (rssTitle)
	{
		var output = Replace(rssTitle.innerHTML,"::Title::",getNode('title'));
		output = Replace(output,"::Link::",getNode('link'));		
		output = Replace(output,"::Description::",getNode('description'));
		rssTitle.innerHTML = output;
	}
	
	index++;
	
	if(index < totalFeeds)
	{
		ReadRSS();
	}
}
