if (typeof jQuery != 'undefined') $(document).ready(function () {
	var user_id = $.cookie('twitter-id');

	var topUrl = function() {
		var topurl = $('#site-url').attr('href');
		if (topurl.match(/^\//)) {
			var url = location.protocol + '//' + location.hostname;
			if (location.port != 80) url += ':' + location.port;
			topurl = url + topurl;
		}
		return topurl;
	}
	var baseUrl = function() {
		var url = location.protocol + '//' + location.hostname;
		if (location.port != 80) url += ':' + location.port;
		return url + '/';
	}
	var cookieDomain = function() {
		var domain = location.hostname;
		if (location.port != 80) domain += ':' + location.port;
		return domain;
	}
	var normalizedUrl = function() {
		var url = location.protocol + '//' + location.hostname;
		if (location.port != 80) url += ':' + location.port;
		url += location.pathname;
		if (!url.match(/\/$/)) url += '/';
		return url;
	}

	var hookTags = function() {
		$('span.tag', $('#user').parent()).each(function(index, tag) {
			$(tag).hover(
				function() {
					if (!user_id) return;
					if (!!($('#ajax-loader').css('display') != 'none')) return;
					var vote_icon = 'unvote';
					if ($('#voter-' + $(tag).text() + '-' + user_id).attr('class') == 'voter')
						vote_icon = 'vote';
					$(tag).css('border', '1px solid gray')
						.append(''
							+ '<span id="tag-modify" style="vertical-align: middle; margin-left: -30px; position: absolute;">'
							+ '<img id="vote-' + $(tag).text() + '" class="' + vote_icon  + '-icon" src="/static/images/' + vote_icon + '-icon.gif" id="vote"/>'
							+ '</span>');
					$('#vote-' + $(tag).text(), tag).click(function() {
						$('#ajax-loader').fadeIn();
						$(tag).mouseout();
						var vote = $(this).attr('class').match(/^unvote/) ? 1 : 0;
						$.getJSON(normalizedUrl() + 'voteTag?callback=?', { tag: $(tag).text(), vote: vote }, function(data) {
							$('#ajax-loader').fadeOut();
							if (data.status == 'ok') {
								vote = vote ? 'voter' : 'unvoter';
								$('#voter-' + $(tag).text() + '-' + user_id).attr('class', vote);
								reloadTags();
							} else $.facebox('<img src="/static/images/fail-icon.gif"> ' + data.message);
						});
						return false;
					}).css('cursor', 'pointer').fadeIn();
					$('#tagminus', tag).click(function() {
						$('#ajax-loader').fadeIn();
						$(tag).mouseout();
						$.getJSON(normalizedUrl() + 'voteTag?callback=?', { tag: $(tag).text(), vote: 'no' }, function(data) {
							$('#ajax-loader').fadeOut();
							if (data.status == 'ok') reloadTags();
						});
						return false;
					}).css('cursor', 'pointer').fadeIn();
				},
				function() {
					$(tag).css('border', '1px solid white');
					$('#tag-modify', tag).remove();
				}
			);
		});
	};

	var reloadTags = function() {
		$('#ajax-loader').fadeIn();
		$('.tags', $('#user').parent()).html('&nbsp;');
		$.getJSON(normalizedUrl() + 'getTags?callback=?', function(data) {
			if (data.status == 'ok') {
				$.each(data.tags, function(index, item) {
					$('.tags', $('#user').parent())
						.append(''
							+ '<span class="tag" style="font-size: ' + item.fontsize + 'ex;">'
							+ '<a rel="tag" href="' + topUrl() + 'tags/' + item.tag + '/">'
							+ item.tag
							+ '</a>'
							+ '</span>'
							+ (item.voter.length > 0 ? '<span style="font-size: small;">(' + item.voter.length + ')</span>' : '')
							+ '&nbsp;\n');
				});
				hookTags();
			} else $.facebox('<img src="/static/images/fail-icon.gif"> ' + data.message);
			$('#tag-name').attr('disabled', false).val('').focus();
			$('#ajax-loader').fadeOut();
		});
	};

	var addTags = function() {
		var id = $('#user').text();
		if (!id) return;
		var value = $('#tag-name').val();
		if (value.match(/[\s\/"'\$&\(\)=\|><\\]/g)) {
			alert("Can't include insanitary characters in tag name!");
			return;
		}
		$('#ajax-loader').fadeIn();
		$('#tag-name').attr('disabled', true);
		$('#tag-add').attr('disabled', true);
		$.getJSON(normalizedUrl() + 'addTags?callback=?', { tags: value }, function(data) {
			$('#ajax-loader').fadeOut();
			if (data.status == 'ok') reloadTags();
			else $.facebox(data.message);
		});
		return false;
	};

	$(document).bind('afterReveal.facebox', function() {
		$('#twitter-user-id')
			.keyup(function() { $(this).change() })
			.change(function() { $('#twitter-user-add').attr('disabled', $(this).val() ? false : true); })
			.focus();
		$('#twitter-user-add').click(function() {
			$(this).attr('disabled', true);
			location.href = topUrl() + 'users/' + $('#twitter-user-id').val();
			return false;
		});
		$('#twitter-notify').click(function() {
			var id = $('#user').text();
			$.getJSON('http://twitter.com/notifications/follow/' + id + '.json?callback=?', function(data) {
				$.facebox('<div>You changed notification of IM.</div>');
			});
			return false;
		});
	});

	var addUser = function() {
		$.facebox(''
			+ '<div id="addUser" style="text-align: center;"><form>'
			+ '<label for="user-id">twitter id</label>:'
			+ '<input type="text" id="twitter-user-id" name="user-id" value=""/><br />'
			+ '<input type="button" id="twitter-user-add" value="add User" disabled="true"/>'
			+ '</form></div>');
		return false;
	};

	var loginStatus = function() {
		if (user_id) {
			$('#login-tool').html(''
				+ 'logged-in as ' + user_id + ' '
				+ '(<a href="#" id="logout">LOGOUT</a>)&nbsp;'
			);
			$('#logout').click(logout);
			$('#tags-editor').fadeIn();
			$('#tag-add').attr('disabled', false);
			$('#tag-name').attr('disabled', false);
			if ($('#tag-name').get(0) && !$.autocomplete) {
				var css = document.createElement('link');
				css.setAttribute('rel', 'stylesheet');
				css.setAttribute('type', 'text/css');
				css.setAttribute('href', baseUrl() + 'static/css/jquery.autocomplete.css');
				css.setAttribute('media', 'screen');
				css.id = 'autocomplete-css';
				var head = document.getElementsByTagName("head")[0] || document.documentElement;
				head.appendChild(css);

				$.getScript(baseUrl() + 'static/javascript/jquery.autocomplete.js', function() {
					$.getJSON(topUrl() + 'getAllTags?callback=?', function(data) {
						if (data.status == 'ok') $('#tag-name').autocompleteArray(data.tags);
					});
				});
			}
		} else {
			$('#login-tool').html(''
				+ '<a href="#" id="login"><img src="/static/images/login-icon.gif"/> LOGIN</a>&nbsp;'
			);
			$('#login').click(login);
			$('#tags-editor').fadeOut();
		}
	};

	var login = function() {
		$.getJSON('http://twitter.com/statuses/user_timeline.json?callback=?&count=1', function(data) {
			user_id = data[0].user.screen_name;
			$.cookie('twitter-id', user_id, { path: '/', secure: false });
			loginStatus();
		});
		return false;
	};

	var logout = function() {
		$.getJSON('http://twitter.com/account/end_session.json?callback=?', function(data) {
			user_id = null;
			$.cookie('twitter-id', user_id, { path: '/', secure: false });
			loginStatus();
		});
		return false;
	};

	$('#user-add').click(addUser);
	$('#tag-add').click(addTags);
	if (user_id ) $('#tags-editor').fadeIn();
	$('#tag-name')
		.focus(function() { $(this).css('background-color', '#ffffff'); })
		.blur(function() { if (!$(this).val()) $(this).css('background-color', '#cccccc'); })
		.keyup(function() { $(this).change() })
		.change(function() { $('#tag-add').attr('disabled', $(this).val() ? false : true); })
		.focus();

	$('#user-tool').html(''
		+ '<a href="#" id="user-json"><img src="/static/images/json-icon.gif"/> JSON</a>&nbsp;'
		+ '<a href="#" id="user-link"><img src="/static/images/site-icon.gif"/> TAKO3</a>&nbsp;'
		+ '<a href="#" id="user-statuses"><img src="/static/images/statuses-icon.gif"/> STATUSES</a>&nbsp;'
		+ '<a href="#" id="user-follow"><img src="/static/images/follow-icon.gif"/> FOLLOW</a>&nbsp;'
	);
	$('#user-json').click(function() {
		window.open(normalizedUrl() + 'getTags');
	});
	$('#user-link').click(function() {
		var id = $('#user').text();
		if (id) {
			$.getJSON('http://tako3.com/json/http://twitter.com/' + id + '?callback=?', function(data) {
				var html = '';
				$.each(data, function(index, item) {
					html += '<span class="userlink"><img src="http://favicon.aruko.net/m/f/' + item + '"><a href="' + item + '">' + item + '</a></span><br />';
				});
				if (!html) html = 'nothing';
				$.facebox('<div>' + html + '</div>')
			});
		}
		return false;
	});
	$('#user-statuses').click(function() {
		var user = $('#user');
		if (user.text()) {
			var id = $(user).text();
			$.facebox(function() {
				$.getJSON('http://twitter.com/statuses/user_timeline/' + id + '.json?callback=?', function(data) {
					var html = '';
					$.each(data, function(index, item) {
						html += '<span class="statustext">' + item.text + '</span><br /><br />';
					});
					$.facebox('<div style="line-height: 10px;">' + html + '</div>')
				});
			});
		}
		return false;
	});
	$('#user-follow').click(function() {
		var id = $('#user').text();
		if (id) {
			$.getJSON('http://twitter.com/friendships/create/' + id + '.json?callback=?', function(data) {
				$.facebox('<div>You followed <a href="http://twitter.com/' + id + '">' + id + '</a>! And <a id="twitter-notify" href="#">notify</a> <b>' + id + '</b>\'s status to IM.</div>');
			});
		}
		return false;
	});

	hookTags();

	var jsc = 100000;
	$('span.user').each(function(index, user) {
		var id = $(user).text();
		$(user)
			.before('<img class="icon" class="photo" id="icon_' + id + '" />')
			.after(''
				+ '&nbsp;'
				+ '<a class="url fn" href="http://twitter.com/' + id + '">'
				+ '<img id="jump_' + id + '" src="/static/images/jump-icon.gif" alt="go twitter" title="go twitter" border="0" />'
				+ '</a>'
				+ '<br />'
				+ '<span class="status" id="status_' + id + '"/>'
				+ '<br />');
		$('#icon_' + id).hide();
		$('#status_' + id).hide();
		$('#jump_' + id).css('cursor', 'pointer')
			.hover(
				function() { $(this).css('background-color', 'lightblue'); },
				function() { $(this).css('background-color', ''); }
			);
		var fn = 'myjsonp' + (jsc++);
		window[fn] = function(data) {
			$(user).after('<span class="username">(' + data[0].user.name + '&#x202C;)</span>');
			$('#icon_' + id).attr('src', data[0].user.profile_image_url).fadeIn();
			$('#status_' + id).text(data[0].text).fadeIn();
		};
		$.getScript('http://twitter.com/statuses/user_timeline/' + id + '.json?callback=' + fn + '&count=1');
	});

	var iconcache = [];
	$('span.usericon').each(function(index, user) {
		var id = $(user).text();
		$(user).before('<img class="icon" id="usericon_' + index + '" />')
		for (var n = 0; n < iconcache.length; n++) {
			if (iconcache[n].id == id) {
				$('#usericon_' + index).attr('src', iconcache[n].icon);
				$(user).after('<span class="username">(' + iconcache[n].name + '&#x202C;)</span>');
				return;
			}
		}
		$('#usericon_' + index).hide();
		$.getJSON('http://twitter.com/users/show.json?screen_name=' + id + '&callback=?', function(data) {
			try {
				$(user).after('<span class="username">(' + data.user.name + ')</small>');
				$('#usericon_' + index).attr('src', data.user.profile_image_url).fadeIn();
				iconcache.push({
					id: id,
					name: data.user.name,
					icon: data.user.profile_image_url
				});
			} catch(e) {}
		});
	});

	loginStatus();

	$('#voters .voter').each(function(index, voter) {
		var fn = 'myjsonp' + (jsc++);
		window[fn] = function(data) {
			$(voter)
				.before('<img class="voter-icon" src="' + data[0].user.profile_image_url + '"/>')
				.after('<span class="username">(' + data[0].user.name + ')</span>');
		};
		$.getScript('http://twitter.com/statuses/user_timeline/' + $(voter).text() + '.json?callback=' + fn + '&count=1');
	});

	$('.untag').click(function() {
		var id = $('#user').text();
		if (!id) return;
		var tag = $(this).attr('id').replace(/^untag-/, '');
		$('#ajax-loader').fadeIn();
		$.getJSON(normalizedUrl() + 'delTags?callback=?', { tags: tag }, function(data) {
			$('#ajax-loader').fadeOut();
			if (data.status == 'ok') reloadTags();
			else $.facebox(data.message);
		});
		return false;
	}).css('cursor', 'pointer');

	$('#filter-tag').click(function() {
		location.href = normalizedUrl() + $('#filter-name').val();
		return false;
	});

	$('#get-bio').click(function() {
		$('#ajax-loader').fadeIn();
		$.getJSON(normalizedUrl() + 'getBio?callback=?', function(data) {
			if (data.status == 'ok') {
				$('#tag-name').val(data.words.join(','));
			} else $.facebox('<img src="/static/images/fail-icon.gif"> ' + data.message);
			$('#ajax-loader').fadeOut();
		});
		return false;
	}).css('cursor', 'pointer');

	var feed = $('#tag-feed');
	if (feed.attr('id')) {
		var tag = normalizedUrl().replace(/^.*\/tags\/([^\/]+)\/?$/, '$1');
		feed.html(''
			+ '<a class="feed" href="http://del.icio.us/rss/tag/' + tag + '">entries in del.icio.us</a>'
			+ '<a class="feed" href="http://b.hatena.ne.jp/t/' + tag + '?mode=rss&sort=hot">entries in hatena bookmark</a><br />'
		);
		$.getScript('http://www.google.com/jsapi?key=ABQIAAAAS_2fKEdj-fsDOrnYqd4nthSpwksEGJn2VMlsd_zAnAXqgPjmqBQjS1NZ_YlJ4eWNr8DsB3Oe9TgSDw', function() {
			google.load("feeds", "1", { callback : function(){
				$.getScript(baseUrl() + 'static/javascript/jquery.gfeed.js', function() {
					$('a.feed').gFeed( { target: '#tag-feed', tabs: true } );
				});
			}});
		});
	}

	$.each({
		news : false,
		info : true,
		tag  : false,
		vote : false,
		user : false,
		freq : false
	}, function(i) {
		var icons = [
			'<img src="/static/images/open-icon.gif" alt="..." title="open this content" style="vertical-align: middle;" />',
			'<img src="/static/images/close-icon.gif" alt="..." title="close this content" style="vertical-align: middle;" />'
		];
		var f = $('.' + i + '-header');
		f.append('<span id="' + i + '-content-toggle">' + icons[1] + '</span>');
		f = $('#' + i + '-content-toggle');
		f.click(function() {
			$(this).html(($('.' + i + '-content').css('display') != 'none') ? icons[0] : icons[1]);
			$('.' + i + '-content').toggle('fast');
		}).css('cursor', 'pointer');
		if (this == true) f.click();
	});

	/*
	$.get('/static/images/vote-icon.gif');
	$.get('/static/images/unvote-icon.gif');
	*/
});
