/**
 * The MessageHandler stores and displays error messages
 * associated with error codes.
 * Error codes have the form error.a.b.c. Special rules apply:
 * If an error code that is used in the application is not
 * defined here, or is set to empty string or a string
 * starting with the character ?, then the error code
 * error.a.b (with the last part removed) is used.
 * If neither error.a.b nor error.a is defined, then the
 * default error code error is used, displaying the message
 * "Error: error.a.b.c".
 * This process can be stopped by defining error.a.b.c=!
 * (any string starting with the character !). This means
 * that no error message will be given for the error code
 * error.a.b.c.
 */
function MessageHandler() {
	this.messageMap = new Array();
}

MessageHandler.prototype.addMessage = function(key, msg) {
	this.messageMap[key] = msg;
}

MessageHandler.prototype.showMessage = function(inkey, params) {
	var key = inkey;
	if (key == undefined) key = 'undefined';
	var msg = this.messageMap[key];
	while (msg == undefined || msg == null || msg == '' || msg.charAt(0) == '?') {
		var index = key.lastIndexOf('.');
		if (index == -1) {
			msg = this.messageMap['default.error'];
			params = inkey;
			break;
		}
		key = key.substring(0, index);
		msg = this.messageMap[key];
	}

	if (msg == undefined
		|| msg == null
		|| msg == ''
		|| msg.charAt(0) == '?'
		|| msg.charAt(0) == '!') return;

	if (params != undefined) {
		if (params instanceof Array) {
			for (var i = 0; i < params.length; i++) {
				msg = msg.replace(new RegExp('\\{' + i + '\\}', 'g'), params[i]);
			}
		} else {
			msg = msg.replace(new RegExp(/\{0\}/g), params);
		}
	}
	alert(msg);
}

