/*FB.init({
	clientId   : '108074319267637',
	status  : false,
	cookie  : true,
	xfbml   : true
});*/

$(function() {
	$("#FB_feed").facebookFeed({
		accessTokenUrl:"/fb.php?action=access_token",
		clientId:"108074319267637",
		clientSecret:"07c097ea3fa02f0dbac4ffa62e79a6f7",
		userId:"lutech"
	});
});


(function($, undefined){
	
	$.fn.facebookFeed = function(opts){
		var I = this,
			o = $.extend({}, defaults, opts),
			token;
		
		//Make sure we have our required options
		$.each(["clientId", "clientSecret", "userId"], function(i, optkey){
			if(!o[optkey]){
				throw "jQuery.facebookFeed requires the \""+optkey+"\" option.";	
			}
		});
		
		
		//Get the access_token
		$.ajax({
			url:o.accessTokenUrl,
			type:"post",
			data:{client_id:o.clientId, client_secret:o.clientSecret, grant_type:"client_credentials"},
			success:function(tokenResponse){
				//Add the token to the feed URL
				token = tokenResponse.replace("access_token=", "");
				I.trigger("access.facebookFeed", token);

				//Get the feed				
				var entriesParams = {
					limit:o.limit,
					access_token:token
				};
				
				$.getJSON("https://graph.facebook.com/"+o.userId+"/feed?"+$.param(entriesParams)+"&callback=?", function(json) {
					I.trigger("entries.facebookFeed", json);
					var $wrap = $(o.entriesWrap),
						//We do all this so that the buildItem option can return an HTML string, DOM element, or jQuery wrapped DOM element
						$items = $.map($.map(json.data, o.buildEntry), function(el, i){
							var $el = $(el);
							$wrap.append($el);
							return $el;
						});
					if(o.emptyContainer){
						I.empty();	
					}
					I.append($wrap);
					I.trigger("finish.facebookFeed", $items);
				});
				
				
			}
		});
		
		
		return this;		
	};
	
	
	var buildEntry = function(entry, i){

		var now = new Date(),
			msg,
			html = "<li>",
			autoLink = function(url){
				var a = url.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
					nice = url;
					if( url.match('^https?:\/\/') ) {
						nice = nice.replace(/^https?:\/\//i,'')
					} else
						url = 'http://'+url;
		
					return '<a href="'+ url +'" target="_blank">'+ nice.replace(/^www./i,'') +'</a>';
				});
				return a;
			}
		console.log(entry);
		if(entry.picture) {
			html += '<img src="'+entry.picture+'" class="picture" align="left"/>';
		}
		if(entry.link){
			html += '<a href="'+entry.link+'" class="link" target="_blank">';
		}
		html += '<span class="name">'+entry.name+'</span>';
		if(entry.link){
			html += '</a>';	
		}
		if((msg = entry.message || entry.description || entry.story)){
			msg = autoLink(msg);
			html += msg;
		}
		

		var updated = new Date();
		updated.setISO8601(entry.updated_time);
		var diff = now.getTime() - updated.getTime();
		var diff_hours = Math.round(diff/3600000);
		html += '<span class="updated_time">';
		if(diff_hours <= 1) {
			var diff_min = Math.round(diff/60000);
			html += diff_min.toString()+' minutes ago';
		} else if(diff_hours <= 24)
			html += diff_hours.toString()+' hours ago';
		else if(diff_hours <= 48)
			html += 'Yesterday at '+updated.format('g:i a');
		else if(diff_hours <= 168)
			html += updated.format('l \\a\\t g:i a');
		else
			html += updated.format('F j \\a\\t g:i a');
		html += '.</span>';

		html += "</li>";
		
		return html;
	};
	
	
	
	//Create the defaults for the plugin
	var defaults = $.fn.facebookFeed.defaults = {
		accessTokenUrl:"https://graph.facebook.com/oauth/access_token",
		clientId:null,
		clientSecret:null,
		userId:null,		
		limit:10,
		entriesWrap:"<ul/>",
		emptyContainer:true,
		buildEntry:buildEntry
	};
	
})(jQuery);
