/* Configuration: Don, I set up Tabs so if we ever want to do other rss feeds, we can just add a tab, and new attributes */

var tabs = {
	"CNN NEWS" : {
		"feed"		: "http://rss.cnn.com/rss/cnn_topstories.rss",
		"function"	: rss
	}
}

var totalTabs;
$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */
	
	/* Counting the tabs */
	totalTabs=0;
	$.each(tabs,function(){totalTabs++;})
	

	$('#feedWidget').show().mouseleave(function(){
		
	
	}).mouseenter(function(){
		
		if(totalTabs>1) $('#activeTab').addClass('hover');
		
	});

	
	/* Showing one of the tabs on load: */
	showTab('CNN NEWS');
	
});


function showTab(key)
{
	var obj = tabs[key];
	if(!obj) return false;
	
	var stage = $('#tabContent');
	
	/* Forming the query: */
	var query = "select * from feed where url='"+obj.feed+"' /* DON, this calls the amount of items we want listed */ LIMIT 5";
	
	/* Forming the URL to YQL: */
	var url = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(query)+"&format=json&callback=?";
	
	$.getJSON(url,function(data){

		stage.empty();

		/* item exists in RSS and entry in ATOM feeds: */
		$.each(data.query.results.item || data.query.results.entry,function(){
			try{
				/* Trying to call the user provided function, "this" the rest of the feed data: */
				stage.append(obj['function'](this));
				
			}
			catch(e){
				/* Notifying users if there are any problems with their handler functions: */
				var f_name =obj['function'].toString().match(/function\s+(\w+)\(/i);
				if(f_name) f_name = f_name[1];
				
				stage.append('<div>There is a problem with your '+f_name+ ' function</div>');
				return false;
			}
		})
	});
	
	$('#activeTab').text(key);
}


function rss(item)
{
	return $('<div>').html(
			formatString(item.title.description || item.title)+
			' <a href="'+(item.origLink || item.link[0].href || item.link)+'" target="_blank">[read story]</a>'
	);
}


function formatString(str)
{
	
	str = str.replace(/<[^>]+>/ig,'');
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	return str;
}

