// require prototype

var Mbox = 
{
	container: null,
	options: {},
	messages: [],
	counter: 0,
	
	// messages types
	MB_NOTICE: 'notice',
	MB_WARNING: 'warning',
	MB_ERROR: 'error',
	
	template: {brief: null, full: null},
	
	init: function(container_id, options) {
		this.container = $(container_id);
		if (options) {
			this.setOptions(options);
		}
		this.template.brief = '<li id="#{id}" class="#{type}">#{text}</li>';
		this.template.full  = '<li id="#{id}" class="#{type}"><strong>#{text}</strong><br>#{details}</li>';

		// load localized messages
		// ...
		if (!this.container) { return; }
		if (this.isEmpty()) {
			this.hide();
		}
	},
	
	setOptions: function(options) {
		this.options = options || {};
	},
	
	addMessage: function(type, text, details, params) {
		if (!this.container || !text.length) { return; }
		this.counter++;
		var id = 'mbox_' + type + '_' + this.counter,
			text = this.getText(text, params),
			details = this.getText(details, params),
			template = this.template[details.length ? 'full' : 'brief'];
		this.container.insert({bottom: this.getText(template, {id: id, type: type, text: text, details: details})});
		this.show();
		this.fire('MessageAdd', $(id));
	},
	
	addNotice: function(text) {
		details = arguments[1] || '';
		params = arguments[2] || {};
		this.addMessage(this.MB_NOTICE, text, details, params);
	},
	
	addWarning: function(text) {
		details = arguments[1] || '';
		params = arguments[2] || {};
		this.addMessage(this.MB_WARNING, text, details, params);
	},
	
	addError: function(text) {
		details = arguments[1] || '';
		params = arguments[2] || {};
		this.addMessage(this.MB_ERROR, text, details, params);
	},
	
	fillFromArray: function(arr) {
		arr.each(function(el) {
			this.addMessage(el.type, el.text, el['details'], el['params']);				
		}.bind(this));
	},
	
	isEmpty: function() {
		return this.container.empty();
	},
	
	hide: function() {
			this.container.hide();
	},
	
	show: function() {
		//if (this.isEmpty()) { return; }
		this.container.show();
	},
	
	fire: function(event, message) {
		(this.options['on' + event] || Prototype.emptyFunction)(message);
	},
	
	getText: function(alias) {
		alias = this.messages[alias] || alias
		return this._format(alias, arguments[1] || {});
	},
	
	_format: function(text, params) {
		return new Template(text).evaluate(params);
	}
}
