$(document).ready(function () {
	getMe2dayPosts('e2goon', 'div.me2day_posts');
});

function getMe2dayPosts(userid, selector) {
	$.getJSON('http://me2day.net/api/get_posts/' + userid +'.json?callback=?', function (posts) {
		var wrapper = $(selector),
			i = posts.length,
			post,
			html = ['</ul>'],
			content;
		
		while (i--) {
			post = posts[i];
			content = ['<li>', post.body, ' <a href="', post.permalink, '">', getTimesAgo(UTCToUnix(post.pubDate)), '</a></li>'];
			html.push(content.join(''));
		}
		html.push('<ul>');
		
		wrapper.append(html.reverse().join(''));
		

		function UTCToUnix(utc) {
			var exec = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/.exec(utc),
				unix = new Date(Date.UTC(parseInt(exec[1], 10), parseInt(exec[2], 10) - 1, parseInt(exec[3], 10), parseInt(exec[4], 10), parseInt(exec[5], 10), parseInt(exec[6], 10)));
			return unix.getTime() / 1000;
		}

		function getTimesAgo(timestamp) {
			var floor = Math.floor,
				now = new Date(),
				diff = Math.round(now.getTime() / 1000) - (now.getTimezoneOffset() * 60) - timestamp,
				years = floor(diff / 31536000),
				months = floor(diff / 2419200),
				weeks = floor(diff / 604800),
				days = floor(diff / 86400),
				hours = floor(diff / 3600),
				minutes = floor(diff / 60),
				seconds = diff,
				timesAgo;
			
			if (years > 0) {
				timesAgo = years + '년 전';
			} else if (months > 0) {
				timesAgo = months + '달 전';
			} else if (weeks > 0) {
				timesAgo = weeks + '주 전';
			} else if (days > 0) {
				timesAgo = days + '일 전';
			} else if (hours > 0) {
				timesAgo = hours + '시간 전';
			} else if (minutes > 0) {
				timesAgo = minutes + '분 전';
			} else {
				timesAgo = seconds + '초 전';
			}
			
			return timesAgo;
		}
	});
}