/******************* MESSAGES **********************************************/
var MESSAGES_DURATION = 8000; // in milliseconds
function initializeMessages() {
	new PeriodicalExecuter(markAndPopMessages, 3);	
} // initializeMessages

/*
 * Just highlight if message already exists.
 */
function addMessage(content, options) {
	var message = findMessage(content);
	if(message) {
		new Effect.Highlight(message);
	} else {
		var options = $H({ "class": "notice" }).merge($H(options));
		message = createMessage(content, options);
		getMessagesContainer().insert({ "top": message });	
	}
} // addMessage

function addMessageFromJSON(object) {
  if(object) {
    var messages = getMessagesContainer();
    var message = findMessage(object.message);

    if(! message) {
      message = new Element("div", { "class": object.klass }).update(object.message);
      messages.insert({bottom: message});
    }

    setTimeout(function() {
      new Effect.Highlight(message);
    }, 300);
  }
} // addMessageFromJSON

function findOrCreateMessage() {
	var message = findMessage(content) || createMessage(content, options);
} // findOrCreateMessage

function findMessage(content) {
	var founded = null;
	getMessages().each(function(node) {
		if(content == node.innerHTML) {
			founded = node;
			throw $break;
		};
	});
	return founded;
} // findMessage

function createMessage(content, options) {
	return new Element("div", { "class": options.get("class") }).update(content);	
} // createMessage

/*
 * Use a timestamp to mark and pop messages.
 * Set a timestamp to the div if it has'nt yet. Otherwise, calcule the difference
 * between the current timestamp and the attribute. If the diff is greater or equal
 * than the defined duration, destroy the message.
 */
function markAndPopMessages() {
	getMessages().each(function(node) {
		var timestamp_attribute = node.readAttribute("timestamp");
		if(timestamp_attribute) {
			if((timestamp() - timestamp_attribute) >= MESSAGES_DURATION) {
				new Effect.Fade(node, {
					duration: 0.5,
					afterFinish: function(e) {
						node.remove();
					}
				});
			}			
		} else
			node.writeAttribute("timestamp", timestamp());
	});
} // markAndPopMessages

function getMessagesContainer() {
	return $("messages");
} // getMessagesContainer

function getMessages() {
	return $$('#messages div');
} // getMessages

function timestamp() {
	return new Date().getTime();
} // timestamp

Event.observe(document, 'dom:loaded', initializeMessages);