jQuery = jQuery.noConflict();

function facebookWall( id, accessToken, limit ){

var graphUser = 
'https://graph.facebook.com/'+id+'/?fields=name,picture&access_token='+accessToken+'&callback=?',
graphPosts = 
'https://graph.facebook.com/'+id+'/posts/?access_token='+accessToken+'&callback=?&date_format=U&limit='+limit;

var posts = new Array();

jQuery.getJSON(graphPosts, function(post){

	jQuery.each(post.data[0], function(key, value) {


			if( key == 'message'){
				posts.push(urlHyperlinks(value));
			}
		
			if(key == 'created_time'){
				posts.push(relativeTime(value*1000));			
			}

	});
	
	
	jQuery('<p>' + posts[0].substring(0,200) + '...</p>').appendTo('#fanpage');
	jQuery('<small>' + posts[1] + '</small>').appendTo('#fanpage p');
	
});

	// Helper functions:

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

	function relativeTime(time){
		
		// Adapted from James Herdman's http://bit.ly/e5Jnxe
		
		var period = new Date(time);
		var delta = new Date() - period;

		if (delta <= 10000) {	// Less than 10 seconds ago
			return 'Just now';
		}
		
		var units = null;
		
		var conversions = {
			millisecond: 1,		// ms -> ms
			second: 1000,		// ms -> sec
			minute: 60,			// sec -> min
			hour: 60,			// min -> hour
			day: 24,			// hour -> day
			month: 30,			// day -> month (roughly)
			year: 12			// month -> year
		};
		
		for (var key in conversions) {
			if (delta < conversions[key]) {
				break;
			}
			else {
				units = key;
				delta = delta / conversions[key];
			}
		}
		
		// Pluralize if necessary:
		
		delta = Math.floor(delta);
		if (delta !== 1) { units += 's'; }
		return [delta, units, "ago"].join(' ');
	}
			

}

jQuery(document).ready(function(){
	facebookWall('OneMethod', '306133069428843|qDe3OEXfvZH3USi3lVNJ2pWQgIo', 1 );
});
