jQuery(function($) {

	var API_URL = 'http://platform.twitter.com/anywhere.js?id=YtIQMOkeHMU4v8VKYy9pA&v=1';

	var MyAnywhere = {
		linkifyUsers: function() {
			this.twitter("#linkifyUsers ul").linkifyUsers();
		},
		hovercards: function() {
			this.twitter("#hovercards ul").hovercards();
		},
		followButton: function() {
			this.twitter("#followButton").followButton("rewish");
		},
		tweetBox: function() {
			this.twitter("#tweetBox").tweetBox({
				label: "@AnywhereからTweet",
				defaultContent: ".@AnywhereからTweetテスト http://rewish.org/javascript/twitter_anywhere"
			});
		},
		connectButtonReady: false,
		connectButtonSignOut: $('<div/>').hide(),
		connectButton: function() {
			var self = this;
			if (!self.connectButtonReady) {
				self.initConnectButton();
			}
			self.twitter("#connectButton").connectButton({
				authComplete: function() {
					self.authComplete();
				},
				signOut: function() {
					self.signOut();
				}
			});
			if (self.twitter.isConnected()) {
				self.authComplete();
			}
		},
		initConnectButton: function() {
			this.connectButtonSignOut.append(
				$('<a/>', {
					text: 'Sign out of Twitter',
					href: 'javascript:void(0)',
					click: function() {
						twttr.anywhere.signOut();
					}
				})
			);
			$('#connectButton').append(this.connectButtonSignOut);
			this.connectButtonReady = true;
		},
		authComplete: function() {
			this.connectButtonSignOut.show();
		},
		signOut: function() {
			this.connectButtonSignOut.hide();
		},
		run: function(method, linkParent) {
			var self = this;
			twttr.anywhere(function(twitter) {
				self.twitter = twitter;
				self[method]();
				linkParent.remove();
			});
		}
	};

	$.each(['linkifyUsers',
	        'hovercards',
	        'followButton',
	        'connectButton',
	        'tweetBox'], function(i, name) {
		$('#' + name).append(
			$('<p/>').append(
				$('<a/>', {
					text: 'サンプルを実行する',
					href: 'javascript:void(0)',
					click: function() {
						var parent = $(this).parent('p');
						parent.html('読み込み中...');
						if (typeof window.twttr === 'undefined') {
							$.getScript(API_URL, function() {
								MyAnywhere.run(name, parent);
							});
						} else {
							MyAnywhere.run(name, parent);
						}
					}
				})
			)
		);
	});

});

