// 文字コード：UTF-8
var chat_last_id = -1;
var chat_timer;

function chat_set_timer()
{
	if(document.chatform.chat_highspeed.checked){
		var time = 1000;
	} else {
		var time = 30000;
	}
	clearTimeout(chat_timer);
	chat_timer = setTimeout('chat_require_update()', time);
}

function chat_update(obj)
{
	var res = eval( '(' + obj.responseText + ')' );
	if(res.update == 1){
		$('chat_list').innerHTML = res.chat_list;
		chat_last_id = res.chat_last_id;
	}
	$('chat_user').innerHTML = res.chat_user;
	chat_set_timer();
}

function chat_require_update()
{
	var url = document.URL.split("#")[0];
	new Ajax.Request(url, {
		method: "post",
		parameters: "chat_last_id=" + chat_last_id,
		onSuccess: chat_update,
		onFailure: chat_set_timer
	});
}

function chat_send()
{
	var name  = document.chatform.name.value;
	var color = document.chatform.color.value;
	var body  = document.chatform.body.value;
	
	if((name != "") && (color != "") && (body != "")){
		var param = "chat=1&name=" + encodeURIComponent(name) + "&color=" + encodeURIComponent(color) + "&body=" + encodeURIComponent(body);
		var url = document.URL.split("#")[0];
		new Ajax.Request(url, {
			method: "post",
			parameters: param,
			onSuccess: chat_update,
			onFailure: chat_set_timer
		});
		document.chatform.body.value = "";
		document.chatform.body.focus();
	} else {
		chat_require_update();
	}
}

function chat_keydown(event)
{
	if(event.keyCode == Event.KEY_RETURN){
		chat_send();
	}
}

function chat_switch_highspeed()
{
	if(document.chatform.chat_highspeed.checked){
		$('chat_highspeed_status').innerHTML = "<span class=\"emphasis\">ON</span> / <span class=\"weak\">OFF</span> （1秒ごとに自動リロード）";
	} else {
		$('chat_highspeed_status').innerHTML = "<span class=\"weak\">ON</span> / <span class=\"emphasis\">OFF</span> （30秒ごとに自動リロード）";
	}
	chat_set_timer();
}

window.onload = chat_require_update;
