var busy = false;

function isValid(type, text)
{
	switch (type)
	{
		case "text":
			if (!text.match(/^[àâéèêëîôöùüçÉÊÀÔa-zA-Z0-9\.\,\-\'\s]+$/)) return false;
		break;

		case "mail":
			if (!text.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/)) return false;
		break;

		case "alternate":
			if (text.search(/^[\<\>\=]$/) != -1) return false;
		break;
	}
	return true;
}

function focusOn(me)
{
	if (me.getAttribute("id") == "cAuthor") { if ($F(me) == $F("cAuthorDefault")) $(me).value = ""; }
	if (me.getAttribute("id") == "cComment") { if ($F(me) == $F("cCommentDefault")) $(me).value = ""; }
}

function focusOut(me)
{
	if (me.getAttribute("id") == "cAuthor") { if ($F(me) == "") $(me).value = $F("cAuthorDefault"); }
	if (me.getAttribute("id") == "cComment") { if ($F(me) == "") $(me).value = $F("cCommentDefault"); }
}

function wordTrim(word)
{
    return word.replace(/^\s+|\s+$/, '');
}

function refreshComments()
{
	$('cAuthor').value = $F('cAuthorDefault');
	$('cComment').value = $F('cCommentDefault');
	
	new Ajax.Updater('commentList', '/blog/ajax/process.php', {
		method: "post",
		encoding: "UTF-8",
		parameters: { id: $F('cID') }
	});
}

function isTooLong(string)
{
	var wordList = new Array();
	wordList = string.split(" ");
	for (var i = 0; i < wordList.length; i++)
	{
		if (wordList[i].length > 32) return true;
	}
	
	return false;
}

function sendComment()
{
	$('cButton').blur();
	
	if (busy)
	{
		alert("attendez !");
		return true;
	}

	if (isTooLong($F('cAuthor'))) { alert("votre nom contient un ou plusieurs mots trop longs"); return false; }
	if (isTooLong($F('cComment'))) { alert("votre commentaire contient un ou plusieurs mots trop longs"); return false; }
	if ($F('cComment') == $F('cCommentDefault')) { alert("vous n'avez rien écrit !"); return false; }
	if ($F('cComment') == "") { alert("vous n'avez rien écrit !"); return false; }
	if ($F('cAuthor') == $F('cAuthorDefault')) $('cAuthor').value = "anonyme";
	
	busy = true;

	var author = $F('cAuthor');
	var comment = $F('cComment');
	var id = $F('cID');
	var url = "http://www.tichat.com/blog/ajax/process.php";
	var parameters = "do=new&id=" + id + "&author=" + author + "&comment=" + comment;

	/*
	if (!comment.match(/^[àâéèêëîôöùüçÀÂÉÈÊËÎÔÖÙÜa-zA-Z\-\s]+$/))
	{
		alert("caractères interdits !");
		busy = false;
		return false;
	}
	*/
	
	new Ajax.Request(url, {
		method: "post",
		encoding: "UTF-8",
		parameters: parameters,
		onSuccess: function(transport) {
			busy = false;
			// alert(transport.responseText);
			refreshComments();
		}
	});
}
