(function ($) {

var self = $.twitter = {

/* //////////  CONFIG ////////// */
	
	//吹き出しのフェードインタイム
	popFadeInTime:  1000,
	
	//吹き出しのフェードアウトタイム
	popFadeOutTime: 1000,
	
	//スレッドの移動谷メーションタイム
	threadMoveTime: 750,
	
	//スレッドの表示アニメーションタイム
	threadShowTime: 750,
	
	//吹き出しの滞在時間
	stayTime:       6000,
	
	//吹き出しの表示間隔
	intervalTop:    3600,
	
	//スレッドの表示間隔
	intervalBV:     4500,
	
	//読み込むtweet件数
	loadTweetCount: 30,
	
	//検索クエリ
	searchQuery:    'to:bc_offical+OR+bc_official+OR+#bc2010',
	
	//「...」になるまでのpx
	maxWidth:       1000,
	
	//「...」になるまでのpx（IE6）
	maxWidthIE6:    800,
	
/* //////////  /CONFIG ////////// */	
	
	
	searchAPI: 'http://search.twitter.com/search.json?callback=?',
	tweetURL:  'http://twitter.com/home?status=',
	data:      [],
	index:     0,
	space:     [0, 1, 2],
	
	init: function () {
		this.load();
		
		if (self.isTop())
			self.hidePop();
		
		self.pngFix();
	},
	
	load: function () {
		var q = '&lang=all&rpp=' + self.loadTweetCount + '&q=' + escape(self.searchQuery);
		
		$.getJSON(self.searchAPI + q, function (json) {
	    $.each(json.results, function(i, item){
	    	self.data.push({
	    		profile_image_url: item.profile_image_url,
	    		from_user:         item.from_user,
	    		text:              item.text.replace(/\n/g, '&nbsp;'),
	    		created_at:        item.created_at
	    	});
	    });
	    
	    self.data.reverse();
	    
	    if (self.data.length)
		    self.timer();
		});
	},
	
	timer: function () {
		self.output(self.index);
		
		setInterval(function () {
			self.output(self.index);
		}, self.interval());
	},
	
	output: function (i) {
		if (self.isTop()) {
			var target  = $('#beatvoice ul');
	  	var balloon = $('<li><div></div></li>').css({opacity: 0.0}).addClass('position_' + self.position());
			
	  	balloon.find('div').append([
	  		'<img src="' + self.data[i].profile_image_url + '" width="40" height="40" alt="' + self.data[i].from_user + '" />',
	  		'<p><span><a href="http://twitter.com/@' + self.data[i].from_user + '" target="_blank">@' + self.data[i].from_user + '</a>&nbsp;&nbsp;&nbsp;</span>' + self.textFormat(self.tweetWidth(self.data[i].text)) + '</p>'
	  	].join(''));
	    
	    self.index++;
	    
	    if (self.data.length <= self.index)
	    	self.index = 0;
	    
	  	target.append(balloon);
	  	self.pop(balloon);
  	}
  	else {
  		var target = $('#beatvoice ul');
	  	var li     = $('<li></li>').css({opacity: 0.0, marginTop: '-104px'});
	  	
	  	li.append([
	  		'<img src="' + self.data[i].profile_image_url + '" width="40" height="40" alt="' + self.data[i].from_user + '" />',
	  		'<p><span class="name"><a href="http://twitter.com/@' + self.data[i].from_user + '" target="_blank">@' + self.data[i].from_user + '</a>：</span>' + self.textFormat(self.tweetWidth(self.data[i].text)) + '<br /><span>' + self.dateFormat(self.data[i].created_at) + '</span></p>'
	  	].join(''));
	  	
	    self.index++;
	    
	    if (self.data.length <= self.index)
	    	self.index = 0;
  		
  		target.prepend(li);
  		self.land(li);
  	}
	},
	
	pop: function (balloon) {
		balloon.animate({opacity: 1.0, top: '25px'}, self.popFadeInTime, function () {
			setTimeout(function () {
				balloon.animate({opacity: 0.0, top: '0px'}, self.popFadeOutTime, function () {
					self.space.push(parseInt(balloon.attr('class').replace(/position_/, '')));
					balloon.remove();
				});
			}, self.stayTime);
		});
	},
	
	land: function (li) {
		li.animate({marginTop: '0px'}, self.threadMoveTime, function () {
			li.animate({opacity: 1.0}, self.threadShowTime, function () {
				if (self.index > 10)
					$('#beatvoice ul li:last').remove();
			});
		});
		
	},
	
	interval: function () {
		if (self.isTop())
			return self.intervalTop;
		return self.intervalBV;
	},
	
	position: function(){
		var r      = Math.floor(Math.random() * self.space.length);
		var _space = [];
		var index;
		
		$(self.space).each(function (i, value) {
			(i == r) ? (index = value) : _space.push(value);
		});
		
		self.space = _space;
		return index;
	},
	
	tweetWidth: function (text) {
		var maxWidth = self.maxWidth;
		if (self.isIE6())
			maxWidth = self.maxWidthIE6;
		var width    = $('#bv_tweet_width');
		
		width.empty();
		width.text(text);
		
		if (width.width() > maxWidth)
		  for (var i = text.length-1; i >= 1; --i) {
		    var s = text.slice(0, i) + '...';
		    width.text(s);
		    if (width.width() <= maxWidth)
		    	return s;
		  }
		
		return text;
	},
	
	textFormat: function (string) {
		return string.replace(/(https?:\/\/[^\/: ...]+\.+[^\/: ...]+(\.*[^: ...]*)*)/g, '<a href="$1" target="_blank">$1</a>')
	},
	
	dateFormat: function (time) {
		var date     = new Date(time);
		var diff     = (((new Date()).getTime() - date.getTime()) / 1000);
		var day_diff = Math.floor(diff / 86400);
		
		if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31)
			return;
				
		return day_diff == 0 && (
					diff <  60    && "1分以内"     ||
					diff <  120   && "1分前" ||
					diff <  3600  && Math.floor(diff / 60) + "分前" ||
					diff <  7200  && "1時間前"   ||
					diff <  86400 && Math.floor(diff / 3600) + "時間前") ||
			day_diff == 1     && "昨日"    ||
			day_diff <  7     && day_diff + "日前" ||
			day_diff <  31    && Math.ceil( day_diff / 7 ) + "週間前";
	},
	
	location: function () {
		var url = location.href;
		return (function (url, scheme, host, port, path, query, hash) {
			return {
				url:    url,
				scheme: scheme,
				host:   host,
				port:   port,
				path:   path,
				query:  query,
				hash:   hash,
				root:   scheme + '://' + host + (port ? ':' + port : '')
			};
		}).apply(null, url.match(
			/^(https?):\/\/([^\/:]+):?([^\/]*)([^\?#]+)\??([^#]*)#?(.*)$/
		));
	},
	
	isTop: function () {
		return !(/^\/beatvoice\/$/.test(self.location().path));
	},
	
	isIE6: function () {
		return (/MSIE (\d)/.test(navigator.userAgent) && (parseFloat(RegExp.$1) < 7));
	},
	
	hidePop: function () {
		$('#bv_hide a').click(function () {
			if ($('#bv_pop:visible').size()) {
				$(this).addClass('hide');
				$('#bv_pop').hide();
				$('#footer').css({
					paddingTop:         '268px',
					backgroundPosition: 'left top'
				});
				
				if (self.isIE6())
					$('#footer').css({height: '302px'});
			}
			else {
				$(this).removeClass('hide');
				$('#bv_pop').show();
				$('#footer').css({
					paddingTop:         '72px',
					backgroundPosition: 'left bottom'
				});
				
				if (self.isIE6())
					$('#footer').css({height: '106px'});
			}
			
			return false;
		});
		
	},
	
	pngFix: function (_el) {
		if (self.isIE6()) {
			var filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader';
			var src;
			
			if (_el) {
				var el = _el;
				var style = el.get(0).currentStyle.backgroundImage || el.get(0).style.backgroundImage;
				if (/^url\(["']?(.+\.png)["']?\)$/i.test(style))
					src = RegExp.$1;
				
				if (src) {
					el.css({
						background: 'none',
						filter:     filter + '(src="' + src + '", sizingMethod=scale)'
					});
					if (el.is('a'))
						el.css({ cursor: 'pointer' });
				}
			}
			else {
				$('.png').each(function () {
					var el = $(this);
					if (el.is('img') && /\.png$/i.test(this.src)) {
						src = this.src;
						el.wrap('<span><span>');
						el = el.parent().css({
							height:  el.height(),
							width:   el.width(),
							display: 'inline-block'
						});
						el.find('img').remove();
					}
					else {
						var style = this.currentStyle.backgroundImage || this.style.backgroundImage;
						if (/^url\(["']?(.+\.png)["']?\)$/i.test(style))
							src = RegExp.$1;
					}
			
					if (src) {
						el.css({
							background: 'none',
							filter:     filter + '(src="' + src + '", sizingMethod=scale)'
						});
						if (el.is('a'))
							el.css({ cursor: 'pointer' });
					}
				});
			}
		}
	}
};

$(function () { self.init(); });

})(jQuery);
