(function($){
	$.fn.facebook_feed = function(options) {

		var defaults = {
			nb: 5,
			profile: 168188903247324,
			markup: "{{if msg}}\n\
                                <li class='${borderClass} {{if picture}}withpic{{/if}}'>\n\
                                <div class='entry'>\n\
                                    <div class='txt'>\n\
                                        <h2><a target='_blank' href='${from.link}' title='${from.name}'>\n\ ${from.name}</a></h2>\n\
                                        {{if picture}}\n\
                                        <div class='img'><a target='_blank' href='${link}'><img src='${picture}' alt='' /></a></div>\n\
                                        {{/if}}{{if msg}}<p>{{html msg}}</p>{{/if}}</div><div class='clear'></div>\n\
                                        <p class='metas'>{{if type!='status'}} <img src='${icon}' alt='${type}' title='${type}' /> \n\
                                    {{/if}}<small>${date}</small>{{if likes}} <img src='scripts/facebook/img/thumb-up.png' alt='likes' /> \n\
                                    <small>${likes[1]}</small></p>{{/if}}</div><div class='clear'>\n\
                                </div>\n\
                                </li>{{else}}{{if picture}}\n\
                                <li class='${borderClass} {{if picture}}withpic{{/if}}'>\n\
                                <div class='entry'>\n\
                                    <div class='txt'>\n\
                                        <h2><a target='_blank' href='${from.link}' title='${from.name}'>\n\ ${from.name}</a></h2>\n\
                                        {{if picture}}\n\
                                        <div class='img'><a target='_blank' href='${link}'><img src='${picture}' alt='' /></a></div>\n\
                                        {{/if}}{{if msg}}<p>{{html msg}}</p>{{/if}}</div><div class='clear'></div>\n\
                                        <p class='metas'>{{if type!='status'}} <img src='${icon}' alt='${type}' title='${type}' /> \n\
                                    {{/if}}<small>${date}</small>{{if likes}} <img src='scripts/facebook/img/thumb-up.png' alt='likes' /> \n\
                                    <small>${likes[1]}</small></p>{{/if}}</div><div class='clear'>\n\
                                </div>{{/if}}{{/if}}",
			loadmore: true,
			replaceMore: false,
			dateFormat: "d/m/Y",
			allowOtherPosts: false,
			access_token: 'AAAEnMomgoDYBAH0HSRU3wHdkV9696VNbwyEKe94Pux4dZBmZA3e76bPISnbDDE9hUsPN6jOrW7Elwskuy19HdwrUPVLf0ZD',
			messages:{
				nodata: "Pas de donnée disponible.",
				notmore: "Pas de message supplémentaires.",
				loadmore: "charger plus",
				notfound: "page non trouvée"
			}
		};
				
		var options = $.extend(defaults, options);
		var authorData = {}, feeds = [], loadedTimes = 0, profile_url = "http://www.facebook.com/profile.php?id=", graph_url = "https://graph.facebook.com/", max_elts = 25, nb_elts = options.nb, currentNb = max_elts, prevPage, currentPage, nextPage, error = false;
		
		var processFeedData = function(feed)
		{
			if(!feed.error)
			{
				if(feed.data.length > 0)
				{
					prevPage = feed.paging.previous.split("since=")[1].split("T")[0];
					nextPage = feed.paging.next.split("until=")[1].split("T")[0];
				
					$(feed.data).each(function(i, elt)
					{
						var data = {};
						
						data.picture = elt.picture;
						
						if(elt.to)
							data.to = elt.to.data;
							
						data.link = elt.link;
						data.icon = elt.icon;
						data.type = elt.type;

						var nb = i;
						if(nb_elts%2 == 0)
							nb++;
							
						className = (nb%2 == 0)?"odd":"even";
						data.borderClass = className+" new";
						if(nb_elts == options.nb || options.replaceMore) data.borderClass += ((i==0)?" first":(i==(options.nb-1))?" last":"");
						
						if(elt.likes)
							data.likes = new Array(elt.likes.data, elt.likes.count);
							
						if(elt.comments)
							data.comments = elt.comments.count;
						
						if(elt.from)
						{
							data.from = elt.from;
							data.from.picture = graph_url+elt.from.id+"/picture";
							data.from.link = profile_url+elt.from.id;
						}
						
						date = elt.created_time.substr(0,10).split("T")[0].split("-");
						date = options.dateFormat.replace("d", date[2]).replace("m", date[1]).replace("Y", date[0]);
						data.date = date;
						
						if(elt.message)
						{
							var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
							data.msg = elt.message.replace(exp,"<a href='$1'>$1</a>"); 
						}
						
						if(typeof(data.to) != "undefined")
						{
							for(i in data.to){
								if(data.to[i] != null && data.msg)
									data.msg = data.msg.replace(data.to[i].name, "<a href='http://www.facebook.com/profile.php?id="+data.to[i].id+"'>"+data.to[i].name+"</a>");
							}
						}
						
						feeds.push(data);
						
					});			
				}
				else
				{
					error = true;
					if(loadedTimes == 0)
						$(".facebook_feed").html("<p class='error'>"+options.messages.nodata+"</p>");
				}
			}
			else
			{
				$(".facebook_feed").html("<p class='error'>"+options.messages.notfound+"</p>");
			}
		}
		
		var getFeedData = function()
		{
			if(options.access_token != null && options.access_token != "")
			{		
				if(currentNb > 0)
				{
					params = "&offset="+(max_elts - currentNb);
				}
				else
				{
					currentNb = max_elts;
					
					params = "&offset=0";
					
					if(nextPage)
						currentPage = nextPage;
				}
				
				if(currentPage)
					until = "&until="+currentPage;
				else
					until = "";
					
				params += until;
				
				url = graph_url+options.profile+"/"+(options.allowOtherPosts?"feed":"posts")+"/"+"?limit="+options.nb+params+"&access_token="+options.access_token;
				
				return $.ajax({
					url: url,
					dataType: "jsonp",
					success: processFeedData
				});
			}
			else
			{
				$(".facebook_feed").html("<p class='error'>Access token missing</p>");
			}
		}
		
		var displayData = function(obj, replace)
		{
			$(".loader").remove();
			
			if(replace)
				obj.find("ul").html($.tmpl(options.markup, feeds));
			else
			{
				obj.find(".last").removeClass("last");
				obj.find("li.new").removeClass("new");
				$.tmpl(options.markup, feeds).appendTo(obj.find("ul"));
				obj.find("li:last-child").addClass("last");
				obj.find("ul li.new").hide().fadeIn();
			}
			
			nb_elts += options.nb;
			currentNb -= options.nb;
			
			obj.find("li img").load(function(){
				$(this).fadeIn("fast");	
			})
		}
		
		var loadMore = function(obj)
		{
			feeds = [];
			loadedTimes ++;
			
			$(".loadingmore", obj).append("<span class='loadingmore_loader'></span>");

			$.when(getFeedData())
				.then(function(){
					if(!error)
						displayData(obj, options.replaceMore);
					else
					{	
						if(!$(".info", obj).hasClass("info"))
							obj.append("<p class='info'>"+options.messages.notmore+"</p>");
						else
							$(".info", obj).html(options.messages.notmore);
					}
					
					$(".loadingmore_loader").remove();
				});
		}
				
		this.each(function(){
		
			var obj = $(this);
			
			obj.addClass("facebook_feed");
			obj.append("<div class='ul-wrapper'><div class='loader'></div><ul /></div>");
			obj.append("<p class='loadingmore'><input id='load-more' type='button' class='uibutton large special' value='"+options.messages.loadmore+"' /></p>");
			
			$("#load-more").click(function(){
				loadMore(obj);
			});
			
			if(options.profile != null && options.profile != "")
			{
				$.when(getFeedData())
					.then(function(){
						displayData(obj, false);
					})
					.fail(function(){
						
					});
				
			}
			else
				obj.html("<p class='error'>"+options.messages.notfound+"</p>");
			
		});
		
		return this;
	};
})(jQuery);
