$(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(".tall");
	$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(" "),
			viewheight = $this.height(),
			num = 0,
			sec = 6000,
			first = true,
			loop = {
				timer: "",
				set: function() {
					return this.timer = setInterval(function() {
						slideNext();
					},sec);
				}
			};
		
		function slidePrev() {
			var $prevList = $twitterList.find("li:eq("+num+")"),
				_height = $prevList.height();
			
			$prevList.clone().prependTo($twitterList);
			$prevList.remove();
			$twitterList.css({ top: _height*-1 });
			
			$twitterList.stop().animate({
				top: 0
			}, "slow");
		}
		function slideNext() {
			var $currentList = $twitterList.find("li:eq(0)");
			$twitterList.stop().animate({
				top: $currentList.height() * -1
			},{
				duration: "slow",
				complete: function() {
					$currentList.clone().appendTo($twitterList);
					$currentList.remove();
					$twitterList.css({ top: 0 });
				}
			});
		}
		
		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).append($twitterList);
			$nav.css({ right: padding[1], bottom: padding[2] });
			
			viewheight = $this.offset().top + $this.height() - parseInt(padding[2].match(/[0-9]+/)) - $stream.offset().top;
			$stream.height(viewheight);	//item window viewarea set
			num = $twitterList.find("li").size()-1;	//item max 'order' number
			
			//mini button set
			if ($twitterList.height()>viewheight && num>0) {
				loop.set();
				$next.click(function() {
					clearInterval(loop.timer);
					slideNext();
					loop.set();
				});
				$prev.click(function() {
					clearInterval(loop.timer);
					slidePrev();
					loop.set();
				});
			}
			else {
				$next.css({ opacity:.3, cursor: "default" });
				$prev.css({ opacity:.3, cursor: "default" });
			}
			
			var _start = 0;
			for (var i=0; i<num+1; i++) {
				_start += 200;
				$twitterList.find("li:eq("+i+")").delay(_start).animate({ opacity:1 }, "slow");
			}
		});
		
		$this.show();
	});
});