/*
 * FeedInjector - reads from an rss feed and populates an HTML element
 * requires prototype.js 1.6+
 *
 * url - path of the rss relative to the domain
 * elementID (optional, default = feed) - ID of the div that will contain the rss entries
 * maxEntries (optional, default = 5) - number of entries to display
 *
 * Usage:
 *
 * // For http://example.com/mysite/mysite.rss
 * var fi = new FeedInjector("/mysite/mysite.rss");
 * fi.load();
 */
function FeedInjector(url, elementID, maxEntries) {
	this.url = url;
	this.elementID = elementID;
	if (elementID == undefined) {
		this.elementID = "feed";
	}
	this.maxEntries = maxEntries;
	if (maxEntries == undefined) {
		this.maxEntries = 5;
	}
}

FeedInjector.prototype.load = function() {
	// Request the file on window load
	$(this.elementID).innerHTML = "";
	new Ajax.Request(this.url,
		{
			method: "get",
			onSuccess: this.inject.bind(this),
			onFailure: function (transport) {
			}
		});
}

FeedInjector.prototype.inject = function(transport) {

	feedText = transport.responseText;
	
	// Search for all entries
	var entries = new Array();
	var entryAdded = false;
	var re = new RegExp("<item");
	var index = feedText.search(re);
	do {
		var entry = new Object();
		$A(["title", "link", "description"]).each(function (entryAttribute) {
			// Find the open tag index
			re = new RegExp("<" + entryAttribute + ">");
			var entryBegin = feedText.substr(index).search(re);
			if (entryBegin != -1) {
				entryBegin += entryAttribute.length + 2;
				
				// Find the close tag index
				re = new RegExp("<\/" + entryAttribute + ">");
				var entryEnd = feedText.substr(index).search(re);
				entry[entryAttribute] = feedText.substr(index + entryBegin, entryEnd - entryBegin);
				index += entryEnd + entryAttribute.length + 3;
			}
		});
		
		entryAdded = (entry.title != undefined);
		if (entryAdded) {
			entries.push(entry);
		}
	} while (entryAdded && entries.length < this.maxEntries);
	
	// Add all of the entries (why does this.elementID go out of scope?)
	var elementID = this.elementID;
	$A(entries).each(function (entry) {
		var entryDiv = document.createElement("div");
        var description = entry.description;
        description = description.replace(/<!\[CDATA\[/, ""); 
        description = description.replace(/\]\]>/, ""); 
		entryDiv.innerHTML =
			"<div class=\"feedlink\"><a href=\"" + entry.link + "\">" + entry.title + "</a></div>" +
			"<div class=\"feeddesc\">" + description + "</div>";
		$(elementID).insert( { bottom: entryDiv } );
	});

}
