// for blogs -- URL should be to RSS2.0 feed
function getLatestBlogEntries(url,numEntries,options)
{
  if(numEntries == null || isNaN(numEntries))
  {
    numEntries = 5;
  }

  $.ajax({
    type: 'GET',
    url: url,
    dataType: 'xml',
    success: function(data, textStatus) { showLatestBlogEntries(data, textStatus, numEntries, options); },
		error: function(XMLHttpRequest, textStatus, errorThrown) { showError(options); } 
  });
}

// expects RSS2.0 feed
function showLatestBlogEntries(data, textStatus, numEntries, options)
{
	if(options == null)
	{
		options = {};
	}
	
	if(options.showTitle == null) { options.showTitle = true; }
	if(options.showMoreLink == null) { options.showMoreLink = true; }
	if(options.showDate == null) { options.showDate = false; }
	options.htmlFilter = options.htmlFilter || false;
	
	var html = '';
	
	if(options.showTitle == true)
	{
		var html = '<h3>' + $(data).find('channel > title').text() + '</h3>';
	}

	html += '<ul>';

  var entries = $(data).find('item');
  if(entries.length < numEntries)
  {
    numEntries = entries.length;
  }

	// add li class="first" to first li
  for(var i = 0; i < numEntries; i++)
  {
    var e = $(entries[i]);
		if(i == 0)
		{
			html += '<li class="first">';
		}
		else
		{
			html += '<li>';
		}
    html += '<a href="' + e.find('link').text() + '" target="_parent">' + $(entries[i]).find('title').text() + '</a>';
		
		if(options.showDate != false)
		{
			html += ' <span>' + getFeedDate(e.find('pubDate').text()) + '</span>';
		}
		
		html += '</li>';
  }
  html += '</ul>';
	
	if(options.showMoreLink != false)
	{
		html += '<a class="more" target="_parent" href="' + $(data).find('channel > link').text() + '">More</a>';
	}

  if(typeof(options.htmlFilter) == 'function')
  {
    html = options.htmlFilter(html);
  }
	
	if(typeof(options.entryListEl) != null)
	{
		options.entryListEl.prepend($.trim(html));
	}
	else
	{
		document.write($.trim(html));
	}
}

function showError(options)
{
	var html = '<h3>Error</h3>';
	html += '<ul><li>Sorry, but an error occurred when retrieving the latest blog entries.';
	html += '</li></ul>';
	
	if(options.entryListEl != null)
	{
		options.entryListEl.html(html);
	}
	else
	{
		document.write(html);
	}
}

function getFeedDate(rssDate)
{
	// e.g.
	// Tue, 28 Oct 2008 06:00:00 -0500
	// to 10/28/2008
	
	var d = rssDate.split(' ');
	var months =
	{
		'Jan' : '1',
		'Feb' : '2',
		'Mar' : '3',
		'Apr' : '4',
		'May' : '5',
		'Jun' : '6',
		'Jul' : '7',
		'Aug' : '8',
		'Sep' : '9',
		'Oct' : '10',
		'Nov' : '11',
		'Dec' : '12'
	}
	
	var numMonth = months[d[2]];
	var dt = numMonth + '/' + d[1] + '/' + d[3];
	
	return dt;	
}