var keys;
var found = Array();

function resultSort(a,b){
	return a.offset-b.offset;
}

function repl(el){

	var results = new Array();
	if (el.nodeType==1)
		if (el.nodeName=="A")
			return;
		else
			$each(el.childNodes,function(child){repl(child);});

	if (el.nodeType!=3)
		return;

	keys.each(function(key){
 		reg = new RegExp('(^|\\W)('+key.wort+')($|\\W)','gi');
		el.data.replace(reg, function (str, p1,w,p2, offset, s){
			if (p1.length>0) offset+=1;
			results.push({"offset":offset,"wort":w,"id":key.id});
			key["found"]=1;
		});
	});
	results.sort(resultSort);
	offset = 0;
	results.each(function(x){
		textNode = document.createTextNode(el.data.substring(0,x.offset-offset));
		el2 = document.createElement('a');
		el2.setAttribute('href','index.php?StoryID=183&id='+x.id+'#'+x.id);
		el2.setAttribute('className','tooltip tooltip_'+x.id);
		el2.setAttribute('class','tooltip tooltip_'+x.id);
		el2.appendChild(document.createTextNode(x.wort));
		el.parentNode.insertBefore(textNode,el);
		el.parentNode.insertBefore(el2,el);
 		el.data=el.data.substring(x.offset+x.wort.length-offset,el.data.length);
 		offset = x.offset+x.wort.length;
	});
}

function texteZuweisen(res){
	res.each(function(x){
		$$('.tooltip_'+x.id).each(function(y){
			y.store('tip:title', x.wort);
// 			y.store('tip:text', decode_utf8(x.beschreibung.substring(0, 200))+"...<br /><i>(Bitte klicken Sie auf den Begriff, um weiter zu lesen!)</i>");
			y.store('tip:text', x.beschreibung.substring(0, 200)+"...<br /><i>(Bitte klicken Sie auf den Begriff, um weiter zu lesen!)</i>");
		});
	});
}

function texteLaden(){
	keys.each(function(key){
		if (key.found)
			found.push(key.id);
	});
	if (found.length==0) return;
	new Json.Remote('glossar/ajax.php5?action=texte', {onComplete: function(res){
		texteZuweisen(res);
		new Tips($$('.tooltip'), {className:'tool',offsets: {'x': 10, 'y': 10},maxTitleChars: 2050 });
	}}).send(found);
}

function glossar(el){
	//alert ("ja2");
	new Json.Remote('glossar/ajax.php5?action=keys', {onComplete: function(res){
		keys=res;
		repl(el);
		texteLaden();
	}}).send();

}


window.addEvent('domready', function() {
 
	glossar($('content'));
});
 
 
function decode_utf8(utftext) {
	var plaintext = ""; 
	var i=0; 
	var c=c1=c2=0;
	
	while(i<utftext.length)
	{
	
	c = utftext.charCodeAt(i);
	
	if (c<128) {
	plaintext += String.fromCharCode(c);
	i++;}
	else if((c>191) && (c<224)) {
	c2 = utftext.charCodeAt(i+1);
	a=String.fromCharCode(((c&31)<<6) | (c2&63));
	if(c2==376)
	{
	a="&szlig;";
	}
	plaintext += a;
	
	
	i+=2;}
	else {
	c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
	plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
	i+=3;}
	}
	
	return plaintext;
}

