var chat_lastTime = 0;
var chat_refresh_time = 1500;

function chat_MAJ()
{
	new Ajax.Request(
	 'ajax.php',
	 {
		method: 'get',
		parameters: {time: chat_lastTime, d: "action", a: "chat"},
		onSuccess: function(transport, json) {
				if (json.messages.length > 0)
				{
					for(i=json.messages.length-1; i>=0; i--)
					{
						//On tranforme le timestamp en date correcte
						var date = new Date();
						var now = new Date();
						date.setTime(json.messages[i]["timestamp"]*1000);

						//On affiche tout
						var newRow = $('chat').insertRow(0);
						var newCell = newRow.insertCell(0);
						if (date.getDay() != now.getDay())
							newCell.innerHTML = '[' + json.messages[i]["pseudo"] + '] ' + (date.getDay()<10?"0"+date.getDay():date.getDay()) + "/" + (date.getMonth()<10?"0"+date.getMonth():date.getMonth()) + " " + (date.getHours()<10?"0"+date.getHours():date.getHours()) + ":" + (date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes()) + ":" + (date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds());
						else
							newCell.innerHTML = '[' + json.messages[i]["pseudo"] + '] ' + (date.getHours()<10?"0"+date.getHours():date.getHours()) + ":" + (date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes()) + ":" + (date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds());
    					newCell = newRow.insertCell(1);
						newCell.innerHTML = json.messages[i]["message"];
						if (chat_lastTime < json.messages[i]["timestamp"])
							chat_lastTime = json.messages[i]["timestamp"];
					}
				}
			},
		onFailure: function() { chat_MAJ(); }
	 }
	);
	chat_refresh = setTimeout("chat_MAJ()", chat_refresh_time);
}

function chat_clearScreen()
{
	$('chat').innerHTML = "";
	chat_write("JS", "Nettoyage de l'écran");
}

function chat_refreshScreen()
{
	chat_refresh = setTimeout("chat_MAJ()", 1);
}

function chat_reset()
{
	chat_lastTime = 0;
}

function chat_changeRefreshTime(newTime)
{
	if (newTime > 0)
	{
		if (newTime < 999)
			newTime *= 1000;
		chat_refresh_time = newTime;

		chat_write("JS", "Temps de rafraîchissement passé à " + newTime/1000 + " seconde(s)");
	}
}

function chat_sendCommande(commande)
{
	new Ajax.Request(
	 'ajax.php?d=action&a=chat',
	 {
		method: 'post',
		parameters: {comm: commande},
		onSuccess: function(transport, json) {
			if (json.confirm)
				chat_write("Server", json.confirm);
			else
				chat_write("Server", "Rien");
			},
		onFailure: function() { alert("La requête a échouée!"); }
	 }
	);
}

function chat_write(posteur, message)
{
	var date = new Date();
	var newRow = $('chat').insertRow(0);
	var newCell = newRow.insertCell(0);
	newCell.innerHTML = '<em>' + posteur + '</em> ' + (date.getHours()<10?"0"+date.getHours():date.getHours()) + ":" + (date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes()) + ":" + (date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds());
	newCell = newRow.insertCell(1);
	newCell.innerHTML = "<em>" + message + "</em>";
}