(function($) {
	
$.fn.feedmixer = function(options) {
	var defaults = {
		url: '',
		items: 10,
		length: 50,
		filter: '',
		title: 1,
		description: 0
	}
	if(!options.url) return false;
	var opts = $.extend(defaults, options);
	$(this).each(function(){
		var container = this;
		$.get(opts.url, function(xml){
			var posts = [];
			var i = 0;
			
			var feed_title = '';
			var feed_description = '';
			
			if (opts.title) $("channel > title", xml).each(function(){feed_title = '<h1>' + $(this).eq(0).text() + '</h1>'});
			if (opts.description) $("channel > description", xml).each(function(){feed_description = '<span>' +  $(this).eq(0).text() + '</span>'});
			
			$("item", xml).each(function(){
				if ( i > opts.items - 1) return;
				var title = '';
				var description = '';
				
				title = $(this).find('title').eq(0).text();
				description = $(this).find('description').eq(0).text();
								
				var re = new RegExp(opts.filter, "i");
				if (opts.filter != '' && ! (title.match(re) || description.match(re))) return;
				
				var post = {};
				post.title = title;
				post.description = sanitise(description, opts.length);						
				post.link = $(this).find('link').eq(0).text();
				post.date = $(this).find('pubDate').eq(0).text();
								
				posts[i++] = format(post);
			});
			
			if (opts.filter != '' && !i)
			{
				$(container).html(feed_title + feed_description + 'No Feed Available.');								
			}
			else
			{
				$(container).html(feed_title + feed_description + '<dl>' + posts.join('') + '</dl>');								
			}			
		})
	});	
};

function sanitise (text, length) {
	var t = text.replace(/\s/g,' ');
	var words = t.split(' ');
	if(words.length <= length) return text;
	var ret='';
	for(var i=0;i<length;i++){
		ret+=words[i]+' ';
	}
	return ret + '... ';
}

function format (post) {
	var html = '<dt><a href="' + post.link+'">' + post.title + '</a><br/><span class="date">' + post.date + '</span></dt>';
	html += '<dd>' + post.description + '<a href="' + post.link + '">More</a></dd>'
	return html;
}

})(jQuery);