/**
 * jquery.fbwallposts.js jquery plugin 
 * @usage:  jQuery("#SELECTOR#").fbwallposts({fbHome:"http://facebuck.com/lookmyface",fbURL:"http://facebuck.com/id/23432342342/",usePics:true});
 * @description: Implants structured facebook wall posts into given jquery selector
 * @author: @mcn
 */
;(function(jQuery) {
	jQuery.fn.fbwallposts = function(options){
		var _this = jQuery(this);
		if (typeof(options) == 'undefined') {
			var options = {};
		}
		// initialize defaults
		var defaultOptions = {
				fbHome	: "#",
				fbURL 	: null,
				usePics : true
		};
		// override defaults
		for (var key in defaultOptions) {
			if (typeof options[key] == 'undefined') {
				options[key] = defaultOptions[key];
			}
		}
		/**
		 * Request the Facebook feed.
		 */
		var s = '';

		// Check for SSL protocol
		if (options.ssl) s = 's';
		var api = "http"+ s +"://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(options.fbURL);
		if (options.limit != null) api += "&num=" + options.limit;
		if (options.key != null) api += "&key=" + options.key;
		api += "&output=json_xml";
		jQuery.ajax({
		  url: api,
		  type: "GET",
		  data: {},
		  success: function(ret, status, httpRequest){
		  	var x, obj, appendItem, picture, link, mofLink, fromName, message;
			
		  	// Recombine each result.data members into a LI structure and append to given jQuery object. 
				var feedData= ret.responseData.feed.entries;
		  	for (x in feedData) {
		  		obj 		= feedData[x];
		  		message  	= (typeof obj.content   != "undefined") ? obj.content   : '';
		  		fromName 	= (typeof obj.author != "undefined") ? obj.author : '';
		  		picture 	= (typeof obj.picture   != "undefined" && options.usePics == true) ? '<img src="' + obj.picture + '" />' : '';
				
		  		/**
		  		 * 1) More on facebook link should alway point either to the article (obj.link) or
		  		 * back to the fbHome or # depending.
		  		 * 
		  		 * 2) If a picture exists, it should link to the article or to the home
		  		 */
		  		if (typeof obj.link != "undefined") {
		  			if (picture != '') {
		  				picture = '<a href="' + obj.link + '">' + picture + '</a>';
		  			}	
		  		}
		  		else {
		  			if (picture != ''){
		  				picture = '<a href="' + options.fbHome + '">' + picture + '</a>';
		  			}
		  		}
		  		mofLink 	= '<a href="' + options.fbHome + '">More on Facebook &raquo;</a>';
	  			
		  		// Append the item, one by one with rules above.
				appendItem 	= '<li class="fb-item"><strong>' + fromName + '</strong> <span class="fb-message">' + message + '</span><div class="fb-link">' + picture +'</div><div class="fb-more-link">' + mofLink + '</div></li>';	
				jQuery(_this).append(appendItem);
			}
		  	if (typeof postResultCallback == 'function') {
				postResultCallback();
			}
		  },
		  dataType: 'json'
		});
	};
})(jQuery);
 

