


(function($){
	var RSS_URL = 'http://www.firemansfund.com/servlet/rss?c=about&rkey=1477';
	

	/*
		Manages functionality for the news module content. Content is loaded from an RSS feed
		and parsed into HTML
	*/
	$.fn.newsFeed = function (url) {
		return $(this).each(function () {
			var el = $(this);
			
			var dummyEl = $('<div />');
			function getEscapedNodeValue(el, tagName) {
				// Escape HTML using jQuery's text function, then get the escaped HTML from the element
				var subEls = el.getElementsByTagName(tagName);
				if (subEls && subEls.length) {
					var subEl = subEls[0];
					var text = subEl.textContent || subEl.text;
					if (text) {
						return dummyEl.text(text).html();
					}
				}
				return '';
			}
			
			function showContent() {
				el.css('display', 'block');
			}
			
			try
			{
				// Make the AJAX call to get the RSS feed
				$.ajax({
					dataType : 'xml',	// Returns the data payload as an XMLDocument
					url : url,			// RSS feed url to GET
					
					// AJAX error handler
					error : function (XMLHttpRequest, textStatus, errorThrown) {
						// Show content, original content will still be there
						showContent();
					},
					// AJAX success handler
					success : function (data, textStatus) {
						try
						{
							var items = data.getElementsByTagName('item');
							var html = [];
							var itemsParsed = 0; // Count successful parses
							
							// Parse first 2 successful items
							for (var i = 0; itemsParsed < 3 && i < items.length; i++)
							{
								var item = items[i];
								
								var title = getEscapedNodeValue(item, 'title');
								var description = getEscapedNodeValue(item, 'description');
								var linkUrl = getEscapedNodeValue(item, 'link');
								
								if (title && description && linkUrl) {
									/*
									<div>
										<h3>{title}</h3>
										<p>
											{description}
											<br />
											&gt;<a href="{linkUrl}">More</a>
										</p>
									</div>
									*/
									
									html.push('<div><p class=\"newsTitle\"><strong>');
									html.push(title);
									html.push('</strong>');
									
									html.push('<p class=\"newsDescription\">');
									html.push(description);
									html.push('<br />&gt;<a href="');
									html.push(linkUrl);
									html.push('">More</a></p></div>');
									
									itemsParsed++;
								}
							}
							
							if (itemsParsed) {
								el[0].innerHTML = html.join('');
							}
						} catch (e) {
							// Set visiblity to visible below, will show default content
						}
						showContent();
					}
				});

			} catch (e) {
				// Show content, original content will still be there
				showContent();
			}
		});
	};
	
	$(document).ready(function () {
		$('#sidebar2').newsFeed(RSS_URL);
	});
})(jQuery); 
