/* ツイッター */
var TwitterClass = function (timeLineName, keyword, hashtag)
{
	this.timeLineName = timeLineName;
	this.timeLineID = "#" + timeLineName;
	this.keyword = keyword;
	this.hashtag = hashtag;
	this.openNum = showNum;
	
	/* クラス初期化 */
	this.init = function () {
		this.openNum = showNum;
		this.getTweet();
	};
	
	/* ツイート取得 */
	this.getTweet = function() {
		
		var timeLineName = this.timeLineName;
		var openNum = this.openNum;
		
		$.getJSON(api, {
				'action': 'get',
				'keyword': encodeURIComponent(this.keyword),
				'since_id': sinceIds[timeLineName]
			}, function(data) {
				showTimeLine(data, timeLineName, openNum);
			}
		);
		
	};
	
};

/* タイムライン表示 */
function showTimeLine(data, timeLineName, openNum) {
	
	var timeLineID = "#" + timeLineName;
	
	if (data != null && data.tweet.length > 0) {
		tweetLen = data.tweet.length;
		
		// since_id保存
		if (data.since_id != '') {
			sinceIds[timeLineName] = data.since_id;
		}
		
		jQuery.each(data.tweet, function() {
			if ($(timeLineID + " #" + this.id).length == 0) {
				$(timeLineID).prepend(makeHtml(this));
			}
		});
		$(timeLineID + " li a").attr({target: "_blank"});
		
		// 時間表示変換
		for (i = 0; i < $(timeLineID + " li").length; i++) {
			$(timeLineID + " li:eq("+i+") .timelink").text(jQuery.timeago($(timeLineID + " li:eq("+i+") .timelink").attr("title")));
		}
		
		
		// 表示アニメーション
		var i = openNum;
		if (openNum > tweetLen) {
			i = tweetLen;
		}
		
		$.timer(300, function(timer) {
			i --;
			
			$(timeLineID + " li:eq("+i+")").show('fast');
			if ($(timeLineID + " li:visible").length > openNum) {
				$(timeLineID + " li:visible:last").hide('fast');
			}
			
			if (i <= 0) {
				timer.stop();
				
				totalLen = $(timeLineID + " li").length;
				for (j = showMaxNum; j < totalLen; j++) {
					$(timeLineID + " li:last").remove();
				}
				
				visibleLen = $(timeLineID + " li:visible").length;
				countFlg = 0;
				for (j = openNum; j < visibleLen; j++) {
					$(timeLineID + " li:visible:last").hide('fast');
					countFlg++;
				}
			}
		});
		
		
	}
	
}

/* ツイートHTML */
function makeHtml(tweet) {
	var html = '';
	
	html += '<li class="boxHide" id="' + tweet.id + '">';
	html += '<dl class="clearfix">';
	html += '<dt><a href="' + tweet.author.uri + '"><img src="' + tweet.img + '" width="48" height="48" alt="' + tweet.author.name + '" /></a></dt>';
	html += '<dd>' + tweet.content + '<br /><a href="' + tweet.link + '" class="timelink" title="' + tweet.updated + '">' + tweet.updated + '</a></dd>';
	html += '</dl>';
	html += '</li>';
	
	return html;
}



$(document).ready(function() {
	
	/* タイムラインインスタンス */
	timeLines['timeLine_1'] = new TwitterClass('timeLine_1', querys['timeLine_1'], hashtags['timeLine_1']);
	
	/* タイムライン初期化 */
	timeLines['timeLine_1'].init();
	
	
	/* checkSpan毎に確認 */
	timers = $.timer(checkSpan, function (timer){
		timeLines['timeLine_1'].getTweet();
	});
	
});

