function post_button_enable()
{
    var form = document.getElementById("inputform");
    form.post.disabled = (form.m.value == "");
}

function post_message(form)
{
    form.post.disabled = true;

    $.ajax({
	type: "POST",
	url: "post.cgi",
	data: "mode=mesg&m=" + encodeURIComponent(form.m.value) + "&n=" + encodeURIComponent(form.n.value),
	success: function(res) {
	    form.m.value = "";
	    if (!res) {
		post_button_enable();
		alert("エラーっぽいです");
	    } else {
		var obj = $("#list li").get(0);
		if (obj)
		    obj.className = "";
		$("#list").prepend(res);
	    }
	}
    });
    return false;
}

function latest()
{
    rebuild_list('latest');
    return false;
}

function ranking()
{
    rebuild_list('ranking');
    return false;
}

function on_next_page_success(res)
{
    $("#list").append(res);
    if ($("#nextid") && $("#nextid:first") && $("#nextid:first").text()) {
	$("#readmoreguruguru").fadeOut(
	    function() {
		$("#readmoretext").show();
	    });
    } else {
	$("#readmore").fadeOut();
    }
}

function display_next_page()
{
    $("#readmoretext").fadeOut(
	function() {
	    $("#readmoreguruguru").fadeIn(
		function() {
		    var nextid = $("#nextid:first").text();
		    $("#nextid").remove()
		    $.ajax({
			type: "GET",
			url: "index.cgi",
			data: "s=" + encodeURIComponent(nextid),
			success: on_next_page_success
		    })
		});
	});
    return false;
}

function on_load_index()
{
    post_button_enable();

    // onkeypress とかだけだと IME 経由時にハンドルできないことがあるので
    // ポーリングする
    var form = document.getElementById("inputform");
    form.m.onchange = form.m.onclick = form.m.ondblclick = form.m.onfocus =
	form.m.onblur = form.m.onkeyup = form.m.onkeydown = post_button_enable;
    setInterval(post_button_enable, 100);

    // nextid があればもっと読むを有効にする
    if ($("#nextid").get(0)) {
	$("#readmoreguruguru").hide();
	var readmore = $("#readmore");
	readmore.css("display", "block");
	readmore.get(0).onclick = display_next_page;
    }
}
