/*
# $Id$
*/

/*
# @namespace App.I18n
*/
App.I18n = {

	/*
	# @property object dictionary
	# Object holding all translations in current locale.
	*/
	dictionary: {},

	/*
	# @property string locale
	# Currentt default locale.
	*/
	locale: null,

	/*
	# @method void add( object translations )
	# translations	= List of translations (format: {english-string: "locale-string", ...})
	#
	# Adds the specified list of translations to the current dictionary.
	# This will overwrite any existing translations with the same index.
	*/
	add: function(translations) {
		for(var i in translations) {
			App.I18n.dictionary[i] = translations[i];
		}
	},

	/*
	# @method void setDefaultLocale( string code )
	# code	= Locale code (ISO 639; xx)
	#
	# Sets the defaults locale.
	*/
	setDefaultLocale: function(code) {
		this.locale = code;
	},

	/*
	# @method string translate( string string )
	# string	= String to be translated
	#
	# Translates all placeholders in the given string.
	# See documentation in server-side "AppView" class for further details.
	*/
	translate: function(string) {
		var tString = string;
		var matches = string.match(/\[t:[^\]]+\]/gim);
		if(matches===null) {
			return tString;
		}

		for(var i=0; i<matches.length; i++) {

			// Split string into separate parts (delimited by ":"), get the
			// translated version of the last part and perform variable
			// replacements on it
			var parts = matches[i].replace(/^\[([^\]]+)\]$/gim, "$1").replace(/([^\\]):/gim, "$1!!split!!").split('!!split!!');
			parts.shift();
			var lString = parts.pop();	/* TODO: This will eventually be loaded from a table of translations somewhere */
			lString = App.I18n.dictionary[lString] ? App.I18n.dictionary[lString] : lString;
			for(var j=0; j<parts.length; j++) {
				lString = lString.replace(/%[a-z]/im, parts[j].replace(/\\:/, ':'));
			}

			// Replace in original string
			var re = new RegExp(matches[i].replace(/([\$\^\*\(\)\-\+\\\|\.\/\?\[\{\]\}])/gim, "\\$1"), 'gm');
			tString = tString.replace(re, lString);
		}
		return tString;
	}
};