(function($){
	var options = {
			loaderClass: 'loading', // Class set to the container while loading feed
			maxItems: 5, // Maximum number of items shown
			urlTemplate: 'https://graph.facebook.com/%FB_USERID%/feed?%FB_DATA%', // URL template
			userId: '', // FB user id
			
			// Wrapper elements
			wrappers: {
				item: '<div />',
				author: '<strong />'
			},
			
			// Filtering function
			filter: function(item){
				return true;
			},
			
			// Error handler function
			errorHandler: function(data, status, xhr){
				if(context !== null){
					$(context).html('<div class="error">FB Error: ' + status + '</div>');
				};
			},
			
			// Function executed when everything is done
			onFinish: function(){}
		},
		context = null;
	
	// Output feed data (created DOM nodes are appended to the container one at a time => BAD!)
	function outputData(data){
		context.empty();
		context.removeClass(options.loaderClass);
		
		for(var i = 0, passed = 0, len = data.data.length; i < len && passed < options.maxItems; i++){
			var item = data.data[i];
			
			if(options.filter(item)){
				var itemWrapper = $(options.wrappers.item),
					authorWrapper = $(options.wrappers.author);
				
				if(item.message){
					$(itemWrapper).text(' ' + item.message);
				};
				
				if(item.from){
					$(authorWrapper).text(item.from.name);
					$(itemWrapper).prepend(authorWrapper);
				};
				
				context.append(itemWrapper);
				passed++;
			}
		}
		
		options.onFinish.call(context);
	};
	
	// Construct the request URL
	function buildUrl(){
		return options.urlTemplate.replace(/%FB_USERID%/g, options.userId).replace(/%FB_DATA%/g, fb.data);
	};
	
	// Load feed (uses JSONP to bypass crossdomain limitations)
	function loadFeed(){
		var ajaxOptions = {
				url: buildUrl(),
				dataType: 'jsonp',
				success: function(data, status, xhr){
					outputData(data);
				},
				error: options.errorHandler
			};
			
		$.ajax(ajaxOptions);
	};
	
	
	$.fn.fbFeed = function(opts){
		$.extend(options, opts);
		context = $(this);
		
		context.addClass(options.loaderClass);
		
		loadFeed();
		
		return this;
	};
})(jQuery);
