/* 文字コードはUTF-8 */
twitter_usertimeline = function(){
	this.init = function(tid, type, keyword){
		var limit = (typeof(arguments[3]) != 'undefined' ? arguments[3] : 10);
		var link_type = (typeof(arguments[4]) != 'undefined' ? arguments[4] : '_self');
		var dateobj = new Date();
		var now = dateobj.getTime();
		var tobj = $('#' + tid).eq(0);
		tobj.html('<div class="message">読込中...</div>');
		var url = (type == 'user' ? 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + keyword + '&include_rts=true&count=' + limit + '&callback=?' : 'http://search.twitter.com/search.json?q=' + encodeURIComponent(keyword) +'&rpp=' + limit + '&callback=?');
		$.getJSON(url, function(json) {
			var html = '';
			tobj.css('display', 'none');
			var length = (type == 'user' ? json.length : json.results.length);
			if(length > 0){
				var count = json.length;
				html += '<ul>';
				var result = (type == 'user' ? json : json.results);
				$.each(result, function(i,item){
					var status = item.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) { return '<a href="'+url+'" target="'+link_type+'">'+url+'</a>'; }).replace(/\B@([_a-z0-9]+)/ig, function(reply) { return reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'" target="'+link_type+'">'+reply.substring(1)+'</a>'; }).replace(/\B#([_a-z0-9]+)/ig, function(reply) { return '<a href="http://twitter.com/search/'+encodeURIComponent(reply)+'" target="'+link_type+'">'+reply+'</a>'; });
					if(type != 'user'){
						status = '<a href="http://twitter.com/' + item.from_user + '" target="'+link_type+'">' + item.from_user + '</a> ' + status;
					}
					var values = item.created_at.split(' ');
					var pubtime = Date.parse(type == 'user' ? values[1] + " " + values[2] + ", " + values[5] + " " + values[3] : item.created_at);
					dateobj.setTime(pubtime);
					var year = dateobj.getFullYear();
					var month = dateobj.getMonth() + 1;
					var day = dateobj.getDate();
					var date_str = year + '.' + (month < 10 ? '0' : '') + month + '.' + (day < 10 ? '0' : '') + day;
					var class_name = (i == 0 ? 'first' : ((limit - i) == 1 ? 'last' : ''));
					if(now - pubtime < 86400000){
						class_name += (class_name != '' ? ' ' : '') + 'new';
					}
					html += '<li' + (class_name != '' ? ' class="' + class_name + '"' : '') + '>' + date_str + ' ' + status + '</li>';
					if((limit - i) == 1){
						return false;
					}
				});
				html += '</ul>';
			}
			else{
				html += '<div class="message">現在、準備中です。</div>';
			}
			tobj.html(html);
			tobj.slideDown('fast');
		});
	}
}

