// 
/*
Object: PACLocale
	Library to hold localization strings. A Hashmap is used to store localization strings that can be accessed by their ID.
	The Library contains all translation strings of the current locale.
	
	Methods are provided to change the locale (this.loadLocale()).
	Url to fetch content from has to return a JSON-Object with key:Value pairs.

	There are two main methods: localize() and translate()
	Where the former replaces translations keys with the current translation and returns the translated string,
	the latter performs a lookup to a given translation key.
	
	You can localize strings using this.localize().
	Further the shortcut $t() is defined to access PAC.localeLib
	
Author: Carsten

Example: 
	[javascript]
	var lib = new PACLocale({ 'locale' : "de" });
	lib.localize('sdfsdfa $t{username} juhu!! dasfasf {dsafds ()');
	// will return 'sdfsdfa Benutzername juhu!! dasfasf {dsafds ()'
	[/javascript]
*/

PACLocale = new Class ({
	
	options : {
		baseUrl : contextPath + "/languagepack?locale=",
		loadFromServer : false
	},
	
	initialize: function(options){
		this.library = $H(); //init localization
		if ($defined(options.locale)) {
			this.loadLocalization(options.locale);
		}
	},
		
	/*
	Method: loadLocalization - Fetches a library from the server if url is given with initialize.
		
	Arguments:
		localizationName      - (string) localization name for which to fetch the data
		reset				  - (boolean) whether or not the library should be reset before loading new content
	*/
	loadLocalization: function(localizationName, reset) {
		var url = this.options.baseUrl + localizationName;
		if(this.request){
			// cancel a still running previous request
			// (does nothing if request already finished)
			this.request.cancel();
		}
		if(reset === true){
			this.library = $H();
		}
		if ($defined(babylonDestroyer)) {	// language keys are provided in main.jsp in global variable babylonDestroyer
			this.library.extend(babylonDestroyer);
		} else {
			this.request = new Ajax(url, {
				method: 'get',
				//async: true, // we have to wait to translate until localizations are back
				onComplete: this.bindContent.bind(this),
				evalScripts: false
			}).request();
		}
	},
	
	/*
	Method: 
		bindContent - loads JS-Translation-Object into the library
		
	Arguments:
		data - JSON Data from the sever
	*/
	bindContent: function(result) {
		if(this.request.transport.status === 200){
			//evalScripts throws an invalid label error so we do:
			this.library.extend(Json.evaluate(result));
		}
	},
	
	/*
	Method: localize
		Localizes a given String by replacing all occurances of $t{myLocalizationKey} by its current translation.
		If given a single translation key the translation will be returned accordingly.

	Arguments:
		stringToLocalize - (string)
		replacements - (object) contains key-value pairs, where all keys in the translated string get replaced by escaped values.
	
	Example:
		$t("$t{PACMyPac.myTranslation} ", { "" : "hallo" })
	*/
	localize: function(stringToLocalize, replacements){
		var multiTranslate = stringToLocalize.match(/\$t{[^{}]+}/g);
		
		if(multiTranslate){
			var getTranslation = function(key){
				return stringToLocalize.replace(key, this.translate(key.slice(3,key.length-1)) || "NO TRANSLATION FOUND FOR: " + key.slice(3,key.length-1) );
			}.bind(this);
		
			multiTranslate.each(function(key){
				stringToLocalize = getTranslation(key);
			});
		} else {
			//single translation
			stringToLocalize = this.translate(stringToLocalize) || stringToLocalize;
		}
		
		//variable replacements:
		if(replacements){
			for(rep in replacements){
				stringToLocalize = stringToLocalize.replace(rep, PACHelper.escapeEntities(replacements[rep]+""));
			}
		}
		
		return stringToLocalize; 
	},
	
	/*
	Method: translate
		Returns a translation string mapped on a given key.
		Adds new localization if a new localization (translationString) is passed.
		Note that changed translations are not stored on the server and are lost after reload.
	Arguments:
		translationKey - (string) Translation KeyName to access the localization string.
		translationString - (string) Translation to be associated to the key.		
	 */
	
	translate: function(translationKey, translationString){
		if($defined(translationString)){
			this.library.set(translationKey, translationString);
		}
		var translation = this.library.get(translationKey);
		return translation;
	}
});

/*
Method: $t
	Shortcut for myPacLocaleInstance.localize();
	Returns the translation of a String, i.e. a String in which all occurences of $t{mylocalizationKey} have been replaced by tranlsations.
	PAC.localeLib is asked for translations.
	
See: PACLocale.localize(); for more Info.
*/
$t = function(stringToLocalize, replacements){
	return PAC.localeLib.localize(stringToLocalize, replacements);
};