/**
 * Internationalization
 *
 * (c) EZdesign.de
 *
 * Author:   Timo Besenreuther
 * Created:  2010-04-17
 * Modified: 2010-05-08
 */

function EzLibrary_Internationalization() {
	
	var lang;
	var translation = null;
	var queue = [];
	var obj = this;
	
	this.loadMsgFiles = function(component, fileName) {
		$.post('includes/ezajax/ezajax.php', {
			'module': 'EzLibrary',
			'namespace': 'Root',
			'class': 'Internationalization',
			'method': 'ajaxLoadMsgFiles',
			'msgComponent': component,
			'msgFileName': fileName
		}, function(response) {
			lang = response.lang;
			translation = response.translation;
			notifyAll();
		}, 'json');
	};
	
	this.wait = function(callback) {
		if (translation == null) {
			queue.push({
				'key': false,
				'callback': callback
			});
		} else {
			callback();
		}
	};
	
	this.get = function(key, callback) {
		if (!callback) {
			return this.directGet(key);
		}
		if (translation == null) {
			// asynchronous mode
			queue.push({
				'key': key,
				'callback': callback
			});
			return false;
		}
		callback(this.directGet(key));
		return true;
	};
	
	this.directGet = function(key) {
		if (!key || key == '') return key;
		try {
			var value = translation[key][lang];
			return decode(value);
		} catch (e) {
			return key;
		}
	};
	
	var decode = function(value) {
		var matches = value.match(/\[[^\]]+\]/gi);
		if (matches != null) {
			for (var i = 0; i < matches.length; i++) {
				var match = matches[i];
				value = value.replace(match, '<' + match.substring(1, match.length - 1) + '>');
			}
		}
		value = value.replace(/\n/g, '<br />');
		return value;
	};
	
	var notifyAll = function() {
		while (queue.length > 0) {
			var item = queue.pop();
			obj.get(item.key, item.callback);
		}
	};
	
}
