var Translator = Class.create({

	initialize : function(dictionary_location, selectors_to_translate_initially) {
		if (!dictionary_location)  { return; }
	
		this.dictionary_location = dictionary_location;
		this.dictionary = {};
		
		var callback = selectors_to_translate_initially.length > 0 ? function() { this.translateSelectors(selectors_to_translate_initially); }.bind(this) : undefined;
		
		this.loadDictionary(callback);
	},
	
	loadDictionary : function(callback) {
		
		new Ajax.Request(this.dictionary_location, {
			onSuccess : function(response) {
				if (!response.responseText) { return; }
			
				try {			
					this.dictionary = response.responseText.evalJSON();
				} catch(e) {
					this.dictionary = {};
				}
			
				if (callback != undefined && typeof callback == 'function') { callback(); }
			}.bind(this)
		});
		
	},
	
	translate : function(selector) {
		$$(selector).each(function(n) {
			for (term in this.dictionary) {
				n.innerHTML = n.innerHTML.replace(new RegExp(term, "gi"), this.dictionary[term]);
			}
		}.bind(this));
	},
	
	translateSelectors : function(selectors) {
		if (!selectors || selectors.length == 0 || !this.hasTranslations()) { return; }
		
		for (var i = 0, num_selectors = selectors.length; i < num_selectors; i++) {
			this.translate(selectors[i]);
		}
	},
	
	getTranslationByTerm : function(term) {
		return this.dictionary[term] != undefined ? this.dictionary[term] : term;
	},
	
	hasTranslations : function() { return this.dictionary != undefined && this.dictionary != {}; }

});
