jQuery.each( [ "get2", "post2" ], function( i, method ) {
	jQuery[ method ] = function( url, data, success, error, type, retry, wait, complete ) {
		var retry_index = 0;
		if ( jQuery.isFunction(data)) {
			complete = wait;
			wait = retry;
			retry = type;
			type = error;
			error = success;
			success = data;
			data = undefined;
		}
		if (! jQuery.isFunction(error)) {
			complete = wait;
			wait = retry;
			retry = type;
			type = error;
			error = undefined;
		}
		if (! wait)
			wait = 100;
		var ajax = function() {
			return jQuery.ajax({
				type: method.slice(0, -1),
				url: url,
				data: data,
				success: success,
				error: function(req, status, ex) {
					if (status == "timeout" && retry_index < retry) {
					//if (retry_index < retry) {
						window.setTimeout(ajax, wait)
						retry_index++;
						return;
					}
					if (error)
						error(req, status, ex);
				},
				complete: complete,
				dataType: type
			});
		}

		return ajax();
	};
});



T.now = (new Date()).getTime();
T.one_second = 1000;
T.one_minute = T.one_second * 60;
T.one_hour = T.one_minute * 60;
T.one_day = T.one_hour * 24;
T.update = function() {
	T.now = $.now();
	var times = $(".time");
	for (var i=0; i<times.length; i++) {
		var tmp = T.countdown_by($(times[i]).attr("d"));
		if ($(times[i]).text() == tmp)
			break;
		$(times[i]).text(tmp);
	}
}
T.createContentsByArray = function(objs) {
	var ret = [];
	for (var i=0; i<objs.length; i++) {
		ret.push(T.createContentsByObject(objs[i]));
	}
	return ret;
}
T.createContentsByObject = function(obj) {
	var content = $("<div/>").addClass("content");
	var header = $("<div/>").addClass("header");
	header.text(obj.id+"： ");
	if (obj.user_id) {
		header.append($("<a/>").addClass("name").attr("href", T.base+"user/"+encodeURIComponent(obj.login_id)).text(obj.n).addClass("user"+obj.t));
	} else {
		header.append($("<a/>").addClass("name").attr("href", T.base+"name/"+encodeURIComponent(obj.n)).text(obj.n));
		if (obj.trip) {
			header.append($("<a/>").addClass("name").attr("href", T.base+"trip/"+encodeURIComponent(obj.trip)).text("@"+obj.trip));
		}
	}
	header.append($("<span/>").addClass("user").text("-"));
	header.append($("<span/>").addClass("time").attr("d", obj.created).text(T.countdown_by(obj.created)));
	content.append(header);

	var contents = obj.content.split("\n");
	var body = $("<div/>").addClass("body");
	for (var j=0; j<contents.length; j++) {
		if (j > 0)
			body.append($("<br/>"));
		body.append($("<span/>").text(contents[j]));
	}
	content.append(body);

	var tag = $("<div/>").addClass("tag");
	obj.jt = JSON.parse(obj.jt);
	if (obj.t_theme) {
		tag.append($("<a/>").css("font-weight", "bold").text(obj.t_theme).attr("href", T.base+"theme/"+encodeURIComponent(obj.t_theme)));
	}
	if (obj.jt) {
		for (var i=0; i<obj.jt.length; i++) {
			tag.append($("<a/>").text(obj.jt[i]).attr("href", T.base+"theme/"+encodeURIComponent(obj.jt[i])));
		}
	}
	content.append(tag);

	var action = $("<div/>").addClass("action");
	content.append(action);

	content.hover(T.show_action, T.hide_action);
	//content.attr("id","content"+obj.id);
	content.attr("i",obj.id);
	if (obj.t_id)
		content.attr("pp", obj.t_id);

	return content;
}
T.show_conversation = function(e) {
	T.conversation($(e.target).parent().parent());
	$(this).text("会話を非表示");
}
T.hide_conversation = function(e) {
	$(e.target).parent().parent().find(".content").remove();
	$(this).text("会話を表示");
}
T.preview = function(path, force) {
	var url_path = $("<a/>").attr("href", T.base+"url")[0].href;
	if (force || url_path == path.substr(0, url_path.length)) {
		var img = $("<img/>").attr(
			"src",
			force ? path : decodeURIComponent(decodeURIComponent(path.substr(url_path.length+1)))
		);
		$("#preview-dialog").html(img).dialog({
			modal: true,
			autoOpen: true,
			width: $("#main-container").innerWidth() - 64,
			height: $(window).innerHeight() - 64,
			show: "fade",
			hide: "fade",
			buttons: {
				"閉じる": function() {
					$(this).dialog("close");
				}
			}
		});
	}
}
T.show_action = function(e) {
	if ($(this).hasClass("active"))
		return;	//時々hoverの処理がバグって二重発生になるためにある処理

	var action = $(this).addClass("active").children(".action");
	var content = $(e.delegateTarget);
	var parent_id = content.attr("pp");
	var id = content.attr("i");

	if (parent_id && content.parent(".content").length==0) {
		if (content.children(".content").length) {
			action.append($("<a/>").attr("href", "javascript:void(0)").toggle(T.hide_conversation, T.show_conversation).text("会話を非表示"));
		} else {
			action.append($("<a/>").attr("href", "javascript:void(0)").toggle(T.show_conversation, T.hide_conversation).text("会話を表示"));
		}
	}

	action.append($("<a/>").attr("href", "javascript:void(0)").click(function(e) {
		T.reply(content);
	}).text("返信"));
	action.append($("<a/>").attr("href", T.base+"read/"+id).text("詳細"));

	if ($(e.delegateTarget).find(".body a").length) {
		var cnt = 0;
		$(e.delegateTarget).find(".body a").each(function(index) {
			if(this.href.match(/\.(png|jpeg|jpg|gif)/i)) {
				action.append(
					$("<a/>").attr("href", "javascript:T.preview('"+this.href+"')").text("画像"+(++cnt))
				);
			}
		});
	}

	if (T.O)
		T.O.show_action(action, content);

	if (T.login) {
		var f_container = $("<span/>");
		action.append(f_container);
		T.getFavorite(f_container, "post", id);
	}
}
T.hide_action = function(e) {
	var action = $(this).removeClass("active").children(".action");
	action.html("");
}
T.pad0 = function(val, len) {
	if (! len)
		len = 2;
	var tmp = new String(val);
	if (tmp.length < len) {
		var ret = val;
		for (var i=tmp.length; i<len; i++) {
			ret = "0" + ret;
		}
		return ret;
	}
	return val;
}

T.countdown_by2 = function(time, from) {
	if (! from)
		from = T.now;
	if (typeof(time) == "string") {
		var d = new Date(
			time.substr(0,4),
			parseInt(time.substr(5,2))-1,
			time.substr(8,2),
			time.substr(11,2),
			time.substr(14,2),
			time.substr(17)
		)
		time = d.getTime();
	}

	time += T.time_diff * 1000;

	var diff = from - time;
	if (diff > (T.one_day*365)) {
		return parseInt(diff / (T.one_day*365)) + "年前";
	} else if (diff > (T.one_day*30)) {
		return parseInt(diff / (T.one_day*30)) + "ヶ月前";
	} else if (diff > T.one_day) {
		return parseInt(diff / T.one_day) + "日前";
	} else if (diff > T.one_hour) {
		return parseInt(diff / T.one_hour) + "時間前";
	} else if (diff > T.one_minute) {
		return parseInt(diff / T.one_minute) + "分前";
	} else {
		return parseInt(diff / T.one_second) + "秒前";
	}
}
T.countdown_by = function(time, from) {
	if (! from)
		from = T.now;
	if (typeof(time) == "string") {
		var d = new Date(
			time.substr(0,4),
			parseInt(time.substr(5,2))-1,
			time.substr(8,2),
			time.substr(11,2),
			time.substr(14,2),
			time.substr(17)
		)
		time = d.getTime();
	}

	time += T.time_diff * 1000;

	var diff = from - time;
	if (diff > (T.one_day*7)) {
		var formatter = new Date();
		formatter.setTime(time);
		return (
			[
				formatter.getFullYear(),
				T.pad0(formatter.getMonth()+1),
				T.pad0(formatter.getDate())
			].join("-")
		 	+ " "
		 	+ [
				T.pad0(formatter.getHours()),
				T.pad0(formatter.getMinutes()),
				T.pad0(formatter.getSeconds())
			].join(":")
		);
		return test;
	} else if (diff > T.one_day) {
		return parseInt(diff / T.one_day) + "日前";
	} else if (diff > T.one_hour) {
		return parseInt(diff / T.one_hour) + "時間前";
	} else if (diff > T.one_minute) {
		return parseInt(diff / T.one_minute) + "分前";
	} else {
		return parseInt(diff / T.one_second) + "秒前";
	}
}

T.lastId = 0;
T.reqId = 0;
T.lastCnt = 0;
T.polling_wait = 2100;
T.polling_loop = 0;
T.flg = false;
T.oldId = 0;
T.oldCnt = 0;
T.oldReading = false;
T.readOpt = {}
T.polling = function() {
	T.reqId = T.lastId;
	var param = T.readOpt;
	T.readOpt.id = T.reqId;
	T.polling_loop++;
	if (T.polling_loop > 10) {
		T.polling_loop = 0;
		T.update();
	}
	$.get2(
		T.api+"new.php",
		param,
		T.polling_callback,
		T.polling_callback_error
	);
}
T.polling_callback = function(cnt) {
	if (! T.flg) {
		if (cnt && cnt > 0 && cnt != T.lastCnt) {
			if (T.reqId == T.lastId) {
				T.lastCnt = cnt;
				$("#new_post_cnt").html(cnt);
				var n = $("#new_post");
				if (n.is(":visible")) {
					$("#new_post").hide().effect("fade", {mode:"show"}, 400);
				} else {
					$("#new_post").hide().effect("blind", {mode:"show"}, 400);
				}
			}
		}
	}
	setTimeout(T.polling, T.polling_wait);
}
T.polling_callback_error = function() {
	setTimeout(T.polling, T.polling_wait);
}
T.trim = function(s){
	return s.replace(/(^[\s　]+)|([\s　]+$)/g, "");
}
T.oldRead = function() {
	if ((!T.oldReading) && T.oldCnt > 0) {
		T.oldReading = true;
		T.oldCnt = 0;
		$("#read-old").effect("fade", {mode:"hide"});
		var param = T.readOpt;
		param.id = T.oldId;
		$("<div id='oldl'/>").insertBefore("#read-old").spin();
		$.get2(
			T.api+"getold.php",
			param,
			function(ret) {
				T.oldReading = false;
				var htmls = T.createContentsByArray(ret);
				for (var i=0; i<htmls.length; i++)
					$("#content-box").append(htmls[i]);
				T.refreshOld(ret[ret.length-1].id);
				$(".tag a").button();
				T.autoLink();
				$("#oldl").remove();
			},
			function() {
				T.refreshOld(T.oldId);
				T.oldReading = false;
				$("#oldl").remove();
			},
			"json"
		);
	}
}
T.refreshOld = function(lastId) {
	T.oldId = lastId;
	var param = T.readOpt;
	param.id = T.oldId;
	$.get(
		T.api+"old.php",
		param,
		function(d) {
			T.oldCnt = d;
			if (d > 0) {
				$("#read-old").effect("fade", {mode:"show"});
				$("#read-old-link").text("古い投稿 "+T.oldCnt+"件 を読み込む");
			}
		}
	);
}
T.favorite = function(container, type, key) {
	container.children(".favorite").effect("fade", {mode:"hide"});
	$.post2(
		T.api+"add_favorite_item.php",
		{t: type, key: key},
		function(ret) {
			if (! ret)
				return;
			if (window.Favo && Favo.manageMode)
				location.reload();
			T.printFavorite(container, ret, type, key);
		},
		function() {
			alert("お気に入りの登録に失敗しました。");
			container.children(".favorite").effect("fade", {mode:"show"});
		},
		"json"
	);
}
T.unfavorite = function(container, type, key) {
	container.children(".favorite").effect("fade", {mode:"hide"});
	$.post2(
		T.api+"del_favorite_item.php",
		{t: type, key: key},
		function(ret) {
			if (! ret)
				return;
			if (window.Favo && Favo.manageMode)
				location.reload();
			T.printFavorite(container, ret, type, key);
		},
		function() {
			alert("お気に入り登録の解除に失敗しました。");
			container.children(".favorite").effect("fade", {mode:"show"});
		},
		"json"
	);
}
T.printFavorite = function(container, ret, type, key) {
	var a = $(T.login ? "<a/>" : "<span/>").addClass("favorite");
	if (T.login) {
		a.attr("href","javascript:void(0)")
		if (ret.favorited) {
			a.text("お気に入り解除("+ret.count+")");
			a.click(function(e) {
				T.unfavorite(container, type, key);
			});
		} else {
			a.text("お気に入り("+ret.count+")");
			a.click(function(e) {
				T.favorite(container, type, key);
			});
		}
	} else {
		a.text("お気に入り数("+ret.count+")");
	}
	container.children(".favorite").remove();
	container.append(a);
}
T.getFavorite = function(container, type, key) {
	$.getJSON(
		T.api+"get_favorite_item.php?"+T.now,
		{t: type, key:key},
		function(ret) {
			if (! ret)
				return;
			T.printFavorite(container, ret, type, key);
		}
	);
}
T.initRead = function(no_content) {
	var param = T.readOpt;
	if (! no_content) {
		var contents = $(".content");
		if (contents.length > 0) {
			T.lastId = parseInt($(contents[0]).attr("i"));
			T.refreshOld(parseInt($(contents[contents.length-1]).attr("i")));
		} else {
			$("#content-box").append("<div class=\"content\">まだ投稿がありません。</div>");
		}
		$(".tag a").button();
		$("#read-old-link").button();
		$(".action").html("");
		contents.hover(T.show_action, T.hide_action);
		$.each($(".time"), function() {
			$(this).text(T.countdown_by($(this).text()));
		});

		if ($("#loading").length) {
			$("#loading").hide();
			setTimeout(T.polling, T.polling_wait);

			$(window).scroll(function(e) {
				var pos = $(this).scrollTop()+$(this).height()+32;
				if (pos > $(document).height()) {
					T.oldRead();
				}
			});
		}
	}

	if ($("#recent_theme_container").length) {
		$("<div id='loading_recent_theme_icon' />").insertAfter($("#loading_recent_theme")).spin();
		$.getJSON(
			T.api+"get_recent_theme.php",
			function(ret) {
				$("#loading_recent_theme_icon").remove();
				$("#loading_recent_theme").hide();
				var t = $("#recent_theme_container");
				for (var i=0; i<ret.length; i++) {
					t.append(
						$("<a/>").addClass("cloud").attr("href", T.base+"theme/"+encodeURIComponent(ret[i].name)).text(ret[i].name+"("+ret[i].cnt+")")
					).append(" ");
				}
			}
		);
	}

	if ($("#keyword_container").length) {
		$("<div id='loading_keyword_icon' />").insertAfter($("#loading_keyword")).spin();
		$.getJSON(
			T.api+"get_active_keyword.php",
			function(ret) {
				$("#loading_keyword_icon").remove();
				$("#loading_keyword").hide();
				for (var i=0; i<ret.length; i++) {
					$("#keyword_container").append(
						$("<a/>").addClass("cloud").attr("href", T.base+"keyword/"+encodeURIComponent(ret[i].keyword)).text(ret[i].keyword+"("+ret[i].cnt+")")
					).append(" ");
				}
			}
		);
	}

	if ($("#theme_container").length) {
		$("<div id='loading_theme_icon' />").insertAfter($("#loading_theme")).spin();
		$.getJSON(
			T.api+"get_theme_cloud.php",
			function(ret) {
				$("#loading_theme_icon").remove();
				$("#loading_theme").hide();
				for (var i=0; i<ret.length; i++) {
					$("#theme_container").append(
						$("<a/>").addClass("cloud").css("font-size", Math.min(360, 100+Math.ceil(ret[i].rcnt*0.7))+"%").attr("href", T.base+"theme/"+encodeURIComponent(ret[i].t_theme)).text(ret[i].t_theme/*+"("+ret[i].rcnt+")"*/)
					).append(" ");
				}
			}
		);
	}

	if ($("#url_topic_container").length) {
		$.getJSON(
			T.api+"get_recent_url.php",
			function(ret) {
				for (var i=0; i<ret.length; i++) {
					$("#url-topic-recent").append($("<li/>").append(
						$("<a/>").addClass("cloud").attr("href", T.base+"url/"+encodeURIComponent(encodeURIComponent(ret[i].url))).text((ret[i].title ? ret[i].title : ret[i].url)+"("+ret[i].cnt+")")
					));
				}
			}
		);
		$.getJSON(
			T.api+"get_hot_url.php",
			function(ret) {
				for (var i=0; i<ret.length; i++) {
					$("#url-topic-hot").append($("<li/>").append(
						$("<a/>").addClass("cloud").attr("href", T.base+"url/"+encodeURIComponent(encodeURIComponent(ret[i].url))).text((ret[i].title ? ret[i].title : ret[i].url)+"("+ret[i].rcnt+")")
					));
				}
			}
		);
	}

	$("#theme_name").keydown(function(e) {
		if (e.keyCode != 13)
			return;

		var self = $(this);
		var b = self.attr("before");
		if (b != self.val()) {
			b = self.val();
			self.attr("before", b);
			$("<div id='loading_recent_theme_icon' />").insertAfter($("#loading_recent_theme")).spin();
			$("#recent_theme_container").html("");
			$.get2(
				T.api+"get_recent_theme.php",
				{name: b},
				function(ret) {
					$("#loading_recent_theme_icon").remove();
					if (ret.length) {
						for (var i=0; i<ret.length; i++) {
							$("#recent_theme_container").append(
								$("<a/>").addClass("cloud").attr("href", T.base+"theme/"+encodeURIComponent(ret[i].name)).text(ret[i].name+"("+ret[i].cnt+")")
							).append(" ");
						}
					} else {
						$("#recent_theme_container").html("テーマが見つかりません。");
					}
				},
				function() {
					$("#loading_recent_theme_icon").remove();
					$("#recent_theme_container").html("エラー");
				},
				"json"
			);
		}
	});

	T.postBox();

	if (! no_content)
		T.autoLink();

}
T.get_new = function(comp,err) {
	$("#new_post").hide();
	if (! comp) {
		$("#loading").show();
	}
	var param = T.readOpt;
	param.id = T.lastId;
	T.flg = true;
	$("<div id='newl'/>").insertAfter("#loading").spin();
	$.get2(
		T.api+"getnew.php",
		param,
		function(ret) {
			T.update();
			if (! comp)
				$("#loading").hide();
			$("#newl").remove();
			if (ret.length > 0) {
				T.lastId = ret[0].id;
				T.lastCnt = 0;
				var htmls = T.createContentsByArray(ret);
				var h;
				while (h = htmls.pop()) {
					h.insertAfter($("#new_post"));
				}
			}
			$(".tag a").button();
			T.autoLink();
			if (comp) {
				comp();
			} else {
				T.flg = false;
			}
		},
		function() {
			$("#newl").remove();
			if (err) {
				err();
			} else {
				location.reload();
			}
		},
		"json"
	);
}

T.reply = function(content) {
	//TODO: bad code
	var content_clone = content.clone();
	content_clone.find(".action").remove();
	//content_clone.find("a").removeAttr("href");
	content_clone.css("font-size","120%").removeClass("active");

	var dialog = $("#reply-dialog").html("")
		.append(content_clone)
		.append("<div><div id='reply-post' /></div>")
		.dialog({
			modal: true,
			autoOpen: true,
			draggable: false,
			resizable: false,
			width: $("#main-container").innerWidth() - 64,
			height: $(window).innerHeight() - 64,
			show: "fade",
			hide: "fade",
			buttons: {
				"閉じる": function() {
					$(this).dialog("close");
				}
			},
			close: function() {
			}
		}
	);
	var replypost = $("#reply-post");
	T.postBox(replypost, true, "reply-box", null, T.reply_callback || function() {
		dialog.dialog("close");
	});
	replypost.find(".noopt").remove();
	var txt = replypost.find("textarea[name='c']").insertAtCaret(">>"+content.attr("i")+"\n");
}

T.conversation = function(content) {
	$.get2(
		T.api + "conversation.php",
		{pp:content.attr("pp")},
		function(ret) {
			if (! ret) {
				alert("会話の取得に失敗しました。");
				return;
			}
			var htmls = T.createContentsByArray(ret);
			var h;
			while (h = htmls.pop()) {
				if (h.attr("i") == content.attr("i"))
					h.css("opacity", "0.8").css("filter","Alpha(Opacity=80)");
				content.append(h);
			}
			content.find(".tag a").button();
			T.autoLink();
		},
		function() {
			alert("会話の取得に失敗しました。");
		},
		"json"
	);
}

T.post_content = function(target, callback1, callback2) {
	if (! target)
		target = $("#post-box");
	target.find(".post-btn").attr("disabled", true);
	var opt = {mode: "hide"}
	var post_l = $("<div/>").insertBefore(target).spin({top:"80px"});
	target.effect(
		"fade",
		opt,
		800
	);
	T.flg = true;
	var param = {c: target.find("textarea[name='c']").val()};
	if (target.find(".anonymous").is(":checked")) {
		param.anonymous = true;
		param.trip = target.find(".trip").val();
	}

	var disOption = target.find("input[name='noopt']").is(":checked");
	var post_finish = function(clear) {
		post_l.remove();
		target.stop(true, true).effect("fade", {mode:"show"}, 200);
		if (clear)
			target.find("textarea[name='c']").val("").focus();
		else
			target.find("textarea[name='c']").focus();
		$(".tag a").button();
		T.flg = false;
		target.find(".post-btn").attr("disabled", false);
		if (callback2) callback2();
	}
	// image upload mode
	if (target.find(".image").val() && T.f) {
		var formdata = new FormData();
		formdata.append("f", T.f);
		formdata.append("c", param.c);
		if (param.anonymous)
			formdata.append("anonymous", param.anonymous);
		if (param.trip)
			formdata.append("trip", param.trip);
		$.ajax({
			url: T.api+'post.php?'+(disOption ? "" : $.param(T.readOpt)),
			type: "post",
			data: formdata,
			contentType: false,
			processData: false,
			dataType: "json",
			success: function(data) {
				if (callback1) callback1();
				T.f = null;
				target.parent().parent().find(".image-preview").remove();
				target.find(".image").val("");
				target.find("form[name='post-form']").removeAttr("enctype");
				if (disOption) {
					T.createContentsByObject(data).insertAfter($("#new_post"));
					T.autoLink();
					post_finish(true);
					return;
				}
				T.get_new(function() {
					post_finish(true);
				}, function() {
					location.reload();
				});
			},
			error: function() {
				alert("投稿に失敗しました。");
				post_finish();
			}
		});
	} else {
	// normal upload
		$.post2(
			T.api+'post.php?'+(disOption ? "" : $.param(T.readOpt)),
			param,
			function(data) {
				if (callback1) callback1();
				if (disOption) {
					T.createContentsByObject(data).insertAfter($("#new_post"));
					T.autoLink();
					post_finish(true);
					return;
				}
				T.get_new(function() {
					post_finish(true);
				}, function() {
					location.reload();
				});
			},
			function(req, status, ex) {
				alert("投稿に失敗しました。");
				post_finish();
			},
			"json",
			3
		);
	}
	return false;
}
T.postBox = function(target, expand, text_class, callback, callback1, callback2) {
	if (! target)
		target = $("#post-box");

	if (target.length == 0)
		return;

	var base_html = [
		'<form name="post-form" method="post">',
		'<div>',
		'<textarea name="c" class="'+(text_class ? text_class : "post")+' ui-corner-all"></textarea>',
		'</div>',
		'<div class="post-btn-box">'
	];

	base_html.push('<input class="post-btn button" type="submit" name="noajax" value="投稿" />');
	if (T.image_upload) {
		base_html.push('<span class="image-container">');
		base_html.push('<button class="image-btn"></button>');
		base_html.push('<input class="image" name="image" type="file" />');
		base_html.push('</span>');
	}
	if (T.readOpt.theme || T.readOpt.url)
		base_html.push('<span class="noopt"><input type="checkbox" name="noopt" value="1" />一般投稿</span>');
	base_html.push('</div>');
	if (T.anonymous) {
		base_html.push('<div class="post-anonymous-box">');
		base_html.push('<input type="checkbox" name="anonymous" class="anonymous" value="1">匿名');
		base_html.push('<input type="password" class="ui-corner-all trip" name="trip" title="匿名の際ここに入力すると、暗号化された識別子（トリップ）を付けられます" />');
		base_html.push('</div>');
	}
	base_html.push('<div class="c"></div>');
	base_html.push('</form>');
	target.append(base_html.join("\n"));
	target.find(".button").button();

	var anonymous = target.find(".anonymous");
	var trip = target.find(".trip");
	if (T.anonymous_value)
		anonymous.attr("checked", T.anonymous_value);
	if (T.trip_value)
		trip.val(T.trip_value);
	var c = target.find("textarea[name='c']");
	var image = target.find("input[type='file']");
	var p = target.parent();
	anonymous.change(function() {
		if (anonymous.is(":checked")) {
			trip.show();
		} else {
			if (! T.login) {
				alert("ログインしていないため、常に匿名モードになります。");
				anonymous.attr("checked", "checked");
				return;
			}
			trip.hide();
			return;
		}
	});
	anonymous.change();
	if (! T.login)
		anonymous.attr("checked", "checked");

	trip.tooltip();
	if (expand) {
		if (! text_class) {
			c.css("height", "78px");
			target.parent().css("height", anonymous.length > 0 ? "166px" : "136px");
		}
		$(".post-anonymous-box").css("display", "block");
	} else {
		c.focus(function(e) {
			if (c.css("height") != "78px") {
				c.css("height", "78px");
				target.parent().css("height", anonymous.length > 0 ? "166px" : "136px");
				$(".post-anonymous-box").css("display", "block");
			}
		});
	}
	target.find(".image-btn").button({icons: {primary: "ui-icon-image"}, text:false}).click(function(e) {
		image.click();
		e.preventDefault();

		return false;
	});
	target.find("form[name='post-form']").submit(function() {
		if (callback) callback()
		return T.post_content(target, callback1, callback2)
	});
	image.change(function(e) {
		if (! e.target.files) {
			alert("お使いのブラウザではファイルアップロード機能が利用出来ません。");
			return;
		}
		var f = e.target.files[0];
		var fname = image.val();
		if (!fname) {
			p.parent().find(".image-preview").remove();
			T.f = null;
			return;
		}
		if(!fname.match(/\.(png|jpeg|jpg|gif)$/i)) {
			alert("拡張子がpng/jpg/jpeg/gifのファイルのみアップロード出来ます。");
			image.val("");
			p.parent().find(".image-preview").remove();
			T.f = null;
			return;
		}

		p.parent().find(".image-preview").remove();

		target.find("form[name='post-form']").attr("enctype", "multipart/form-data");
		var p_container = $("<div class='image-preview box controller ui-widget-content ui-corner-all' />").css("text-align", "center").css("padding-top", "1ex");
		p_container.insertAfter(p);
		
		$("<canvas class='preview-canvas' width='200' height='200'/>").appendTo(p_container).click(function() {
			p.parent().find(".image-preview").remove();
			image.val("");
			T.f = null;
			target.find("form[name='post-form']").removeAttr("enctype");
		});
		$("<p>投稿ボタンでこのイメージを一緒にアップロードします。<br />キャンセルする場合、画像をクリックしてください。</p>").css("padding", "0 1ex 1ex 1ex").css("font-size", "80%").css("text-align", "left").appendTo(p_container);
		var canvas = p_container.find(".preview-canvas")[0];
		var reader = new FileReader();
		reader.onload = function(evt) {
			var image = new Image();
			image.onload = function() {
				var w = image.width, h = image.height;
				if (w > h) {
					if (w > 200) {
						h = h * (200 / w);
						w = 200;
					}
				} else {
					if (h > 200) {
						w = w * (200 / h);
						h = 200;
					}
				}
				canvas.width = w;
				canvas.height = h;
				var ctx = canvas.getContext("2d");
				ctx.drawImage(image, 0, 0, w, h);
			}
			image.src = evt.target.result;
		}
		T.f = f;
		reader.readAsDataURL(f);
	});
}
T.f = null;
T.autoLink = function(target, pureLink) {
	var all_reg = new RegExp("(https?://\\S+)", "ig");
	$(target ? target : ".body:not(.anc) span").each(function() {
		var t = $(this);
		t.html(t.html().replace(
			all_reg,
			"<a href=\"$1\">$1</a>"
		));
		if (! pureLink) {
			t.find("a").each(function() {
				this.href = T.base+"url/"+encodeURIComponent(encodeURIComponent(this.href));
			});
		}
		t.parent().addClass("anc");
	});
}

$(function() {
	$(".button").button();
	if ($("#control-box").length == 0) {
		$("#content-container").removeAttr("id");
	}
});

jQuery.fn.extend({
	insertAtCaret: function(myValue){
		return this.each(function(i) {
			if (document.selection) {
				//For browsers like Internet Explorer
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}
			else if (this.selectionStart || this.selectionStart == '0') {
				//For browsers like Firefox and Webkit based
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
				this.focus();
				if ($.browser.opera) {
					this.selectionStart = startPos + myValue.length+1;
				} else {
					this.selectionStart = startPos + myValue.length;
					this.selectionEnd = startPos + myValue.length;
					this.scrollTop = scrollTop;
				}
			} else {
				this.value += myValue;
				this.focus();
			}
		})
	}
});