$(document).ready(function(){

	if ($("#inTheNewsFeed").length > 0) {
		newsFeed("15", "#inTheNewsFeed");
	}
	if ($("#recentNewsFeed").length > 0) {
		newsFeed("2", "#recentNewsFeed");
	}

	function newsFeed(itemCount,target) {
		$(target).html(
			'<div style="text-align: center; padding-top: 100px" > \
				<img width="208" height="13" src="/images/loadingAnimation.gif" alt="Loading..."/> \
			</div>'
		);
		$.getJSON("http://feeds.delicious.com/v2/json/RTIINTL?callback=?&count="+itemCount, function(data){

			// setup abbreviations
			daysOfWeek=["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
			monthsOfYear=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
			
			// parse notes field in data object and setup a sortable date object and display date string for output

			$.each(data, function(i,item){
				item.sortDate = setupDateForSort(item.n,item.dt);
				item.displayDate = daysOfWeek[item.sortDate.getDay()] + ", " + monthsOfYear[item.sortDate.getMonth()] + " " + item.sortDate.getDate() + ", " + item.sortDate.getFullYear();
			});
			
			function setupDateForSort(itemDate,postedDate) {
				var regex = /^\d{2}\.\d{2}\.\d{4}$/;
				if (regex.test(itemDate)) {
					// reformat date for sorting
					year = itemDate.substring(6,10);
					month = itemDate.substring(0,2);
					day = itemDate.substring(3,5);
					
					var newDate = new Date();
					newDate.setDate(day);
					newDate.setMonth(month-1);
					newDate.setYear(year);
					newDate.setHours('00');
					newDate.setMinutes('00');
					newDate.setSeconds('00');
								
					return newDate;
				}
				else {
					return parseFeedDate(postedDate);
				}
			}

			function parseFeedDate(linkDate) {
				// parse date from feed
				year = linkDate.substring(0,4);
				month = linkDate.substring(5,7);
				day = linkDate.substring(8,10);
				hour = linkDate.substring(11,13);
				minute = linkDate.substring(14,16);
				second = linkDate.substring(17,19);
				var theDate = new Date();

				// set up date object
				theDate.setDate(day);
				theDate.setMonth(month-1);
				theDate.setYear(year);
				theDate.setHours(hour);
				theDate.setMinutes(minute);
				theDate.setSeconds(second);

				return theDate;
			}
			
			data.sort(function(item1,item2) {
				return item2.sortDate - item1.sortDate;
			});
			
			if (target == "#inTheNewsFeed") {			
				output = '<div>';

				$.each(data, function(i, item){
					paragraph = 
					'<p> \
						<span class="date">' + item.displayDate + '</span><br/> \
						<span class="storyTitle">' + item.d + '&nbsp; \
						<a href="' + item.u + '" target="_blank">View</a> \
					</p>';
					
					output += paragraph;
				});
			
				output += '</div>';
		
				$(target).fadeOut(500,function(){
						$(this).fadeOut(500).html(output).fadeIn(500,function(){	
							$("#inTheNewsFeed a").prepare_links();
						});
					});
				}
		});
	}

	
});