/* vk-lang */

/*
  Für folgende Attribute wird der Text automatisch übersetzt:
    title

  HTML-Text muss mit Funktion tag getagged werden:
    lang.tag("Mein Text)
 */


var VKLang = function(conf) {
    var that = VK(conf),
    conf = conf,
    lang = null,
    langs = null,
    attach = function(cnt) {
	var txts = [];
	if ((langs.length == 0) || ((langs.length == 1) && (lang == 'de'))) {
	    return(txts);
	}
	$("span.lang", cnt).each(function(i) {
		var txt = VKLangTxt({cnt: $(this),
				     lang: that,
				     txt: $(this).text()});
		txts.push(txt);
	    });
	$("[title]", cnt).each(function(i) {
		var title, txt;
		title = $(this).attr("title");
		txt = VKLangTxt({cnt: $(this),
				 lang: that,
				 attrs: {title: $(this).attr("title")}});
		txts.push(txt);
	    });
	return(txts);
    },
    create = function() {
	langs = [];
	for (k in conf.langs) {
	    if(conf.langs.hasOwnProperty(k)) {
		langs.push(k);
	    }
	}
	if (langs.length > 0) {
	    lang = langs[0];
	}
	if (conf.lang) {
	    lang = conf.lang;
	}
    },
    detach = function(txts) {
	var i;
	if ((langs.length == 0) || ((langs.length == 1) && (lang == 'de'))) {
	    return;
	}
	for (i = 0; i < txts.length; i++) {
	    that.updateableRemove(txts[i]);
	}
    },
    dir = function() {
	if (lang == 'he') {
	    return('rtl');
	}
	else {
	    return('ltr');
	}
    },
    get = function() {
	return(lang);
    },
    keys = function(key) {
	return(langs);
    },
    text = function(key) {
	var val = conf.langs[lang].lexicon[key];
	return(val);
    },
    key = function() {
	return(lang);
    },
    set = function(l) {
	lang = l;
	that.updateUpdateables({hint: "lang", lang: lang});
    },
    tag = function(txt) {
	if ((langs.length == 0) || ((langs.length == 1) && (lang == 'de'))) {
	    return(txt)
	}
	else {
	    return('<span class="lang">'+txt+'<\/span>');
	}
    };
    that.attach = attach;
    that.detach = detach;
    that.dir = dir;
    that.get = get;
    that.key = key;
    that.keys = keys;
    that.set = set;
    that.text = text;
    that.tag = tag;
    create();
    return(that);
};


var VKLangTxt = function(conf) {
    var that = VK(conf),
    cnt = conf.cnt,
    lang = conf.lang,
    txt = conf.txt,
    attrs = conf.attrs,
    create = function() {
	lang.updateableAdd(that);
	update();
    },
    update = function() {
	var text;
	if (txt) {
	    text = lang.text(txt);
	    if (text) {
		cnt.text(text);
	    }
	}
	else if(attrs) {
	    text = lang.text(attrs.title);
	    if (text) {
		cnt.attr("title", text);
	    }
	}
	else {
	    text = null;
	}
    };
    create();
    that.update = update;
    return(that);
};
