/**
 * Class to show toast messages.
 **/
module.exports =
{
	 maxMessages: 6
	,timeout: 10 /* Seconds */
	,_container: null
	,_timeouts: null

	/**
	 * Shows a normal toast message.
	 *
	 * @param String message The message text
	 **/
	,showMessage: function (message)
	{
		this._showText (message, 'message');
	}
	
	/**
	 * Shows a warning toast message.
	 *
	 * @param String message The message text
	 **/
	,showWarning: function (message)
	{
		this._showText (message, 'warning');
	}
	
	/**
	 * Shows an error toast message.
	 *
	 * @param String message The message text
	 **/
	,showError: function (message)
	{
		this._showText (message, 'error');
	}
	
	/**
	 * Hides all currently displayed toast messages.
	 **/
	,hide: function ()
	{
		if (!this._container)
			return;

		if (this._timeouts)
		for (var i = 0; i < this._timeouts.length; i++)
			clearTimeout (this._timeouts[i]);

		this._timeouts = null;			

		document.removeEventListener ('mousedown', this.hideHandler);
		Vn.Node.remove (this._container);
		this._container = null;
		this.nodes = [];
	}

	,_createContainer: function ()
	{
		if (this._container)
			return;
	
		var container = document.createElement ('div');
		container.className = 'htk-toast';
		document.body.appendChild (container);

		this.hideHandler = this.hide.bind (this);
		document.addEventListener ('mousedown', this.hideHandler);

		this._timeouts = [];
		this._container = container;
	}

	,_showText: function (message, className)
	{
		this._createContainer ();

		if (this._timeouts.length >= this.maxMessages)
			this._onMessageTimeout ();
		
		var node = document.createElement ('div');
		node.className = className;
		node.addEventListener ('mousedown', this._onMessageMouseDown);

		var textNode = document.createTextNode (message);
		node.appendChild (textNode);

		this._container.appendChild (node);

		var timeoutId = setTimeout (this._onMessageTimeout.bind (this), this.timeout * 1000);
		this._timeouts.push (timeoutId);
	}

	,_onMessageTimeout: function ()
	{
		if (!this._container)
			return;
	
		var nodes = this._container.childNodes;
	
		if (nodes.length > 0)
		{
			clearTimeout (this._timeouts.shift ());
			Vn.Node.remove (nodes[0]);
		}
		if (nodes.length == 0)
			this.hide ();
	}
	
	,_onMessageMouseDown: function (event)
	{
		event.stopPropagation ();
	}
};
