$(function() {
	$.ajax({
		type: 'GET',
		dataType: 'json',
		url: '/json/user_timeline.json',
		cache: false,
		success:function(data, textStatus, XMLHttpRequest) {
			//console.log(data);
			$('#screen-name').wrap('<a href="http://twitter.com/#!/Kst_official" target="_blank"></a>')
			//$('#twitter-profile').prepend('<a href="http://twitter.com/intent/user?screen_name=Kst_official"><img src="' + data[0].user.profile_image_url.replace(/normal/gi,'mini') + '" width="24" height="24" /></a>');
			$.each(data, function(n) {
				html = '<div class="tweet">';
				html += '<p class="tweet-body">'+ this.text.linkify_tweet() +'</p>';
				html += '<p class="tweet-date"><a href="http://twitter.com/#!/Kst_official/status/'+this.id_str+'" title="'+this.created_at.gmt2str2()+'" target="_blank">'+ this.created_at.gmt2str() + '</a></p>';
				html += '</div>';
				$('#twitter-timeline').append(html);
			})
			$('#twitter-timeline').find('.tweet').last().addClass('last-child');
		},
		error:function(req, status, error) {
			//alert('error: '+status);
		}
	});
});

//tweet本文にリンクをつける
String.prototype.linkify_tweet = function() {
	var tweet = this.replace(/(s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:@&=+$,%#]+)/gi,'<a href="$1" target="_blank">$1</a>');
	tweet = tweet.replace(/#(\w+)/gi,'<a href="http://twitter.com/search?q=%23$1" target="_blank">#$1</a>');
	return tweet.replace(/@(\w+)/gi,'<a href="http://twitter.com/$1" target="_blank">@$1</a>');
};

//日付変換1 何分前
String.prototype.gmt2str = function(){
	var c = Date.parse(this);
	if (typeof c === 'number'){
		var n = new Date().getTime();
		var s = Math.floor((n-c) / 1000);
		if  	(s<60)  								return [s, '秒前'].join('');
		else if (s>=60 && s<60*60)  					return [Math.floor(s/60), '分前'].join('');
		else if (s>=60*60 && s<60*60*24)				return [Math.floor(s/60/60), '時間前'].join('');
		else if (s>=60*60*24 && s<60*60*24*30)  		return [Math.floor(s/60/60/24), '日前'].join('');
		else if (s>=60*60*24*30 && s<60*60*24*30*365)   return [Math.floor(s/60/60/24/30), 'ヶ月前'].join('');
		else if (s>=60*60*24*30*365)					return [Math.floor(s/60/60/24/30/365), '年前'].join('');
	}
};
//日付変換2 YYYY/MM/DD HH:MM
String.prototype.gmt2str2 = function(){
	var date = new Date(this);
	return date.getFullYear()+"/"+("0"+(date.getMonth()+1)).slice(-2)+"/"+("0"+date.getDate()).slice(-2)+" "+("0"+date.getHours()).slice(-2)+":"+("0"+date.getMinutes()).slice(-2);
};
