/*
* Globale vorinitialisierte Variablen
*/
var row = 0;
var direction = 1;
var evalStr = "";

/*
* Löscht die Werte aller Inputfelder eines Formularteils
*/
function clearSubForm(node)
{
	if ((node.nodeName.toLowerCase() == "input" && node.getAttribute("type").toLowerCase() == "text") || node.nodeName.toLowerCase() == "textarea")
	{
		node.value = "";
	}
	if (node.nodeName.toLowerCase() == "option")
	{
		node.selected = false;
	}

	// Child-Nodes werden aktualisiert
	if (node.hasChildNodes())
	{
		node = node.firstChild;
		while (node != null)
		{
			clearSubForm(node);
			node = node.nextSibling;
		}
	}
}

/*
* Löscht einen Teil eines Formular
*/
function removeSubForm(id, node)
{
	var container = document.getElementById(id);
	if (container.childNodes.length > 1)
	{
		// Ein weiteres SubFormular der selben Sorte ist vorhanden, SubFormular wird gelöscht
		container.removeChild(node);
	}
	else
	{
		// Letztes Subformular, Subformular wird nur versteckt und ein Feld zum wiedereinblenden angezeigt
		if (container.firstChild)
		{
			container.firstChild.style.display = "none";
			document.getElementById("restore"+id).style.display = "block";
		}
	}
}

/*
* Stellt Teil eines Formular wieder her
*/
function restoreSubForm(id)
{
	var container = document.getElementById(id);
	// Letztes Subformular, Subformular wird angezeigt und ein Feld zum Wiedereinblenden versteckt
	if (container.firstChild)
	{
		container.firstChild.style.display = "block";
		document.getElementById("restore"+id).style.display = "none";
	}
}

/*
* Ein Teil einer Form wird dupliziert und mit neuen Namen versehen
*/
function duplicateSubForm(id, actNode)
{
	var newObject = document.getElementById(id).cloneNode(true);
	actNode= document.getElementById(actNode);
	var formName = id.substr(0, id.length -3).substr(id.indexOf("["));
	var i = 0;
	var node = document.getElementById(id.substr(0, id.length -3)+"["+i+"]");
	while (node)
	{
		i++;
		node = document.getElementById(id.substr(0, id.length -3)+"["+i+"]")
	}
	updateName(newObject, id.substr(id.indexOf("[")), formName+"["+i+"]", i);

	document.getElementById(id).parentNode.appendChild(newObject, actNode.nextSibling);
	eval(evalStr);
	evalStr = "";
}

/*
* Alle Attribute des Nodes und aller Children werden geupdated
*/
function updateName(obj, oldName, newName, n)
{
	// Bennenung der Attribute des Objects wird aktualisiert
	if (obj.attributes)
	{
		for (i = 0; i < obj.attributes.length; i++)
		{
			if (obj.attributes[i].nodeName.toLowerCase() == "href" && obj.attributes[i].nodeValue.search(/fxEffect/) != -1)
			{
				// Es wird eine Ersetzung für einen fx Event aufruf vorgenommen
				//alert(n);
				obj.attributes[i].nodeValue = obj.attributes[i].nodeValue.replace(/\d\./gi,n+".");
				//alert(obj.attributes[i].nodeValue);
				// Neuer Effekt wird zur initialisiert (nicht sehr allgemein gehalten) vorgemerkt
				evalStr +='fxEffectCorrection'+n+' = new fx.Height(document.getElementById("table'+newName+'") , {duration: 400, onComplete: function() { toggle("atable'+newName+'");}});';
			}
			else
			{
				// Der IE hat Probleme mit .attributes
				try
				{
					if (obj.attributes[i].nodeValue && obj.attributes[i].nodeValue != "")
					{
						obj.attributes[i].nodeValue = obj.attributes[i].nodeValue.replace(oldName, newName);
					}
				}
				catch(e)
				{
					// IE Steigt aus da er alle möglichen Attribute durchläuft
				}
			}
		}
	}

	// Child-Nodes werden aktualisiert
	if (obj.hasChildNodes())
	{
		obj = obj.firstChild;
		while (obj != null)
		{
			updateName(obj, oldName, newName, n);
			obj = obj.nextSibling;
		}
	}
}

/*
* Ein - und Ausblenden von einem HTML Elment
*/
function show(obj)
{
	if (document.getElementById(obj).style.display == "none" || document.getElementById(obj).style.display == "")
	{
		document.getElementById("a"+obj).firstChild.data = "<<";
		document.getElementById(obj).style.display = "block";
	}
	else
	{
		document.getElementById("a"+obj).firstChild.data = ">>";
		document.getElementById(obj).style.display = "none";
	}
}

/*
* Ein - und Ausblendepfeile werden vertauscht
*/
function toggle(obj)
{
	if (document.getElementById(obj).firstChild.data == ">>")
	{
		document.getElementById(obj).firstChild.data = "<<";
	}
	else
	{
		document.getElementById(obj).firstChild.data = ">>";
	}
}



// Ein String wird an der Stelle des Cursors eingefügt
function insertString(str, textarea)
{
	if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionStart);
		textarea.value = begin + str + end;
		textarea.setSelectionRange(begin.length + 1, begin.length + 1);
	}
	else
	{
		if (typeof(textarea.caretPos) != "undefined")
		{
			var begin = textarea.value.substr(0, textarea.caretPos);
			var end = textarea.value.substr(textarea.caretPos);
			textarea.value = begin + str + end;
			textarea.caretPos.select();
		}
	}
	
	textarea.focus();
}


function Assistance() {
	this.assistance = document.getElementById("assistance");
	this.leftOffset = -10;
}

Assistance.prototype.init = function(event, field) {
	this.field = field;
	this.position();
}

/**
* Positioniert den Helper
*/
Assistance.prototype.position = function() {
	this.assistance.style.display="block";
	var docPos = getPosition(this.field);
	this.assistance.style.left = (docPos.x + this.leftOffset) + "px";
	if (docPos.y < this.assistance.clientHeight + 30) {
		// Wird unterhalb angezegt
		this.assistance.style.top = (docPos.y + this.field.clientHeight + 12) + "px";
		this.assistance.style.bottom = "auto";
		this.assistance.getElementsByTagName("img")[0].src = "/trainer/img/notice.gif";
		this.assistance.getElementsByTagName("img")[0].style.top = "-10px";
		this.assistance.getElementsByTagName("img")[0].style.bottom = "auto";
		this.assistance.getElementsByTagName("img")[1].style.top = "auto";
		this.assistance.getElementsByTagName("img")[1].style.left = "auto";
		this.assistance.getElementsByTagName("img")[1].style.bottom = "3px";
		this.assistance.getElementsByTagName("img")[1].style.right = "3px";
		
	}
	else {
		// Wird überhalb angezegt
		//this.assistance.style.bottom = (docPos.y + 12) + "px";
		//this.assistance.style.top = "auto";
		this.assistance.style.top = (docPos.y - this.assistance.clientHeight - 12) + "px";
		this.assistance.style.bottom = "auto";
		this.assistance.getElementsByTagName("img")[0].src = "/trainer/img/noticeTop.gif";
		this.assistance.getElementsByTagName("img")[0].style.bottom = "-10px";
		this.assistance.getElementsByTagName("img")[0].style.top = "auto";
		this.assistance.getElementsByTagName("img")[1].style.top = "3px";
		this.assistance.getElementsByTagName("img")[1].style.right = "3px";
		this.assistance.getElementsByTagName("img")[1].style.bottom = "auto";
		this.assistance.getElementsByTagName("img")[1].style.left = "auto";
	}
	
}

/**
* Eingabehelfer für alle Sprachen
*
*/
function InputAssistance()
{
	this.leftOffset = 30;
	this.assistance = document.getElementById("assistance");
	if (typeof document.evaluate != 'undefined' && !is_safari)
	{
		var xPath = new XPath();
		xPath.evaluate("//div[@id='assistance']//div[@class='result']", document);
		this.assistance.result = xPath.iterateNext();
	}
	else
	{
		// Der IE kann keine XPath expression auf dem HTML durchführen
		var nodes = getElementsByClass("result", document.getElementById("assistance"),"div");
		if (nodes && nodes.length > 0) {
			this.assistance.result = nodes[0];
		}
	}
	this.chars = /([a-z]|[A-Z]|[0-9])+$/;
}
InputAssistance.prototype = new Assistance();

InputAssistance.prototype.init = function(event, field, format, mark, multiplechoice, cloze) {
	this.field = field;
	this.subst = -1;
	
	if (typeof document.evaluate != 'undefined' && !is_safari)
	{
		var xPath = new XPath();
		xPath.evaluate("//div[@id='assistance']//span[@class='format']", document);
		if (format)
		{
			xPath.iterateNext().style.display = "inline";
		}
		else
		{
			xPath.iterateNext().style.display = "none";
		}
		xPath.evaluate("//div[@id='assistance']//span[@class='mark']", document);
		if (mark)
		{
			xPath.iterateNext().style.display = "inline";
		}
		else
		{
			xPath.iterateNext().style.display = "none";
		}
		xPath.evaluate("//div[@id='assistance']//span[@class='multiplechoice']", document);
		if (multiplechoice)
		{
			xPath.iterateNext().style.display = "inline";
		}
		else
		{
			xPath.iterateNext().style.display = "none";
		}
		xPath.evaluate("//div[@id='assistance']//span[@class='cloze']", document);
		if (cloze)
		{
			xPath.iterateNext().style.display = "inline";
		}
		else
		{
			xPath.iterateNext().style.display = "none";
		}
	}
	else
	{
		// Der IE kann keine XPath expression auf dem HTML durchführen
		var nodes = getElementsByClass("format", document.getElementById("assistance"));
		if (nodes && nodes.length > 0) {
			if (format) {
				nodes[0].style.display = "inline";
			}
			else {
				nodes[0].style.display = "none";
			}
		}
		
		nodes = getElementsByClass("mark", document.getElementById("assistance"));
		if (nodes && nodes.length > 0) {
			if (mark) {
				nodes[0].style.display = "inline";
			}
			else {
				nodes[0].style.display = "none";
			}
		}
		
		nodes = getElementsByClass("multiplechoice", document.getElementById("assistance"));
		if (nodes && nodes.length > 0) {
			if (multiplechoice) {
				nodes[0].style.display = "inline";
			}
			else {
				nodes[0].style.display = "none";
			}
		}
		nodes = getElementsByClass("cloze", document.getElementById("assistance"));
		if (nodes && nodes.length > 0) {
			if (cloze) {
				nodes[0].style.display = "inline";
			}
			else {
				nodes[0].style.display = "none";
			}
		}
	}
	
	try
	{
		this.assistance.result.innerHTML = "";
	}
	catch(e)
	{
		// lp != chde
	}
	
	// Position wird angepasst
	this.position();
}

	
/**
* Ein Buchstabe wird angefügt
*/
InputAssistance.prototype.insert = function(str) {
	this.field.focus();
	if (typeof(this.field.selectionStart) != "undefined")
	{
		var begin = this.field.value.substr(0, this.field.selectionStart);
		var end = this.field.value.substr(this.field.selectionStart);
		this.field.value = begin + str + end;
		this.field.setSelectionRange(begin.length + str.length, begin.length + str.length);
	}
	else
	{
		if (this.field.nodeName.toLowerCase() == "input") {
			this.field.value += str;
		}
		else {
			if (typeof(document.selection) != "undefined")
			{
				// IE
				var range = document.selection.createRange();
				var insText = range.text;
				range.text = str;
				/* Anpassen der Cursorposition */
				range = document.selection.createRange();
				range.move('character', 0);
				range.select();
			}
		}
	}
}
	
/**
* Chinesische Schriftzeichenauflösung
*/
InputAssistance.prototype.translate = function(event) {
	if (this.field) {
		// Es wird überprüft ob eine Spezialtaste gedrückt wurde
		if (event.ctrlKey) {
			// Strg + Zfferntaste wurde gedrückt
			try {
				var subst = parseInt(String.fromCharCode(event.keyCode)) - 1 ;
				if (!isNaN(subst)) {
					this.subst = subst
					this.appendSign();
				}
				return;
			}
			catch(e) {
				// Keine Zahl
				this.subst = -1;
				return;
			}
		}
		else {
			switch (event.keyCode) {
				case 38:
					// Pfeiltaste nach oben
					this.subst--;
					this.appendSign();
					return;
				break;
				case 40:
					// Pfeiltaste nach unten
					this.subst++;
					this.appendSign();
					return;
				break;
				case 27:
					// ESC
					this.assistance.style.display = "none";
					return;
				break;
			}
		}
		// Inhalt wird aktualisiert
		var value = this.chars.exec(this.field.value);
		try {
			value = value[0];
		}
		catch(e) {
			value = "";
		}
		if (value == "") {
			//this.assistance.result.innerHTML = "";
			return;
		}
		eval('this.codeTable = codeTable'+value.substr(0,1).toUpperCase());

		this.assistance.result.innerHTML = "Direkte Treffer:<br/>";
		this.subst = -1;
		// Auswahlliste der Zeichen wird angelegt
		signs = new Array();
		var more = new Array(); 
		// Exakte übereinstimmung wird getestet
		
		for (var i = 0; i < this.codeTable.length; i++) {
			if (value == this.codeTable[i].pinjin.substr(0, value.length)) {
				if (value == this.codeTable[i].pinjin) {
					signs.push(i);
					var str = "<span onclick=\"inputAssistance.subst = "+ (signs.length-1) +";inputAssistance.appendSign();\">";
					if (signs.length <= 9) {
						str += signs.length + ") ";
					}
					else {
						str += "&#160;&#160;&#160;&#160;";
					}
					str += this.codeTable[i].sign + "&#160;&#160;" + this.codeTable[i].pinjin + "</span>";
					this.assistance.result.innerHTML += str;
					this.assistance.result.innerHTML += "<br/>";
				}
				else if (signs.length < 9 && more.length < 9) {
					more.push(i);
				}
			}
		}
		this.assistance.result.innerHTML += "------<br/>Teiltreffer:<br/>";
		for (var n = signs.length; n < 9 && n < more.length; n++) {
			var i = more[n];
			signs.push(i);
			var str = "<span onclick=\"inputAssistance.subst = "+ (signs.length-1) +";inputAssistance.appendSign();\">";
			if (signs.length <= 9) {
				str += signs.length + ") ";
			}
			else {
				str += "&#160;&#160;&#160;&#160;";
			}
			str += this.codeTable[i].sign + "&#160;&#160;" + this.codeTable[i].pinjin + "</span>";
			this.assistance.result.innerHTML += str;
			this.assistance.result.innerHTML += "<br/>";
		}
	}
	return;
}
	
/**
* Eingabehelfer soll deaktiviert werden
*/
InputAssistance.prototype.disable = function() {
	var conf = confirm('Eingabehelfer wirklich deaktivieren?\r\nSie k\u00F6nnen den Eingabehelfer jederzeit unter Suchtips wieder aktivieren.'); 
	if (conf)
	{
		setCookie( "assistance", false, 10000, "/");
		this.assistance.style.display = "none";
		inputAssistance = new InputAssistanceDummy();
	}
	
}
	
InputAssistance.prototype.appendSign = function() {
	if (this.subst < 0)
	{
		this.subst = signs.length -1;
	}
	else if(this.subst >= signs.length)
	{
		this.subst = 0;
	}
	
	var value = this.chars.exec(this.field.value);
	if (value && value[0] != "")
	{
		value = value[0];
		this.field.value = this.field.value.substr(0, this.field.value.length - value.length) + this.codeTable[signs[this.subst]].sign;
	}
	else
	{
		try
		{
			this.field.value = this.field.value.substr(0, this.field.value.length - 1) + this.codeTable[signs[this.subst]].sign;
		}
		catch(e)
		{
			// TODO Wann, warum tritt dieser Fehler auf
			// Fehlerbehandlung
		}
	}
	var spans = this.assistance.result.getElementsByTagName("span");
	for (i = 0; i < spans.length; i++)
	{
		if (i == this.subst)
		{
			spans[i].style.backgroundColor = "#6181FF";
		}
		else
		{
			spans[i].style.backgroundColor = "transparent";
		}
	}
	setFocusPosition(this.field,  this.field.value.length);
}
	
/**
* Tag um den selectierten text erstellen
*/
InputAssistance.prototype.tagText = function(tagName) {
	// Can a text range be created?
	if (typeof(document.selection) != "undefined" && this.field.createTextRange && !is_opera)
	{
		this.field.focus();
		var range = document.selection.createRange();
		var insText = range.text;
		range.text = "["+tagName+"]" + insText + "[/"+tagName+"]";
		/* Anpassen der Cursorposition */
		range = document.selection.createRange();
		if (insText.length == 0) 
		{
			range.move('character', - ("[/"+tagName+"]").length);
		}
		else 
		{
			range.moveStart('character', ("["+tagName+"]").length + insText.length + ("[/"+tagName+"]").length);
		}
		range.select();
	}
	// Mozilla text range wrap.
	else if (typeof(this.field.selectionStart) != "undefined")
	{
		var begin = this.field.value.substr(0, this.field.selectionStart);
		var selection = this.field.value.substr(this.field.selectionStart, this.field.selectionEnd - this.field.selectionStart);
		var end = this.field.value.substr(this.field.selectionEnd);
		var newCursorPos = this.field.selectionStart;
		var scrollPos = this.field.scrollTop;

		this.field.value = begin +"["+tagName+"]" + selection + "[/"+tagName+"]" + end;

		if (this.field.setSelectionRange)
		{
			if (selection.length == 0)
				this.field.setSelectionRange(newCursorPos + ("["+tagName+"]").length, newCursorPos + ("["+tagName+"]").length);
			else
				this.field.setSelectionRange(newCursorPos, newCursorPos + ("["+tagName+"]").length + selection.length +("[/"+tagName+"]").length);
			this.field.focus();
		}
		this.field.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		this.field.value += "["+tagName+"]" + "[/"+tagName+"]";
		this.field.focus(this.field.value.length - 1);
	}
}


/**
* Dummy der keine Aktionen durchführt, wid geladen wenn der assistance disabled ist
*/
function InputAssistanceDummy()
{
	this.appendSign = function()
	{
	}
	this.insert = function()
	{
	}
	this.translate = function()
	{
	}
	this.init = function()
	{
	}
}


RichtextInputAssistance = function() {
}
/**
* Ein Buchstabe wird angefügt
*/
RichtextInputAssistance.prototype.insert = function(str) {
	this.field.getElementById("body").focus();
	this.field.execCommand("insertHTML", false, str);
	//this.field.innerHTML += str;
}
//RichtextInputAssistance.prototype = new InputAssistance();

function initAssistence()
{
	if (!(!(getCookie("assistance") && getCookie("assistance") == "false")))
	{
		// assistance ist disabled, dummy wird geladen
		inputAssistance = new InputAssistanceDummy();
	}
	else
	{
		inputAssistance = new InputAssistance();
	}
}

function initRichtextInputAssistence(obj) {
	if (inputAssistance.assistance) {
		inputAssistance.assistance.style.display = "none";
	}
	inputAssistance = new RichtextInputAssistance();
	inputAssistance.field = obj;
}

/*
* Drag and Drop Support
*/
document.onmousemove = mouseMove;
document.onmouseup   = mouseUp;

var dragObject  = null;
var dragItem  = null;
var mouseOffset = null;

function getMouseOffset(target, ev)
{
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(obj)
{
	var left = 0;
	var top  = 0;

	while (obj.offsetParent)
	{
		left += obj.offsetLeft;
		top += obj.offsetTop;
		obj = obj.offsetParent;
	}

	left += obj.offsetLeft;
	top  += obj.offsetTop;

	return {x:left, y:top};
}

/*
* Maus wurde bewegt
* dragObject wird analog verschoben
*/
function mouseMove(ev) {
	ev = ev || window.event;
	var mousePos = mouseCoords(ev);

	if(dragObject && mousePos) {
		dragObject.style.position = 'absolute';
		dragObject.style.top = (mousePos.y - mouseOffset.y) + "px";
		dragObject.style.left = (mousePos.x - mouseOffset.x) + "px";
		dragObject.style.right = "auto";
		dragObject.style.bottom = "auto";
		return false;
	}
}

/*
* Mouse Koordinaten werden ausgelesen
*/
function mouseCoords(ev){
	try {
		if(ev.pageX || ev.pageY){
			return {x:ev.pageX, y:ev.pageY};
		}
		return {
			x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:ev.clientY + document.body.scrollTop  - document.body.clientTop
		};
	}
	catch(e) {
		return null;
	}
}

/*
* Fall es ein dragable Object gibt wird dies wieder zurückgesetzt
*/
function mouseUp(){
	if (dragObject)
	{ 
		dragObject.onmousedown = function()
		{
			return false;
		}
	}
	if (dragItem)
	{
		dragItem.onmousedown = null;
	}
	dragObject = null;
}

/*
* Macht ein Object dragable
*/
function makeDraggable(item)
{
	if(!item) return;
	dragObject  = this;
	
	item.onmousedown = function(ev){
		dragObject  = this;
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
	dragItem = item;
}

// Linguatec
AC_FL_RunContent = 0;
/*addScript("/trainer/js/linguatec.js");
addScript("/trainer/js/animator.js");
addScript("/trainer/js/Lang/de.js");
addScript("/trainer/js/Lang/en.js");*/

/*
* Fügt einem Object ein Event hinzu
*/
function addEvent( obj, type, fn ) {
	if ( obj.attachEvent ) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else
		obj.addEventListener( type, fn, false );
	}
function removeEvent( obj, type, fn ) {
	if ( obj.detachEvent ) {
		obj.detachEvent( 'on'+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
		obj.removeEventListener( type, fn, false );
}


function showContent(node, id) {
	var openFolder = openTree(node);
	if (openFolder) {
		document.getElementById("learningcontent0").style.display = "none";
		document.getElementById("learningcontent"+id).style.display = "block";
	}
	else {
		document.getElementById("learningcontent"+id).style.display = "none";
		document.getElementById("learningcontent0").style.display = "block";
	}
}

/**
* Sucht alle Elemente mit einer Klasse
*/
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function showMore(node) {
	var obj = node.nextSibling;
	var offset = obj.innerHeight;
	obj.style.height = "0px";
	obj.style.display = "block";
	
	var anim = new Animator();
	anim.addSubject(new CSSStyleSubject(
		obj,
		"height: 0px;",
		"height: 300px"));
	anim.play();
}


function Page() {
	this.page = 1;
	this.name = "page";
	this.lastPage = 1;
}

Page.prototype.nextPage = function() {
	document.getElementById(this.name + this.page).style.display = "none";
	this.page++;
	document.getElementById(this.name + this.page).style.display = "block";
	if (this.page == this.lastPage) {
		document.getElementById(this.name + "-next").style.display = "none";
	}
	document.getElementById(this.name + "-prev").style.display = "block";
}

Page.prototype.prevPage = function() {
	document.getElementById(this.name + this.page).style.display = "none";
	this.page--;
	document.getElementById(this.name + this.page).style.display = "block";
	if (this.page == 1) {
		document.getElementById(this.name + "-prev").style.display = "none";
	}
	document.getElementById(this.name + "-next").style.display = "block";
}