var dict = false;
var forum = false;
var trainer = false;
/**
* 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");
	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;
	
	if (typeof XMLHttpRequest != 'undefined') {
		this.xmlHttpReq = new XMLHttpRequest();
	}
	else {
		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");
			}
		}
	}


	/*
	* 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)
		{
			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() {};

	/*
	* 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', unescape(obj.getAttribute("href")));
				s3.addVariable('repeat','false');
				s3.addVariable('showdigits','false');
				s3.addVariable('showdownload','false');
				s3.write('player');
				
			}
			this.xPath.evaluate("//div[@id='linguatecplayer']", ajaxGetMoreInfo.xmlHttpReq.responseXML);
			if ((obj = this.xPath.iterateNext())) {
				this.player = new LinguatecPlayer("linguatecplayer", 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);
	}
	
	this.history = new Array();
	this.requestFinan = function(url) {
		this.url = server + "/" + url + "?";
		this.history.push(this.url);
		ajaxGetMoreInfo.startGetRequest("lp="+document.dict.lp.value+"&lang="+document.dict.lang.value);
	}
	
	this.backFinan = function() {
		this.history.pop();
		if (this.history.length > 0) {
			this.url = this.history[this.history.length - 1];
			ajaxGetMoreInfo.startGetRequest("lp="+document.dict.lp.value+"&lang="+document.dict.lang.value);
		}
	}
	
	/**
	* 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();


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

	/*
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function() {
		
		if(ajaxGetForumInfo.xmlHttpReq.readyState == 4) {
			
			document.getElementById("forumContent").innerHTML = "";
			document.getElementById("forumNavigation").innerHTML = "";
			this.xmlDoc = ajaxGetForumInfo.xmlHttpReq.responseXML;
			this.xPath = new XPath();
			this.xPath.evaluate("/threads/body", this.xmlDoc);
			var body;
			var n = 0;
			while (body = this.xPath.iterateNext()) {
				n++;
				var xPath = new XPath();
				xPath.evaluate(".//td[@id='middle']/form//div[@class='content']", this.xmlDoc, body);
				//xPath.evaluate("//div", this.xmlDoc, body);
				var thread;
				if (thread = xPath.iterateNext()) {
					//thread.setAttribute("id", "threadContent"  + (n - 1));
					appendXSLTObject(document.getElementById("forumContent"), thread);
				}
				var tab = "<li><span id='thread" + (n - 1) + "' onclick='activateTab(\"thread\", " + (n - 1) + ");'";
				if (n == 1) {
					tab += " class='active' ";
				}
				else {
					tab += " class='inactive' ";
				}
				tab += ">Faden " + n + "</span></li>";
				document.getElementById("forumNavigation").innerHTML += tab;
			}
			document.getElementById("forumContent").innerHTML = document.getElementById("forumContent").innerHTML;
			var thread = document.getElementById("forumContent").firstChild;
			n = 0;
			while(thread) {
				n++;
				thread.setAttribute("id", "threadContent"  + (n - 1));
				thread = thread.nextSibling;
			}
		}
	}

	/*
	* Ajaxrequest wird gestartet
	*/
	this.request = function(event, offset) {
		this.url = server + "/m-html/conf/"+lp+"/html.conf/fLinkResolve.html?offset="+offset;
		//this.url = server + "/forum/tmp.php?";
		this.activateForumInfo(event);
		this.startGetRequest("");
	}
	
	/**
	* 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('forumContent');
	}
}
AjaxGetForumInfo.prototype = new Ajax();
var ajaxGetForumInfo = new AjaxGetForumInfo();



/*
* 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);
					}
					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/text-1.1.php";
	this.xPath = new XPath();
	this.asyncron = false;
	this.xslt = new Xslt();
	this.xslt.init("/api/Xsl/AJAX/query.php");
	this.xslt.setLangParameter();
	this.option = new Option();
	this.option.height = 260;
	lang = document.dict.lang.value;
	
	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;
		case "rude":
			this.xslt.setParameter("from", "ru");
		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);
	}
}

Translate.prototype.render = function(xmlDoc) {
	var result = this.xslt.transformToDocument(xmlDoc);
	translate.resultObject.innerHTML = "";
	appendXSLTResult(translate.resultObject, result);
	document.result.lang.value = lang;
	document.result.lp.value = lp;
	
	// Verlinkung wird eingefügt
	var nodes = translate.resultObject.getElementsByTagName("td");
	var length = nodes.length;
	for (var i = 0; i < length; i++) {
		if (nodes[i].lang) {
			var node = nodes[i].firstChild;
			
			while (node) {
				if (node.nodeType == 3) {
					var newRepr = document.createElement("span");
					// Textknoten Verlinkung wird eingefügt
					var str = node.data;
					var substrs = str.split(/ /);
					for (var n = 0; n < substrs.length; n++) {
						if (!substrs[n].match(/\[.+\]/)) {
							var newNode = document.createElement("span");
							newNode.onclick = relink;
							newNode.setAttribute("class", "link");
							newNode.appendChild(document.createTextNode(substrs[n] + " "));
							newRepr.appendChild(newNode);
							
						}
						else {
							newRepr.appendChild(document.createTextNode(substrs[n] + " "));
						}
					}
					var nextNode = node.nextSibling;
					node.parentNode.replaceChild(newRepr, node);
					node = nextNode;
				}
				else {
					node = node.nextSibling;
				}
			}
		}
	}
}
function relink(e) {
	if(!e) {
		e = event;
	}
	var node;
	if (e.target) {
		node = e.target;
	}
	else {
		node = e.srcElement;
	}
	if (node) {
		var where = -1;
		if (node.parentNode.parentNode.getAttribute("lang") == "de") {
			where = 1;
		}
		translate.queryDict(node.firstChild.data, where);
	}
}

Translate.prototype.insertLinks = function() {
	var nodes = document.getElementById("results").getElementsByTagName("tr");
	for (i = 0; i < nodes.length; i++){
		if (nodes[i].vAlign == 'top') {
			if (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 formName = "inserttext";
		var fields = new Array();
		for (var x = 0; x < eval("document."+formName+".elements.length"); x++) {
			// join them into a string.
			var type = eval("document."+formName+".elements["+x+"].type");
			if (type == "checkbox") {
				if (document.forms[formName].elements[x].checked == true) {
					fields.push(encodeURIComponent(document.inserttext.elements[x].name)+'='+encodeURIComponent(document.inserttext.elements[x].value));
				}
			}
		}
		
		var str = "search=" + encodeURIComponent(word) + "&where=" + where + "&lp="+lp+"&lang="+lang+"&"+fields.join('&');
		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.setAttribute("disabled", "disabled");
		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
}*/

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


/**
* Anklicken und übersetzen.
*/
function Loader(target, url) {
	this.url = server + url;
	this.asyncron = true;
	this.target = target;
}
Loader.prototype = new Ajax();

/**
* Ergebniss des Ajax-Requests wird behandelt
* Statische Funktion
*/
Loader.prototype.update = function() {
	if(loader.xmlHttpReq.readyState == 4) {
		loader.target.innerHTML += loader.xmlHttpReq.responseText;
		/*var node = loader.xmlHttpReq.responseXML.documentElement;
		node = document.importNode(node, true);
		loader.target.appendChild(node);
		//appendXSLTResult(loader.target, loader.xmlHttpReq.responseXML);*/
	}
}
var loader;
