jQuery(document).ready(function($) {
	
	newscount = 0;

	var fSort = function( a, b ) {
			
		/* /
		// Sort Ascending
		var x = $(a).find('date').text();
		var y = $(b).find('date').text();
		/* */

		/* */
		// Sort Descending
		var x = $(b).find('date').text();
		var y = $(a).find('date').text();
		/* */
		
		return ( ( x < y ) ? -1 : ( ( x > y ) ? 1 : 0 ) );
	}
					
	$('#newsxmlitem, #sidenewsxmlitem').hide();
	
	var bHasNewsXmlItem = $('#newsxmlitem').length ? true : false;
	
	// http://www.thetruetribe.com/2008/05/truncating-text-with-javascript/
	function truncate(text, length, ellipsis) {    
	
		// Set length and ellipsis to defaults if not defined
		if (typeof length == 'undefined') var length = 100;
		if (typeof ellipsis == 'undefined') var ellipsis = '...';
	
		// Return if the text is already lower than the cutoff
		if (text.length < length) return text;
	
		// Otherwise, check if the last character is a space.
		// If not, keep counting down from the last character
		// until we find a character that is a space
		for (var i = length-1; text.charAt(i) != ' '; i--) {
			length--;
		}
	
		// The for() loop ends when it finds a space, and the length var
		// has been updated so it doesn't cut in the middle of a word.
		return text.substr(0, length) + ellipsis;
	}
	
	
	$.get(
		'xml/news.xml',
		function( xml ) {
			$(xml).find('item').sort( fSort ).each(function() {
				
				var date = new Date();
				// alert( Date.parse( $(this).find('date').text() ) );
				date.setTime( Date.parse( $(this).find('date').text() ) );
				
				
				if ( bHasNewsXmlItem ) {
					var tmpl = $('#newsxmlitem').clone();
					tmpl.removeAttr('id');
					tmpl.find('h2').html( $(this).find('title').text() );
					tmpl.find('h4').html( date.format('dddd, mmmm d, yyyy') );
					tmpl.find('div.newscontent').html( $(this).find('content').text() );
					
					var link = $(this).find('link').text();
					if ( link ) {
						tmpl.find('p.newslink a').attr( 'href', $(this).find('link').text() );
					} else {
						tmpl.find('p.newslink').remove();
					}
					
					tmpl.show();
					
					$('#newsblock').append( tmpl );
				}
				
				if ( newscount < 2 ) {
					
					var tmpl = $('#sidenewsxmlitem').clone();
					tmpl.removeAttr('id');
					tmpl.find('h3').html( '<a href="news.html">' + $(this).find('title').text() + '<\/a>' );
					tmpl.find('h4').html( date.format('dddd, mmmm d, yyyy') );
					tmpl.find('p').html( $(this).find('content').text() );
					tmpl.find('p').html( truncate( tmpl.find('p').text(), 250, '...' ) );
					tmpl.show();
					
					$('#sidenewsblock').append( tmpl );
				}
				
				newscount ++;
				
			});
		}
	);
				
});

