if(typeof Integrity === 'undefined'){
	Integrity = {};
}

if(typeof Integrity.Locale === 'undefined'){
	Integrity.Locale = {};
}

// create storage for message resources
Integrity.Locale.storage = {};

window.L = Integrity.Locale.getString = function(key, subsObj) {
	var strings = Integrity.Locale.storage;
	var value = key;
	if (typeof strings[key] === 'string') {
		value = strings[key];
		// if value starts with a "@" - this is reference to other message.
		// we need to replace current message with referenced one and replace a message to not search it anymore.
		if(value.charAt(0) === "@"){
			value = Integrity.Locale.getString(value.substr(1));
			strings[key] = value;
		} else if (value.charAt(0) === "\\" && value.substr(0, 2) === "\\@"){
			// escaped reference - need to remove leading symbol
			value = value.substr(1);
		}
	}

	// replace %1, %2...%n with corresponding arguments value
	// also named parameters are supported
	if(arguments.length > 1 && typeof value === "string"){
		if(typeof subsObj !== "undefined" && subsObj instanceof Object){
			for(var param in subsObj){
				value = value.replace(new RegExp("(^|([^\\\\]))\%"+param, "g"), "$2" + subsObj[param].toString());
			}
		} else {
			// substitute by number
			for(var ii = 1; ii < arguments.length; ii++){
				if(arguments[ii] == null){
					continue;
				}
				value = value.replace(new RegExp("(^|([^\\\\]))\%"+ii, "g"), "$2" + arguments[ii].toString());
			}
		}
	}
	
	return value;
};

Integrity.Locale.set = function(oDict) {
	var aPhrases = Integrity.Locale.storage;

	// convert nested messages into dot-separated string
	function fFlatten(prefix, values){
		if(typeof values == "string"){
			aPhrases[prefix] = values;
			return;
		}

		if(prefix != ""){
			prefix += ".";
		}

		for (var sKey in values) {
			fFlatten(prefix + sKey, values[sKey]);
		}
	}

	fFlatten("", oDict);
};

Integrity.Locale.localize = function(target){
	if(typeof target === "undefined"){
		target = $("body, head");
	}

	target.find('[data-l], [data-l-title]').not('[data-l-processed]').each(function(i, el){
		el = $(el).attr('data-l-processed', true);
		var key = el.attr('data-l') || el.attr('data-l-title');
		if(el.attr('data-l-title')){
			el.attr('title', L(key));
		} else {
			// localize depending on tagname
			var tagName = el.get(0).tagName.toLowerCase();
			switch(tagName) {
				case "input":
					el.val(L(key));
					break;
				default:
					el.html(L(key));
			}
		}
	});
};

if(typeof $ !== "undefined"){
	$.fn.i18n = function(){
		Integrity.Locale.localize(this);
		return this;
	};
}


