/**************************************/
/* Message                            */
/**************************************/
noOfMessagesToShow = 10;

function Message()
{
  this.name = '';
  this.email = '';
  this.text = '';
  this.updated = '';
  this.repliesToID = 0;
  this.editMessage = 0;
  this.iconID = 0;
  this.html = '';
  this.ID = 0;
  this.guestbookID = 0;
  this.firstMessage = 0;

  this.loadFromXMLNode = function(node)
  {
    this.html = node.childNodes[0].childNodes[0].nodeValue;
    this.ID = node.attributes.getNamedItem("ID").value;
    this.name = node.childNodes[2].childNodes[0].nodeValue;
    this.updated = node.childNodes[3].childNodes[0].nodeValue;
  };

  this.save = function()
  {
    new Ajax.Request('save.php',
                     {method: 'post',
                      parameters: 'guestbookID=' + this.guestbookID + '&name=' + encodeURIComponent(this.name) + '&email=' + encodeURIComponent(this.email) + '&text=' + encodeURIComponent(this.text) + '&repliesToID=' + this.repliesToID + '&editMessage=' + this.editMessage,
                      onSuccess: this.saveSuccess,
                      onFailure: this.saveFailure});
  };

  this.saveSuccess = function(r)
  {
		/*
		It seams like the sound slows the client machine down.
		I did turn the sound off saving a new message (when time is more critical), for new messages on page reload the sound is still present.
		playSound('notify');
		*/
		pollMessages(true);
		$('repliesToID').value = 0;
		$('editMessage').value = 0;
		$('text').innerHTML = "";

    toggleEdit();
  };

  this.saveFailure = function(r)
  {
		pollMessages(true);
    toggleEdit();

    showErrorMessage('Något gick snett');
  };
}

function postMessage()
{
  // deletes ending spaces
	var name = $F('name').replace(/^\s+|\s+$/, '');
	var text = $F('text').replace(/^\s+|\s+$/, '');
	var email = $F('email').replace(/^\s+|\s+$/, '');

	if(name=="" || text=="")
	{
		showErrorMessage('Du måste ange både namn och text för ditt inlägg!');
	}
	else
	{
		var e = new Message();

		e.name = name;
		e.email = email;
		e.text = text;
		e.repliesToID = $F('repliesToID');
		e.editMessage = $F('editMessage');
		e.guestbookID = guestbookID;
    $('postMessage').src=images['write_disabled.png'];
		e.save();
	}
}

function noPostMessage()
{
	toggleEdit();
}