$(document).ready(function(){
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=$.LiVE.util.getEmbedProtocol()+"//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
});
$(function() {
	// 連携キット、local時はexit
	if ($.LiVE.bdkit && location.protocol=="file:") return;
	
	var $ticker = $.LiVE.Elements.WIDGETS.ticker.find(".default");
	$ticker.each(function() {
		var $this = $(this).parent(),
			$box = $(this),
			id = $this.attr("id"),
			data = $.LiVE.widget[id].data,
			isHashMode = (data.hash.length>0),
			isAccountMode = (data.account.length>0);
		
		$ticker.height('100%');
		
		if (!data.hash.match(/^#/)) data.hash = "#" + data.hash;
		
		if ( isHashMode && isAccountMode ) {
			var url = $.LiVE.util.getEmbedProtocol()+"//search.twitter.com/search.json?q=from:" + data.account + "%20" + encodeURIComponent(data.hash) + "&callback=?";
		} else if ( isHashMode ) {
			var url = $.LiVE.util.getEmbedProtocol()+"//search.twitter.com/search.json?q=" + encodeURIComponent(data.hash) + "&callback=?";
		} else {
			var url = $.LiVE.util.getEmbedProtocol()+"//api.twitter.com/1/statuses/user_timeline.json?screen_name=" + data.account + "&count=20&callback=?";
		}
		var $name = $this.find(".name"),
			$stream = $this.find(".stream"),
			$nav = $this.find(".nav"),	//re-position later
			$prev = $("<div/>").addClass("prev").appendTo($nav),
			$next = $("<div/>").addClass("next").appendTo($nav),
			$twitterList = $("<ul/>"),
			padding = ($.LiVE.widget[id].css.padding || "0px 0px 0px 0px").split(" "),
			num = 0,
			sec = 6000,
			first = true,
			loop = {
				timer: "",
				set: function() {
					return this.timer = setInterval(function() {
						slideNext();
					},sec);
				}
			};
			
		var ua = window.navigator.userAgent.toLowerCase();
		if( ua.match('chrome') || ua.match('safari') || ua.match('firefox') ) $stream.css('position','static');
		
		function slidePrev() {
			var $currentList = $twitterList.find("li:eq("+num+")");
			num = num-1 < 0 ? $twitterList.find("li").size()-1 : num-1;
			var $prevList = $twitterList.find("li:eq("+num+")");
			
			$prevList.css({
				marginTop: $prevList.height() * -1,
				display: "block"
			});
			$currentList.stop().animate({
				marginTop: $prevList.height()
			},{
				duration: "slow",
				complete: function() {
					$currentList.css({ display: "none" });
				}
			});
			$prevList.stop().animate({
				marginTop: 0
			}, "slow");
		}
		function slideNext() {
			var $currentList = $twitterList.find("li:eq("+num+")");
			num = num+1 > $twitterList.find("li").size()-1 ? 0 : num+1;
			var $nextList = $twitterList.find("li:eq("+num+")");
			
			$nextList.css({
				marginTop: $currentList.height(),
				display: "block"
			});
			$currentList.stop().animate({
				marginTop: $currentList.height() * -1
			},{
				duration: "slow",
				complete: function() {
					$currentList.css({ display: "none" });
				}
			});
			$nextList.stop().animate({
				marginTop: 0
			}, "slow");
		}
		
		function formatTwitString(str){
			str = " " + str;
			str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
			str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank" class="info">$2</a>');
			str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank" class="info">#$2</a>');
			return str;
		}
		function formatNumber(src) {
			var numStr = new String(src);
			while(numStr != (numStr = numStr.replace(/^(-?\d+)(\d{3})/,"$1,$2")));
			return numStr;
		}
		
		var firstAttack = true;
		
		// get TL
		$.getJSON(url, function(json){
			var recs = (json.results) ? json.results:json;
			$.each(recs, function(index,item){
				if ( isAccountMode && isHashMode ) {
					var _screen_name = item.from_user,
						_user_name = item.from_user_name,
						_profile_image = item.profile_image_url;
				} else if ( isAccountMode ) {
					var _screen_name = item.user.screen_name,
						_user_name = item.user.name,
						_profile_image = item.user.profile_image_url;
				} else {
					var _screen_name = item.from_user,
						_user_name = item.from_user_name,
						_profile_image = item.profile_image_url;
				}
				var _tweeter = "",
					_created_at = new Date( item.created_at );
				
				if (isNaN(_created_at) || _created_at.toString() == "Invalid Date") {
					var str = item.created_at.split(" ");
					_created_at = new Date( [str[0],str[2],str[1],str[5],str[3],str[4]].join(" ") );
				}
				
				if (data.name) {
					_tweeter = '<a href="' + $.LiVE.util.getEmbedProtocol() + '//www.twitter.com/' + _screen_name + '" target="_blank" class="info">'
								+ _user_name + '(@' + _screen_name + '):'
								+ '</a>';
				}
				
				//create twitline
				var _timestamp = '<span class="date"> - ' 
								+ _created_at.getFullYear() + '/' + (_created_at.getMonth()+1) + '/' + _created_at.getDate() + " "
								+ _created_at.getHours() +  ":" + $.LiVE.util.zeroPad(_created_at.getMinutes(), 2)
								+ '</span>',
					$entry = $("<li/>").html('<span class="item">' + _tweeter + formatTwitString(item.text) + _timestamp + '</span>').addClass("clearfix").appendTo($twitterList);
				
				if (data.icon) {
					var _link = $("<a/>")
							.addClass("profileicon")
							.attr({ href: $.LiVE.util.getEmbedProtocol()+"//www.twitter.com/" + _screen_name, target: "_blank" })
							.prependTo($entry),
						_icon = $("<img/>")
							.attr({ src: _profile_image, alt: _user_name })
							.appendTo(_link);
				}
				
				if (firstAttack) {
					firstAttack = false;
					if (!isHashMode && data.info) {
						var _followers = $("<span/>")
								.addClass("followers")
								.text(formatNumber(item.user.followers_count) + " followers")
								.prependTo($name),
							_a = $("<a />", {href: $.LiVE.util.getEmbedProtocol()+"//www.twitter.com/" + _screen_name, target: "_blank"})
								.addClass("account")
								.text(_user_name + " (@" + _screen_name + ")")
								.prependTo($name);
					} else if (isHashMode && !isAccountMode && data.info) {
						$name.text(""); //---(@----)
					} else if (isHashMode && isAccountMode && data.info) {
						/*var _followers = $("<span/>")
								.addClass("followers")
								.text(formatNumber(item.user.followers_count) + " followers")
								.prependTo($name),*/
						var _a = $("<a />", {href: $.LiVE.util.getEmbedProtocol()+"//www.twitter.com/" + _screen_name, target: "_blank"})
								.addClass("account")
								.text(_user_name + " (@" + _screen_name + ")")
								.prependTo($name);
					}
					else $name.addClass("off");
				}
			});
			$this.find("#ticker-" + id).prepend($twitterList);
			$twitterList.find("li:first").fadeIn();
			if ($this.height() > $twitterList.height()) {
				$twitterList.height($this.height() - parseInt(padding[2].match(/[0-9]+/)) - parseInt(padding[0].match(/[0-9]+/)) - $name.height());
			}
			$nav.show();
			loop.set();
			
			//mini button set
			$next.click(function() {
				clearInterval(loop.timer);
				slideNext();
				loop.set();
			});
			$prev.click(function() {
				clearInterval(loop.timer);
				slidePrev();
				loop.set();
			});
		});
		
		$this.show();
	});
});