/**
 * jquery.wallposts.js jquery plugin 
 * @usage:  jQuery("#SELECTOR#").wallposts({fbHome:"http://facebuck.com/lookmyface",fbURL:"http://facebuck.com/id/23432342342/",usePics:true,feedSource:'Facebook'});
 * @description: Implants structured facebook wall posts into given jquery selector
 * @author: @mcn
 * To use:
 * 1) Make sure you've initialized the google apis, e.g. <script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAASMl8vuUglVI2CRxVxUTRsxQ7ufbiDB4daXd7WWlGJkApSnxRThQ9Nu_QWCu2wtzI3JECzRlzmnGHrg"></script>
 * 2) Set up facebook or twitter URLs appropriately, and pass as shown above
 * Currently implemented, sources 'Facebook' and 'Twitter' (case sensitive)

 */
function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}

function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a href='$1'>$1</a>"); 
}


;(function(jQuery) {
	google.load("feeds", "1");
	
	jQuery.fn.wallposts = function(options){
		var _this = jQuery(this);
		if (typeof(options) == 'undefined') {
			var options = {};
		}
		// initialize defaults
		var defaultOptions = {
				fbHome	: "#",
				fbURL 	: null,
				usePics : true,
				feedSource : 'Facebook',
				numEntries : 21,
				findTitle : '',
				replaceTitle : ''
		};
		// 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;
				
				if(options.feedSource == 'Twitter'){
					// START TWITTER FEED
					var feed = new google.feeds.Feed(options.fbURL);
					feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
					feed.setNumEntries(options.numEntries);
					
					feed.load(function(result) {
						var xmldoc = result.xmlDocument;
						if (xmldoc == null) return;
						var title,link,twittersource,description,guid,dcdate,pubdate,li;
						var items = xmldoc.getElementsByTagName('item');
						
						for (var i = 0; i < items.length; i++) {
							title				= html_entity_decode(items[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
							title		 		= title != 'undefined' ? title.replace(options.findTitle, options.replaceTitle) : '';							
							link				= items[i].getElementsByTagName('link')[0].childNodes[0].nodeValue;
							pubDate			= items[i].getElementsByTagName('pubDate')[0].childNodes[0].nodeValue;
							description	= items[i].getElementsByTagName('description')[0].childNodes[0].nodeValue;
							
							// Make @user become a link
							description 				= description.replace(/\@(\w+)/gi, '<a class="twitter-user" href="http://twitter.com/$1">@$1</a>');							
							li 		  						= '\
								<li class="twitter-item">\
									<div class="twitter-title">\
										<a href="' + link + '">' + title + '</a>\
									</div>\
									<div class="twitter-description">' + description + '</div>\
									<div class="twitter-pubDate">' 		 + pubDate 			+ '</div>\
								</li>';
							
							//li = li.replace(/>/g, "&gt;");
							//li = li.replace(/</g, "&lt;");

							jQuery(_this).append(replaceURLWithHTMLLinks(li));
							
						}
						if (typeof postResultCallback == 'function') {
							postResultCallback();
						}
					});   	//feed.load()
					// END TWITTER FEED	
				} else {
					// START FACEBOOK FEED
					// 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 + '" target="_blank">' + picture + '</a>';
							}	
						}
						else {
							if (picture != ''){
								picture = '<a href="' + options.fbHome + '" target="_blank">' + picture + '</a>';
							}
						}
						mofLink 	= '<a href="' + options.fbHome + '" target="_blank">More on Facebook &raquo;</a>';
						
						message = message.replace(/<a href="\//g,'<a target="_blank" href="http://www.facebook.com/');
						
						// Append the item, one by one with rules above.
					appendItem 	= '<li class="fb-item"><strong>' + html_entity_decode(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);
 

