/**
* Fügt dem document ein Javascript hinzu
* Enthaltener Code wird NICHT! ausgeführt
* Funtionen können anschliesend ausgeführt werden
*/
function addScript(url) {
	script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	/*if( url.indexOf('?') > -1) {
		url += '&';
	}
	else {
		url += '?';
	}
	url += 'rand=' + Math.random();*/
	script.setAttribute("src", url);
	document.getElementsByTagName('head')[0].appendChild(script);
}

/*
* Ajaxrequest Klasse
* Abstracte Klasse von der alle anderen Ajax-Requests abgeleitet sind
*/
function Ajax()
{
	this.asyncron = true;
	this.xmlHttpReq = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try
	{
		this.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		logDebug("Using Msxml2.XMLHTT");
	}
	catch (e)
	{
		try
		{
			this.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			logDebug("Using Microsoft.XMLHTTP");
		}
		catch (e2)
		{
			this.xmlHttpReq = false;
			//logDebug("Using Msxml2.XMLHTT");
		}
	}
	@end @*/

	if (!this.xmlHttpReq && typeof XMLHttpRequest != 'undefined')
	{
		this.xmlHttpReq = new XMLHttpRequest();
		logDebug("Using native XMLHttpRequest");
	}


	/*
	* Ajax-Get-Request wird durchgeführt
	*/
	this.startGetRequest =  function(querystring)
	{
		if (this.xmlHttpReq)
		{
			this.showLoader();
			this.xmlHttpReq.open("GET", this.url + "&" + querystring , true);
			this.xmlHttpReq.onreadystatechange = this.update;
			this.xmlHttpReq.send(null);
		}
		else
		{
			/*
			* Browser unterstützt keine AJAX-Requests,
			* Pop-Up  wird stadt dessen geöffnet bzw. neue Seite angezeigt
			*/
			document.open(this.url +  "&" + querystring + "&lang=" + document.dict.lang.value + "&lp=" + document.dict.lp.value + "&ajax=false", "PopUpInfo", "width=500,height=400,left=0,top=0, menubar=yes, resizable=yes, scrollbars=yes, location=yes, toolbar=yes, status=yes");
		}
	}
	
	this.showLoader = function() {
		if (this.resultObject && !is_ie)
		{
			this.resultObject.innerHTML = "<table class='loading'><tr><td><img src='/trainer/img/ajax_loader_32x32.gif' alt='loading ...'/></td></tr></table>";
		}
	}

	/*
	* Ajax-Post-Request wird durchgeführt
	*/
	this.startPostRequest =  function(querystring)
	{
		if (this.xmlHttpReq)
		{
			this.showLoader();
			this.xmlHttpReq.open("POST", this.url, this.asyncron);
			this.xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			if (this.asyncron)
			{
				this.xmlHttpReq.onreadystatechange = this.update;
				// Der querystring wird encodeURI() erwartet und ist in UTF8
				this.xmlHttpReq.send(querystring);
			}
			else
			{
				this.xmlHttpReq.send(querystring);
				this.update();
			}
		}
		else
		{
			/*
			* Browser unterstützt keine AJAX-Requests,
			* Pop-Up  wird stadt dessen geöffnet bzw. neue Seite angezeigt
			*/
			document.open(this.url +  "&" + querystring + "&lang=" + document.dict.lang.value + "&lp=" + document.dict.lp.value + "&ajax=false", "PopUpInfo", "width=500,height=400,left=0,top=0, menubar=yes, resizable=yes, scrollbars=yes, location=yes, toolbar=yes, status=yes");
		}
	}

	this.update = function(){};
}

/*
* Vocabeln werden geladen
*/
function AjaxGetSelectedVocables()
{
	this.url = "?ajax=info";
	this.xslt = new Xslt();
	this.xslt.init("/trainer/Xsl/AJAX/displayVocables.php");

	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function()
	{
		ajaxGetSelectedVocables.resultObject = document.getElementById('contentDisplayVocvables');
		if(ajaxGetSelectedVocables.xmlHttpReq.readyState == 4)
		{
			//alert(ajaxGetSelectedVocables.xmlHttpReq.responseText);
			var xmlDoc = ajaxGetSelectedVocables.xmlHttpReq.responseXML;
			// wird das auch von Irgendwo aufgerufen wo man beide Seiten sehen will? ja statistik
			ajaxGetSelectedVocables.xslt.setParameter("mode", "preview");
			ajaxGetSelectedVocables.xslt.setParameter("side", "2");
			if (document.getElementsByName("value[editcycleforlearning][0][cycle][0][direction][0]").length > 0)
			{
				if (!(document.getElementsByName("value[editcycleforlearning][0][cycle][0][direction][0]")[0].checked))
				{
					ajaxGetSelectedVocables.xslt.setParameter("side", "1");
				}
			}
			if (document.getElementsByName("value[editcycleforquery][0][cycle][0][direction][0]").length > 0)
			{
				if (!(document.getElementsByName("value[editcycleforquery][0][cycle][0][direction][0]")[0].checked))
				{
					ajaxGetSelectedVocables.xslt.setParameter("side", "1");
				}
			}
			result = ajaxGetSelectedVocables.xslt.transformToDocument(xmlDoc.documentElement);
			ajaxGetSelectedVocables.xslt.setParameter("side", "2");
			ajaxGetSelectedVocables.xslt.setParameter("mode", "");
			
			ajaxGetSelectedVocables.resultObject.innerHTML = "";
			if (xmlDoc.documentElement.firstChild.childNodes.length == 0) {
				//document.getElementById("contentContainerHint").style.display = "block";
				
			}
			else {
				//document.getElementById("contentContainerHint").style.display = "none";
				appendXSLTResult(ajaxGetSelectedVocables.resultObject, result);
			}
			//ajaxGetSelectedVocables.resultObject.appendXSLTResult(result);
			//.appendXSLTResult();
		}
	}

	/*
	* Ajaxrequest wird gestartet
	*/
	this.request = function(event, formName)
	{
		this.startPostRequest("ajax=info&"+postBackString(event, formName));
	}

	/*
	* Ajaxrequest wird gestartet
	*/
	this.loadLearningLection = function(id)
	{
		var str = "ajax=info&postBack=managecontent&value[savecontent][0][idLearningLection]="+id;
		this.startPostRequest(str);
	}
}
AjaxGetSelectedVocables.prototype = new Ajax();

/*
* Schreibt die Abfrageergebnisse zum Server zurück
*/
function AjaxSendTrainerResults()
{
	this.resultObject = null;

	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function()
	{
		if(ajaxSendTrainerResults.xmlHttpReq.readyState == 4)
		{
			// Es erfolgt kein visuelles Feedback
		}
	}

	/*
	* Ajaxrequest wird gestartet
	*/
	this.request = function(post)
	{
		this.startPostRequest(post);
	}
}
AjaxSendTrainerResults.prototype = new Ajax();
var ajaxSendTrainerResults = new AjaxSendTrainerResults();

/*
* I-Link wird angezeigt
*/
function AjaxGetMoreInfo() {
	

	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function()
	{
		if(ajaxGetMoreInfo.xmlHttpReq.readyState == 4) {
			ajaxGetMoreInfo.resultObject.innerHTML = ajaxGetMoreInfo.xmlHttpReq.responseText;
			
			this.xPath = new XPath();
			this.xPath.evaluate("//a[@id='pronlink']", ajaxGetMoreInfo.xmlHttpReq.responseXML);
			if ((obj = this.xPath.iterateNext())) {
				document.getElementById("pronlink").parentNode.id = "player";
				var s3 = new SWFObject('/trainer/img/mp3player.swf', 'line', '130', '20', '7');
				s3.addVariable('file', obj.getAttribute("href"));
				s3.addVariable('repeat','false');
				s3.addVariable('showdigits','false');
				s3.addVariable('showdownload','false');
				s3.write('player');
				
			}
			this.xPath.evaluate("//div[@id='linuatecplayer']", ajaxGetMoreInfo.xmlHttpReq.responseXML);
			if ((obj = this.xPath.iterateNext())) {
				this.player = new LinguatecPlayer("linuatecplayer", obj.getAttribute("lang"));
				this.player.getTextFromNode(obj);
				this.player.speed = 75;
				this.player.write();
			}
		}
	}

	/*
	* Ajaxrequest wird gestartet
	*/
	this.request = function(event, offset) {
		this.url = server + "/" + lp + "/" + "j?ajax";
		var idWord = null;
		if (offset.search(/_b/) != -1) {
			this.activateForumInfo(event);
		}
		else
		{
			if (event.target && event.target.previousSibling)
			{
				idWord = event.target.previousSibling.value;
			}
			this.resultObject = document.getElementById('divMoreInfo');
			this.resultObject.style.display = "block";
			this.resultObject.style.visibility = "visible";
			
			position(event, this.resultObject);
		}
		this.startGetRequest("lp="+document.dict.lp.value+"&lang="+document.dict.lang.value+"&offset="+offset+"&idWord="+idWord);
	}
	
	/**
	* Das divForumInfo wird aktiviert und als resultObject gesetzt 
	*/
	this.activateForumInfo = function(event) {
		this.resultObject = document.getElementById('divForumInfo');
		positionRight(event, this.resultObject);
		this.resultObject.style.left = "150px";
		try {
			this.resultObject.style.top = (parseInt(this.resultObject.style.top.replace(/\s*px/,"")) - 100) +"px";
		}
		catch(e) {
		}
		
		this.resultObject.style.visibility = 'visible';
		this.resultObject.style.display = 'block';
		this.resultObject = document.getElementById('divForumInfo');
	}
	
	/*
	* Zeigt die Chinesischen Animierten Zeichereihenfolge an
	*/
	this.showAnimatedStroke = function(event, filename) {
		document.getElementById('divForumInfo').className = "popup";
		this.activateForumInfo(event);
		this.resultObject.innerHTML = "<div>"
				+ "<h1 onmousedown=\"makeDraggable(document.getElementById('divForumInfo'));\" class=\"drag\">" 
				+ "&#160;<img src=\"/trainer/img/fileclose.png\" alt=\"Close\" onclick=\"document.getElementById('divForumInfo').style.display='none';\"/>"
				+ "</h1>"
				+ "<div style='padding:3px;'>"
				+ "Radikale sind blau dargestellt, zusätzliche Striche rot. Wird mehr "
				+ "als eine Pinyin-Silbe angezeigt, so besitzt das Zeichen die durch "
				+ "die Silben angezeigten Aussprachealternativen."
				+ "</div>"
				+ "<div style='padding:3px;'>"
				+ "用蓝色书写的，表示该汉字的部首。用红色书写的，表示该汉字的剩余笔画。"
				+ "如果该汉字为多音字，将会显示该字所有读音的拼音音节。"
				+ "</div>"
				+ "<iframe src='"+filename+"' style='border: 0px solid black; width: 778px; height:345px;'></iframe>"
				+ "Die Darstellungen basiert auf der <i>eStroke Online</i>-Software "
				+ " <a href='http://www.eon.com.hk/'>EON Media Limited</a>."
				+ "<br/>"
				+ "汉字笔顺规范演示是在"
				+ "<a href='http://www.eon.com.hk/'>EON Media Limited</a>"
				+ "公司研发的软件<i>eStroke Online</i>-Software基础上制作的。"
				+ "<br/>"
				+ "<br/>"
				+ "</div>";
	}
	
	/*
	* Zeigt die Chinesischen Animierten Zeichereihenfolge an
	*/
	this.showExtendedStroke = function(event, filename) {
		document.getElementById('divForumInfo').className = "popup";
		this.activateForumInfo(event);
		this.resultObject.innerHTML = "<div>"
				+ "<h1 onmousedown=\"makeDraggable(document.getElementById('divForumInfo'));\" class=\"drag\">" 
				+ "&#160;<img src=\"/trainer/img/fileclose.png\" alt=\"Close\" onclick=\"document.getElementById('divForumInfo').style.display='none';\"/>"
				+ "</h1>"
				+ "<div style='padding:3px;'>"
				+ "Radikale sind blau dargestellt, zusätzliche Striche rot. Wird mehr "
				+ "als eine Pinyin-Silbe angezeigt, so besitzt das Zeichen die durch "
				+ "die Silben angezeigten Aussprachealternativen."
				+ "</div>"
				+ "<div style='padding:3px;'>"
				+ "用蓝色书写的，表示该汉字的部首。用红色书写的，表示该汉字的剩余笔画。"
				+ "如果该汉字为多音字，将会显示该字所有读音的拼音音节。"
				+ "</div>"
				+ "<iframe src='"+filename+"' style='border: 0px solid black; width: 778px; height:345px;'></iframe>"
				+ "Die Darstellungen basiert auf der <i>eStroke Online</i>-Software "
				+ " <a href='http://www.eon.com.hk/'>EON Media Limited</a>."
				+ "<br/>"
				+ "汉字笔顺规范演示是在"
				+ "<a href='http://www.eon.com.hk/'>EON Media Limited</a>"
				+ "公司研发的软件<i>eStroke Online</i>-Software基础上制作的。"
				+ "<br/>"
				+ "<br/>"
				+ "</div>";
	}
}
AjaxGetMoreInfo.prototype = new Ajax();
var ajaxGetMoreInfo = new AjaxGetMoreInfo();


/*
* Form soll ausgetauscht werden
*/


function AjaxGetForm()
{
	this.resultObject = null;
	this.url = "?ajax=form";

	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function()
	{
		if(ajaxGetForm.xmlHttpReq.readyState == 4)
		{
			var xml = ajaxGetForm.xmlHttpReq.responseXML;

			xml = xml.documentElement;

			var targetNode = null;
			for(i=0;i<xml.childNodes.length;i++)
			{
				if(xml.childNodes[i].nodeName=="url")
				{
					ajaxGetForm.url = xml.childNodes[i].firstChild.nodeValue+"?ajax=form";
				}
				if(xml.childNodes[i].nodeName=="remove")
				{
					node = document.getElementById(xml.childNodes[i].firstChild.nodeValue);
					targetNode = node.parentNode;
					if(node && node.parentNode && node.parentNode.removeChild)
					{
						node.parentNode.removeChild(node);
					}
				}
				if(xml.childNodes[i].nodeName=="append")
				{
					//debugger;
					if (targetNode)
					{
						node = targetNode;
					}
					else
					{
						node = document.getElementById(xml.childNodes[i].firstChild.firstChild.nodeValue);
					}
					//alert(xml.childNodes[i].firstChild.nextSibling.firstChild.nodeValue);
					node.innerHTML += xml.childNodes[i].firstChild.nextSibling.firstChild.nodeValue;
				}
				if(xml.childNodes[i].nodeName=="eval")
				{
					eval(xml.childNodes[i].firstChild.firstChild.nodeValue);
				}
				if (xml.childNodes[i].nodeName=="error")
				{
					alert(xml.childNodes[i].firstChild.nodeValue);
				}
			}
		}
	}

	/*
	* Ajaxrequest wird gestartet
	*/
	this.request = function(event, formName)
	{
		this.startPostRequest(postBackString(event, formName));
	}
}
AjaxGetForm.prototype = new Ajax();
var ajaxGetForm = new AjaxGetForm();


/*
* Form soll ausgetauscht werden
*/
function AjaxGetPopUp()
{
	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function()
	{
		if(ajaxGetPopUp.xmlHttpReq.readyState == 4)
		{
			var xml = ajaxGetPopUp.xmlHttpReq.responseXML;
			xml = xml.documentElement;

			for(var i=0;i<xml.childNodes.length;i++)
			{
				if(xml.childNodes[i].nodeName=="remove")
				{
					var node = document.getElementById(xml.childNodes[i].firstChild.nodeValue);
					if (node)
					{
						targetNode = node.parentNode;
						if(node && node.parentNode && node.parentNode.removeChild)
						{
							node.parentNode.removeChild(node);
						}
						document.getElementById('popup').style.display = "none";
					}
				}
				if(xml.childNodes[i].nodeName=="url")
				{
					ajaxGetPopUp.url = xml.childNodes[i].firstChild.nodeValue+"?ajax=form";
				}
				if(xml.childNodes[i].nodeName=="append")
				{
					var node = document.getElementById(xml.childNodes[i].firstChild.firstChild.nodeValue);
					/*while (node.firstChild) {
						node.removeChild(node.firstChild);
					}*/
					node.innerHTML = "";
					// Der neue Childnode wird geladen
					var childNode = importNode(loadXMLString(xml.childNodes[i].firstChild.nextSibling.firstChild.nodeValue).documentElement, document, true);
					//node.appendChild(childNode);
					node.innerHTML = xml.childNodes[i].firstChild.nextSibling.firstChild.nodeValue;
					document.getElementById('popup').style.display = "block";
				}
				if(xml.childNodes[i].nodeName=="replace")
				{
					node = document.getElementById(xml.childNodes[i].firstChild.firstChild.nodeValue);
					var newNode = document.createElement("div");
					newNode.innerHTML = xml.childNodes[i].firstChild.nextSibling.firstChild.nodeValue;
					node.parentNode.replaceChild(newNode, node);
				}
				if(xml.childNodes[i].nodeName=="eval")
				{
					eval(xml.childNodes[i].firstChild.firstChild.nodeValue);
				}
				if (xml.childNodes[i].nodeName=="error")
				{
					alert(xml.childNodes[i].firstChild.nodeValue);
				}
			}
		}
	}
}
AjaxGetPopUp.prototype = new AjaxGetForm();
var ajaxGetPopUp = new AjaxGetPopUp();

/**
* Überprüft auf gültiges Login/Nick
*/
function AjaxRegister() {
	this.url = "?ajax=info";
	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function() {
		if(ajaxRegister.xmlHttpReq.readyState == 4) {
			var xml = ajaxRegister.xmlHttpReq.responseXML;
			xml = xml.documentElement;

			for(var i=0;i<xml.childNodes.length;i++) {
				if(xml.childNodes[i].nodeName=="loginack") {
					//document.getElementById("loginHelperContent").innerHTML = "This is a valid Login";
					ajaxRegister.login.style.borderColor = "green";
					document.getElementById("loginHelper").style.display = "none";
				}
				if(xml.childNodes[i].nodeName=="loginnoack") {
					ajaxRegister.login.style.borderColor = "red";
					document.getElementById("loginHelperContent").innerHTML = ajaxRegister.xmlHttpReq.responseText;
					document.getElementById("loginHelper").style.display = "block";
				}
				if(xml.childNodes[i].nodeName=="nickack") {
					ajaxRegister.nick.style.borderColor = "green";
					document.getElementById("nickHelper").style.display = "none";
				}
				if(xml.childNodes[i].nodeName=="nicknoack") {
					ajaxRegister.nick.style.borderColor = "red";
					document.getElementById("nickHelperContent").innerHTML = ajaxRegister.xmlHttpReq.responseText;
					document.getElementById("nickHelper").style.display = "block";
				}
			}
		}
	}
}
AjaxRegister.prototype = new Ajax();
var ajaxRegister;

AjaxRegister.prototype.checkLogin = function(node) {
	this.login = node;
	this.startPostRequest("postBack="+node.form.name+"&value[action]=login&value[object]=login&value[value]="+encodeURIComponent(node.value));
}

AjaxRegister.prototype.setLogin = function(node) {
	this.login.value = node.textContent;
	this.login.style.borderColor = "green";
	document.getElementById("loginHelper").style.display = "none";
}

AjaxRegister.prototype.checkNick = function(node) {
	this.nick = node;
	this.startPostRequest("postBack="+node.form.name+"&value[action]=login&value[object]=nick&value[value]="+encodeURIComponent(node.value));
}

AjaxRegister.prototype.setNick = function(node) {
	this.nick.value = node.textContent;
	this.nick.style.borderColor = "green";
	document.getElementById("nickHelper").style.display = "none";
}


/**
* Anklicken und übersetzen.
*/
function Translate() {
	this.url = server + "/api/leo-1.0.php";
	this.xPath = new XPath();
	this.asyncron = false;
	this.xslt = new Xslt();
	this.xslt.init("/api/Xsl/AJAX/query.php");
	
	switch(lp) {
		case "frde":
			this.xslt.setParameter("from", "fr");
		break;
		case "esde":
			this.xslt.setParameter("from", "es");
		break;
		case "itde":
			this.xslt.setParameter("from", "it");
		break;
		case "chde":
			this.xslt.setParameter("from", "ch");
		break;
		default:
			this.xslt.setParameter("from", "en");
		break;
	}	
	
	this.resultObject = document.getElementById('queryResult');
}
Translate.prototype = new Ajax();

/**
* Ergebniss des Ajax-Requests wird behandelt
* Statische Funktion
*/
Translate.prototype.update = function() {
	if(translate.xmlHttpReq.readyState == 4)
	{
		translate.render(translate.xmlHttpReq.responseXML);
		/*if (translate.resultObject.innerHTML == "<notloggedin>Not logged in.</notloggedin>") {
			var relogin = new AjaxGetForm();
			relogin.url = "/forum/relogin.php?ajax=form";
			relogin.startPostRequest();
		}
		else {*/
		/*var cont = translate.xmlHttpReq.responseText;
		cont = cont.slice(cont.search(/<td id="contentholder">/) + 23);
		cont = cont.slice(0, cont.search(/<div id="multiword">/));
		translate.resultObject.innerHTML = cont;
		cont = null;
		
		// verlinkung wird in AJAX Links gewandelt
		if (document.getElementById("results")) {
			var nodes = document.getElementById("results").getElementsByTagName("a");
			for (i = 0; i < nodes.length; i++){
				var term = nodes[i].href.match(/search=(\w+)(&|$)/);
				if (term && term.length >= 1) {
					nodes[i].setAttribute("href", "javascript: translate.queryDict(\"" + term[1] +"\");");
				}
			}
		}
		if (document.getElementById("subnavigation")) {
			document.getElementById("subnavigation").parentNode.removeChild(document.getElementById("subnavigation"));
		}
			//translate.insertLinks();
		//}*/
	}
}

Translate.prototype.render = function(xmlDoc) {
	var result = this.xslt.transformToDocument(xmlDoc);
	translate.resultObject.innerHTML = "";
	appendXSLTResult(translate.resultObject, result);
}

Translate.prototype.insertLinks = function() {
	var nodes = document.getElementById("results").getElementsByTagName("tr");
	for (i = 0; i < nodes.length; i++){
		if (nodes[i].vAlign == 'top') {
			if (eval("document.inserttext.direction[1].checked")) {
				var langA = nodes[i].getElementsByTagName("td")[1].textContent;
				nodes[i].getElementsByTagName("td")[0].innerHTML = "<img src='/trainer/img/pfeil_l.gif' onclick='translate.replace(\""+langA+"\");'/>" + nodes[i].getElementsByTagName("td")[0].innerHTML;
			}
			else {
				var langB = nodes[i].getElementsByTagName("td")[3].textContent;
				nodes[i].getElementsByTagName("td")[4].innerHTML += "<img src='/trainer/img/pfeil_r.gif' onclick='translate.replace(\""+langB+"\");'/>";
			}
		}
	}
}

Translate.prototype.replace = function(insText) {
	var insertNode = this.field.createElement("span");
	insertNode.lang = "de";
	insertNode.appendChild(this.field.createTextNode(insText));
	// get current selection
	var sel = this.win.getSelection();
	
	// get the first range of the selection
	// (there's almost always only one range)
	var range = sel.getRangeAt(0);
	
	// deselect everything
	sel.removeAllRanges();
	
	// remove content of current selection from document
	range.deleteContents();
	
	// get location of current selection
	var container = range.startContainer;
	var pos = range.startOffset;
	
	// make a new range for the new selection
	range=document.createRange();
	
	if (container.nodeType==3 && insertNode.nodeType==3) {
	
	// if we insert text in a textnode, do optimized insertion
	container.insertData(pos, insertNode.nodeValue);
	
	// put cursor after inserted text
	range.setEnd(container, pos+insertNode.length);
	range.setStart(container, pos+insertNode.length);
	
	} else {
	
	
	var afterNode;
	if (container.nodeType==3) {
	
		// when inserting into a textnode
		// we create 2 new textnodes
		// and put the insertNode in between
	
		var textNode = container;
		container = textNode.parentNode;
		var text = textNode.nodeValue;
	
		// text before the split
		var textBefore = text.substr(0,pos);
		// text after the split
		var textAfter = text.substr(pos);
	
		var beforeNode = document.createTextNode(textBefore);
		afterNode = document.createTextNode(textAfter);
	
		// insert the 3 new nodes before the old one
		container.insertBefore(afterNode, textNode);
		container.insertBefore(insertNode, afterNode);
		container.insertBefore(beforeNode, insertNode);
	
		// remove the old node
		container.removeChild(textNode);
	
	} else {
	
		// else simply insert the node
		afterNode = container.childNodes[pos];
		container.insertBefore(insertNode, afterNode);
	}
	
	range.setEnd(afterNode, 0);
	range.setStart(afterNode, 0);
	}
	
	sel.addRange(range);

};


/**
* Anfrage ans Wörterbuch wird gestellt
*/
Translate.prototype.queryDict = function(word, where) {
	if (document.dict.search.value != word) {
		if (!where) {
			where = -1;
			this.field.body.lang = "en";
			where = document.inserttext.searchLoc.value;
			if (where == 1) {
				this.field.body.lang = "de";
			}
		}
		this.resultObject = document.getElementById('queryResult');
		

		var str = "search=" + encodeURIComponent(word) + "&where=" + where + "&lp="+lp+"&lang="+lang;
		this.startPostRequest(str);
		document.dict.search.value = word;
	}
}

/**
* Anfrage ans Wörterbuch wird gestellt
*/
Translate.prototype.more = function(min, cat) {
	var where;
	if (!where) {
		where = -1;
		this.field.body.lang = "en";
		where = document.inserttext.searchLoc.value;
		if (where == 1) {
			this.field.body.lang = "de";
		}
	}
		
	var str = "search=" + encodeURIComponent(document.dict.search.value) + "&where=" + where + "&min="+min+"&fixedSect=" + cat+ "&lp="+lp+"&lang="+lang;
	this.startPostRequest(str);
}

/**
* Anfrage ans Wörterbuch wird gestellt
*/
Translate.prototype.less = function(max, cat) {
	var where;
	if (!where) {
		where = -1;
		this.field.body.lang = "en";
		where = document.inserttext.searchLoc.value;
		if (where == 1) {
			this.field.body.lang = "de";
		}
	}
	var str = "search=" + encodeURIComponent(document.dict.search.value) + "&where=" + where + "&max="+max+"&fixedSect=" + cat+ "&lp="+lp+"&lang="+lang;
	this.startPostRequest(str);
}

/**
* Ergebniss wird angezeigt
*/
Translate.prototype.displaySearchResults = function(xml) {
	if (xml && xml.documentElement) {
		this.resultXml = xml;
		
		this.xslt.setParameter("mode", "bigresult");
		var result = this.xslt.transformToDocument(xml.documentElement);
		this.xslt.setParameter("mode", "");

		document.getElementById('queryResult').innerHTML = "";
		appendXSLTResult(document.getElementById('queryResult'), result.documentElement);
	}
	else {
		document.getElementById('queryResult').innerHTML = "";
		alert("Fehler bei der Anfrage");
	}
}

/**
* Multiwordsuche wird (de)aktiviert
*/
Translate.prototype.display = function(node) {
	if (document.getElementById("subnavigation").style.display.toLowerCase() == "table" || document.getElementById("subnavigation").style.display.toLowerCase() == "") {
		node.value="Wort";
		document.getElementById("subnavigation").style.display = "none";
		document.getElementById("singleword").style.display = "none";
		if (document.getElementById("results")) {
			document.getElementById("results").parentNode.removeChild(document.getElementById("results"));
		}
		document.getElementById("multiword").style.display = "block";
		//addEvent(document.dict, "submit", "translate.queryDict(document.dict.search.value)");
		document.getElementById("iframe").src="/forum/translator.php?" + Math.random();
		this.field = document.getElementById("iframe").contentDocument;
		this.win = document.getElementById("iframe").contentWindow;
	}
	else {
		node.value="Text";
		document.getElementById("singleword").style.display = "block";
		document.getElementById("subnavigation").style.display = "table";
		document.getElementById("multiword").style.display = "none";
		document.dict.onsubmit = "";
	}
}

Translate.prototype.showLoader = function() {
	if (this.resultObject && !is_ie)
	{
		this.resultObject.innerHTML = "<div style='width: 100%;height: 300px;'><table class='loading' style='width: 100%;height: 300px;'><tr><td>&#160;<img src='/trainer/img/ajax_loader_32x32.gif' alt='loading ...'/>&#160;</td></tr></table></div>";
	}
}
var translate;
function initTranslate() {
	if (!translate) {
		translate = new Translate();
	}
	// TODO node.value="Wort";
	/*	document.getElementById("subnavigation").style.display = "none";
		document.getElementById("singleword").style.display = "none";
		document.getElementById("multiword").style.display = "block";
		document.dict.action = "translate.queryDict(document.dict.search.value);";*/
}


/**
* Ein dummer Browser kann keine internen Objecte Prototypen ...
*/
function appendXSLTResult(obj, result)
{
	if (typeof result == 'object') {
		try
		{
			if (is_opera) {
				var serializer = new XMLSerializer();
				var html = serializer.serializeToString(result);
				obj.innerHTML += html;
			}
			else {
				// node wird importiert falls nötig
				if (result.ownerDocument == obj.ownerDocument)
				{
					node = result.documentElement;
				}
				else
				{
					node = importNode(result.documentElement, obj.ownerDocument, true);
				}
				obj.appendChild(node);
			}
		}
		catch(e)
		{
			// Hack für den IE ...
			if (result.xml)
			{
				obj.innerHTML += result.xml;
			}
			else if(result.innerHTML)
			{
				obj.innerHTML += result.innerHTML;
			}
		}
	}
	else if (typeof result == 'string')
	{
		obj.innerHTML += result;
	}
	else
	{
		alert("Unknown result type:" + typeof result);
	}
}
/**
* Importiert einen Node (und seine childNodes) in das übergebene Document
*/
function importNode(node, xmlDoc, childNodes)
{
	try
	{
		return xmlDoc.importNode(node, childNodes);
	}
	catch(e)
	{
		return node;
	}
}

/**
* 
*/
function loadXMLString(str) 
{
	try
	{
		 //Firefox, Mozilla, Opera, etc.
		var parser=new DOMParser();
		xmlDoc=parser.parseFromString(htmlEntityDecode(str.trim()),"text/xml");
		return(xmlDoc);
	}
	catch(e) 
	{
		try 
		{
			//Internet Explorer
			var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(htmlEntityDecode(str.trim()));
			return(xmlDoc); 
		}
		catch(e)
		{
		}
	}
	
	return(null);
}

function htmlEntityDecode(str) 
{
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}
/*function appendXSLTResult(result)
{
	if (typeof result == 'object')
	{
		try
		{
			this.appendChild(result.documentElement);
		}
		catch(e)
		{
			// Hack für den IE ...
			this.innerHTML = result.xml;
		}
	}
	else if (typeof result == 'string')
	{
		this.innerHTML = result;
	}
	else
	{
		alert("Unknown result type");
	}
}

if (Node && Node.prototype)
{
	Node.prototype.appendXSLTResult = appendXSLTResult;
}
else if (Objecte && Objecte.prototype)
{
	Objecte.prototype.appendXSLTResult = appendXSLTResult;
}
else
{
	// Dummer IE
}*/

/*
* Option dient zur Einstellung der Seitengröße, Sortierung, 
*/
function Option() {
	this.panels = new Array();
}

var actOptions;

/**
 * Pannel ein-/ausblenden
 * die anderen Panels werden ausgeblendet
 */
Option.prototype.toggle = function(node, name) {
	if (actOptions && actOptions != this) {
		actOptions.hideOthers(null);
	}
	
	// Animation wird neu erstellt
	if (!this.panels[name]) {
		var xPath = new XPath();
		xPath.evaluate("ancestor::div[@class='options']/div[@class='panel']", document, node);
		var panel = xPath.iterateNext();
		
		xPath.evaluate("ancestor::div[@class='options']", document, node);
		node = xPath.iterateNext();
		
		panel.style.left = (node.offsetLeft) + "px";
		panel.style.top = (node.offsetTop + 24) + "px";
		
		var anim = new Animator().addSubject(new CSSStyleSubject(
			panel,
			"height: 0px; display: none;",
			"height: 220px; display: block;"));
		this.panels[name] = new Panel(node, anim);
	}
	// andere Panels ausblenden
	this.hideOthers(this.panels[name]);
	
	// Panel ein/ausblenden
	if (!this.panels[name].display) {
		this.panels[name].show();
	}
	else {
		this.panels[name].hide();
	}
	actOptions = this;
}

/**
 * Goto-Pannel ein-/ausblenden
 * die anderen Panels werden NICHT ausgeblendet
 */
Option.prototype.toggleGotoPage = function(node) {
	var xPath = new XPath();
	xPath.evaluate("ancestor::div[@class='paging']/div[@class='panel']", document, node);
	var panel = xPath.iterateNext();
	
	if (!is_ie){
		panel.style.left = (node.offsetLeft - 102) + "px";
	}
	else {
		panel.style.right = "0px";
	}
	panel.style.top = (node.offsetTop + 20) + "px";
	
	var anim = new Animator().addSubject(new CSSStyleSubject(
		panel,
		"height: 0px; display: none;",
		"height: 80px; display: block;"));
	
	if (panel.style.display != "block") {
		anim.play();
		node.parentNode.style.backgroundColor = "#6181FF";
	}
	else {
		anim.reverse();
		node.parentNode.style.backgroundColor = "transparent";
	}
}

Option.prototype.hideOthers = function(panel) {
	for (var name in this.panels) {
		if (panel != this.panels[name] && this.panels[name].display) {
			this.panels[name].hide();
		}
	}
}


function Panel(node, anim) {
	this.node = node;
	this.anim = anim;
	this.display = false;
	this.trees = new Array();
}

Panel.prototype.show = function(node) {
	this.display = true;
	this.anim.play();
	this.node.style.backgroundColor = "#6181FF";
}
	
Panel.prototype.hide = function(node) {
	this.display = false;
	this.anim.reverse();
	this.node.style.backgroundColor = "transparent";
}

Option.prototype.setOptions = function(node) {
	var xPath = new XPath();
	xPath.evaluate("../div[@class='content']/select", document, node);
	while (obj = xPath.iterateNext()) {
		if (obj.id.search(/orderbylisting/) != -1) {
			this.orderBy = obj.value;
		}
		if (obj.id.search(/limitlisting/) != -1) {
			this.limit = obj.value;
		}
	}
}

Option.prototype.setSortField = function(field) {
	if (this.orderBy == field + " desc") {
		this.orderBy = field + " asc";
	}
	else {
		this.orderBy = field + " desc";
	}
}

Option.prototype.setFilters = function(node) {
	this.filters = new Array();
	var xPath = new XPath();
	xPath.evaluate("../div[@class='content']//input[@type='checkbox']", document, node);
	while (obj = xPath.iterateNext()) {
		if (obj.checked) {
			var typ = obj.name.split("][");
			typ = typ[typ.length - 2];
			if (!this.filters[typ]) {
				this.filters[typ] = new Array();
			}
			this.filters[typ].push(obj.value);
		}
	}
}
Option.prototype.resetFilters = function(node) {
	this.filters = new Array();
	var xPath = new XPath();
	xPath.evaluate("../div[@class='content']//input[@type='checkbox']", document, node);
	while (obj = xPath.iterateNext()) {
		obj.checked = false;
	}
}

Panel.prototype.openTree = function(i, node) {
	if (this.trees[i]) {
		this.trees[i].toggle();
	}
	else {
		// Animation muss neu erstellt werden
		var xPath = new XPath();
		xPath.evaluate("../ul", document, node);
		var tree = xPath.iterateNext();
		
		// Höhe wird bestimmt
		var height = 5;
		var child = tree.firstChild;
		while (child) {
			if (child.nodeName.toLowerCase() == "li") {
				height+= child.offsetHeight;
			}
			child = child.nextSibling;
		}
		
		// Animationen werden erzeugt
		var anim = new Animator();
		anim.addSubject(new CSSStyleSubject(
			tree,
			"height: 0px;",
			"height: " + height +"px"));
			
		xPath.evaluate("./img[@class='closed']", document, node);
		var img = xPath.iterateNext();
		anim.addSubject(new DiscreteStyleSubject(
			img,
			"display", "inline-block", "none", 0.5));
		
		xPath.evaluate("./img[@class='open']", document, node);
		img = xPath.iterateNext();
		anim.addSubject(new DiscreteStyleSubject(
			img,
			"display", "none", "inline-block", 0.5));
			
		this.trees[i] = anim;
		this.trees[i].play();
	}
}
		
Option.prototype.toString = function(node) {
	var str = "";
	if (this.page && (!isNaN(this.page))) 	{
		str += "&page="+this.page;
	}
	if (this.limit && (!isNaN(this.limit))) {
		str += "&limit="+this.limit;
	}
	if (this.orderBy) {
		str += "&orderBy="+this.orderBy;
	}
	for (var typ in this.filters) {
		if (typeof this.filters[typ] == "object") {
			for (var i = 0; i < this.filters[typ].length; i++) {
				str += "&value["+this.obj+"][0]["+typ+"listing][0]["+typ+"]["+this.filters[typ][i]+"]="+this.filters[typ][i];
			}
		}
	}
	// Suchstring hinzufügen
	if (document.getElementById("value["+this.obj+"][0][search][0]") && document.getElementById("value["+this.obj+"][0][search][0]").value != "") {
		str += "&value["+this.obj+"][0][search][0]=" + document.getElementById("value["+this.obj+"][0][search][0]").value;
	}
	if (document.getElementById("value["+this.obj+"][0][languagea][0]") && document.getElementById("value["+this.obj+"][0][languagea][0]").value != "") {
		str += "&value["+this.obj+"][0][search][0]=" + document.getElementById("value["+this.obj+"][0][languagea][0]").value;
		if (document.getElementById("value["+this.obj+"][0][languageb][0]") && document.getElementById("value["+this.obj+"][0][languageb][0]").value != "") {
			str += " " + document.getElementById("value["+this.obj+"][0][languageb][0]").value;
		}
		if (str.search(/ $/) == -1) {
			str += "*";
		}
		
	}
	else if (document.getElementById("value["+this.obj+"][0][languageb][0]") && document.getElementById("value["+this.obj+"][0][languageb][0]").value != "") {
		str += "&value["+this.obj+"][0][search][0]=" + document.getElementById("value["+this.obj+"][0][languageb][0]").value;
		if (str.search(/ $/) == -1) {
			str += "*";
		}
	}
	if (document.getElementById("value["+this.obj+"][0][subject][0]") && document.getElementById("value["+this.obj+"][0][subject][0]").value != "") {
		str += "&value["+this.obj+"][0][search][0]=" + document.getElementById("value["+this.obj+"][0][subject][0]").value;
	}
	
	return str;
}

function Dictionary() {
	this.option = new Option();
}
var dictionary = new Dictionary();