Ext.ns('Nexts');

Nexts.Resources = function() {
	var global = '__global__';
	var deflang = '_';
	var resMap = {};
	var resChain = [ deflang ];
	
	function findValue(key, res) {
		var v = null;
		if (res) {
			for (var i in resChain) {
				var r = res[resChain[i]];
				if (r) {
					v = Nexts.findValue(key, r);
				}
				if (v != null) {
					return v;
				}
			}
		}
		return v;
	}
	
	return {
		bind: function(name, locale, res) {
			if (arguments.length == 2) {
				res = locale;
				locale = name;
				name = global;
			}
			else if (arguments.length == 1) {
				res = name;
				locale = deflang;
				name = global;
			}

			var r = resMap[name];
			if (!r) {
				r = {};
				resMap[name] = r;
			}
			r[locale] = res;
		},
		
		unbind: function(name, locale) {
			name = name || global;
			var res = resMap[name];
			if (res) {
				delete res[locale];
			}
		},

		setChain: function(chain) {
			resChain = [].concat(chain);
			if (chain.indexOf(deflang) < 0) {
				resChain = resChain.concat([ deflang]);
			}
		},

		getText: function(name, key, defvar) {
			if (arguments.length == 1) {
				key = name;
				name = global;
			}
			
			var v = null;
			var res = resMap[name];
			if (res) {
				v = findValue(key, res);
			}
			if (v == null && name != global) {
				res = resMap[global];
				v = findValue(key, res);
			}
			
			return v == null ? defvar : v;
		}
	}
}();

