// Creating our plugin.

(function($){

	$.facebookWall = function(options){

		options = options || {};

		if(!options.id){
			throw new Error('You need to provide an user/page id!');
		}

		// Default options of the plugin:

		options = $.extend({
			limit: 15	// You can also pass a custom limit as a parameter.
		},options);

		// Putting together the Facebook Graph API URLs:

		var graphUSER = 'http://graph.facebook.com/'+options.id+'/?fields=name,picture&callback=?',
			graphPOSTS = 'http://graph.facebook.com/'+options.id+'/posts/?access_token='+options.access_token+'&callback=?&date_format=U&limit='+options.limit;

		var wall = this;

		$.when($.getJSON(graphUSER),$.getJSON(graphPOSTS)).done(function(user,posts){

			// user[0] contains information about the user (name and picture);
			// posts[0].data is an array with wall posts;

			var fb = {
				user : user[0],
				posts : []
			};

			$.each(posts[0].data,function(){

				// We only show links and statuses from the posts feed:
				if(this.type != 'link' && this.type!='status'){
					return true;
				}

				// Converting URL strings to actual hyperlinks:
				this.message = urlHyperlinks(this.message);

				fb.posts.push(this);
			});

		});

		return fb.posts;
	};

	// Helper functions:

	function urlHyperlinks(str){
		return str.replace(/\b((http|https):\/\/\S+)/g,'<a href="$1" target="_blank">$1</a>');
	}

})(jQuery);
