/**
* Lückentext
*/
var ajaxGetSelectedVocables = new AjaxGetSelectedVocables();
function Exercise()
{
	this.url = server + "/trainer/editDictation.php?ajax=info";
	this.exercise = "dictation";
	this.words =new Array();
	this.vocableContainer = document.getElementById("vocableContainer");

	this.xslt = new Xslt();
	this.xPath = new XPath();
	this.xslt.init("Xsl/AJAX/manageExercise.php");

	// Vocabelliste
	this.xmlDoc = null;

	/**
	* Ergebniss des Ajax-Requests wird behandelt
	* Statische Funktion
	*/
	this.update = function()
	{
		if(exercise.xmlHttpReq.readyState == 4)
		{
			if (exercise.xmlHttpReq.responseXML && exercise.xmlHttpReq.responseXML.documentElement && exercise.xmlHttpReq.responseXML.documentElement.firstChild) {
				
				// Vokabeln vom Apache sind zurückgekommen
				if (exercise.xmlHttpReq.responseXML.documentElement.firstChild.nodeName == "vocablelisting") {
					// Laden einer Vocabelliste
					if (exercise.xmlHttpReq.responseXML.documentElement.getAttribute("load") == "true") {
						exercise.xmlDoc = exercise.xmlHttpReq.responseXML;
						exercise.renderList();
					}
					// Suchergebniss
					if (exercise.xmlHttpReq.responseXML.documentElement.getAttribute("search") == "true") {
						exercise.displaySearchResults(exercise.xmlHttpReq.responseXML);
					}
				}
				
				// Vocabeln vom dictQuery Ajax-Modul
				if (exercise.xmlHttpReq.responseXML.documentElement.firstChild.nodeName == "entrylisting") {
					//var doc = exercise.xslt.transformToDocument(exercise.xmlHttpReq.responseXML);
					exercise.displaySearchResults(exercise.xmlHttpReq.responseXML);
				}
				
				// Fehlermeldung vom Server
				if (exercise.xmlHttpReq.responseXML.documentElement.firstChild.nodeName == "error") {
					try {
						alert("Error on request\n\r"+exercise.xmlHttpReq.responseXML.documentElement.firstChild.textContent);
					}
					catch(e) {
						// IE
						alert("Error on request\n\r"+exercise.xmlHttpReq.responseXML.documentElement.firstChild.text);
					}
				}

				// Diktat ist geladen worden, "to" wird für die Autokorrektur verwendet
				if (exercise.xmlHttpReq.responseXML.documentElement.firstChild.nodeName == "dictation") {
					exercise.xPath.evaluate("//text", exercise.xmlHttpReq.responseXML);
					if ( exerciseText = exercise.xPath.iterateNext()) {
						if (exerciseText.textContent) {
							exercise.autocorrect(exerciseText.textContent);
						}
						else {
							exercise.autocorrect(exerciseText.text);
						}
					}
				}

				// Übersetzung ist geladen worden, "to" wird für die Ergebnissübernahme verwendet
				if (exercise.xmlHttpReq.responseXML.documentElement.firstChild.nodeName == "translation") {
					exercise.xPath.evaluate("//to/span", exercise.xmlHttpReq.responseXML);
					if ( exerciseText = exercise.xPath.iterateNext()) {
						var node = document.getElementById("exerciseContent");
						try {
							node.innerHTML = "";
							exerciseText = importNode(exerciseText, node.ownerDocument, true);
							node.appendChild(exerciseText);
							node.innerHTML += "&#160;";
						}
						catch(e) {
							// TODO: Warum funktioniert das nicht im IE?
							node.innerHTML = exerciseText.xml;
						}
						// node.innerHTML = exercise.innerHTML;
					}
				}
			}
		}
	}

	/**
	* Fügt dem Baustein eine Vokabel hinzu
	*/
	this.addVocable = function(id, sourceObj) {
		this.xPath.evaluate( "//vocable[xml/entry[@uid = '"+id+"']]", this.resultXml);
		var obj;
		if  (obj = this.xPath.iterateNext()) {
			if (this.xmlDoc) {
				// Es wird überprüft ob eine Vocabel mit der selben id bereits existiert
				this.xPath.evaluate( "//vocable[xml/entry[@uid = '"+id+"']]", this.xmlDoc);
				if (!(searchObj =  this.xPath.iterateNext())) {
					// Vocabel existiert nicht
					this.xPath.evaluate( "//vocablelisting", this.xmlDoc);
					try {
						var node = this.xmlDoc.importNode(obj, true)
						this.xPath.iterateNext().appendChild(node);
					}
					catch(ex) {
						this.xPath.iterateNext().appendChild(obj);
					}
				}
			}
			else {

			}
		}
		sourceObj.parentNode.parentNode.parentNode.removeChild(sourceObj.parentNode.parentNode);
		this.renderList();
	}

	/**
	* Entfernt eine Vokabel aus dem Baustein
	*/
	this.removeVocable = function(id, sourceObj)
	{
		this.xPath.evaluate( "//entry[@uid = '"+id+"']", this.xmlDoc);
		var obj;
		if  (obj = this.xPath.iterateNext())
		{
			obj.parentNode.removeChild(obj);
		}
		sourceObj.parentNode.parentNode.parentNode.removeChild(sourceObj.parentNode.parentNode);
	}


	/**
	* Die zum Lernbaustein gehörende Vocabelliste wird geladen
	*/
	this.loadVocables = function()
	{
		var str = "ajax=info&postBack=edit"+this.exercise+"&value[action]=load&value[object]=vocablelisting";
		this.startPostRequest(str);
	}


	/**
	* Der Inhalt von TreeContainer (Der Learninhaltsbaum) wird erzeugt
	*/
	this.renderList = function()
	{
		// Es wird überprüft ob eine Vokabel existiert
		this.xPath.evaluate("//entry", this.xmlDoc);
		var obj;
		if  (obj =  this.xPath.iterateNext())
		{
			this.xslt.setParameter("mode", "manage");
			var result = this.xslt.transformToDocument(this.xmlDoc);
			this.xslt.setParameter("mode", "");
			document.getElementById("vocableContainer").innerHTML = "";
			appendXSLTResult(document.getElementById("vocableContainer"), result);
		}
	}

	/**
	* Der Inhalt von TreeContainer (Der Learninhaltsbaum) wird erzeugt
	*/
	this.displaySearchResults = function(xml)
	{
		this.resultXml = xml;

		this.xslt.setParameter("mode", "add");
		var result = this.xslt.transformToDocument(xml.documentElement);
		this.xslt.setParameter("mode", "");

		document.getElementById('queryResult').innerHTML = "";
		appendXSLTResult(document.getElementById('queryResult'), result);
	}

	/**
	* Erzeugt einen Array aller Wörter in einem Knoten incl. Children
	*/
	this.parseHTML = function(node)
	{
		if (node.nodeValue && node.nodeValue != "")
		{
			return splitText(node.nodeValue);
		}
		else
		{
			var words = Array();
			for (var i = 0; i < node.childNodes.length; i++)
			{
				words = words.concat(this.parseHTML(node.childNodes[i]));
			}
			return words;
		}
	}

	/**
	* Findet die einzelnen Wörter ohne Satzzeichen in dem Text
	* kommt nicht mir HTML-Formatierten Strings zurecht
	*/
	this.findWords = function(str)
	{
		this.words.concat(splitText(str));
	}

	/**
	* Stellt eine Anfrage beim dictQuery für dieses Wort um dann ein Speichern zu ermöglichen
	*/
	this.queryDict = function(word)
	{
		var url = this.url;
		this.url = server +"/api/trainer.php?lp=" + lp+ "&lang=" + lang;
		this.resultObject = document.getElementById('queryResult');
		var where = -1;
		if (eval("document.queryDict.direction[1].checked")) {
			where = 1;
		}

		var str = "search=" + encodeURIComponent(word) + "&where=" + where + "&uid=" + idPerson;
		this.startPostRequest(str);
		this.resultObject = null;
		this.url = url;
		document.getElementById('value[search][]').value = word;
	}

	/**
	* Erstellt einen Text in dem die einzelnen Wörter anklickbar sind
	* Durch das klciken auf die Wörter wird eine Suche gestartet
	*/
	this.createQueryText = function(obj, cont)
	{
		var words;

		if (typeof(cont) == "string")
		{
			words =  splitText(cont);
		}
		else
		{
			words = this.parseHTML(cont);
		}

		var str = "<div>";
		for (var i = 0; i < words.length; i++)
		{
			if (words[i].trim() != "<br/>") {
				str += "<span onclick='exercise.queryDict(\"" + words[i].replace(/'/,"").replace(/"/,"") + "\");' >"+words[i]+"</span> ";
			}
			else {
				str += "<br/>";
			}
		}
		str += "</div>";
		str = str.replace(/((\n\r?)|\r)/g,'<br/>');
		obj.innerHTML = str;
	}

	/*
	* Speichert eine Übung ab
	*/
	this.save = function(event) {
		var str = postBackString(event, 'edit'+this.exercise);

		// Wortschatz wird gesammelt
		this.xPath.evaluate("//entry", this.xmlDoc);
		var obj;
		while (obj = this.xPath.iterateNext()) {
			str += "&value[idword][]=" + obj.getAttribute("uid");
			if (obj.getElementsByTagName("comment")[0] 
				&& obj.getElementsByTagName("comment")[0].textContent 
				&&  obj.getElementsByTagName("comment")[0].textContent.trim() != "") {
				str +=encodeURIComponent( "," + obj.getElementsByTagName("comment")[0].textContent);
			}
		}
		
		// Upload von dazugehörigem Bild bzw JPG
		var upload = false;
		if (this.exercise == "readingexercise" &&  document.getElementById("value[readingexercise][0][upload][0]") && document.getElementById("value[readingexercise][0][upload][0]").checked)
		{
			upload = true;
		}
		if (this.exercise == "dictation" && document.getElementById("value[dictation][0][upload][0]") && document.getElementById("value[dictation][0][upload][0]").checked)
		{
			upload = true;
		}

		// Syncroner Request, damit die Session["IdExercise"] gesetzt wird
		document.getElementById('assistance').style.display = 'none';
		ajaxGetPopUp.asyncron = false;
		ajaxGetPopUp.startPostRequest(str);
		ajaxGetPopUp.asyncron = true;

		// PopUp für Upload von MP3 File bzw. JPEG wird geöffnet
		if (this.exercise == "readingexercise" &&  upload && !document.getElementById('edit'+this.exercise))
		{
			var uploadWindow = document.open(server + trainerPath + '/uploadImg.php', 'uploadWindow','width=640,height=480,left=100,top=200');
			uploadWindow.focus();
		}
		if (this.exercise == "dictation" && upload && !document.getElementById('edit'+this.exercise))
		{
			var uploadWindow = document.open(server + trainerPath + '/uploadMP3.php', 'uploadWindow','width=640,height=480,left=100,top=200');
			uploadWindow.focus();
		}
	}

	/*
	* Öffnet einen Dialog um einer Vokabel einen Kommentar hinzuzufügen
	*/
	this.editComment = function(event, idword)
	{
		this.xPath.evaluate("//vocablelisting/vocable[idword='"+idword+"']", this.xmlDoc);
		var obj;
		if (obj = this.xPath.iterateNext())
		{
			this.renderBlock(obj);
			positionRight(event, document.getElementById("smallpopup"));
		}
	}

	/*
	* Speichert einen Comment ab
	*/
	this.updateComment = function(idword, comment)
	{
		this.xPath.evaluate("//vocablelisting/vocable[idword='"+idword+"']", this.xmlDoc);
		var obj;
		if (obj = this.xPath.iterateNext())
		{
			obj.getElementsByTagName("comment")[0].textContent = comment;
		}
		document.getElementById("smallpopup").style.display = "none";
	}

	/*
	* Der Inhalt für das Dialogfeld wird erzeugt
	*/
	this.renderBlock = function(obj)
	{
		this.xslt.setParameter("mode", "comment");
		var result = this.xslt.transformToDocument(obj);
		this.xslt.setParameter("mode", "");

		document.getElementById("smallpopupcontent").innerHTML = "";
		document.getElementById("smallpopupcontent").appendChild(result.documentElement);
		document.getElementById("smallpopup").style.display = "block";
	}

	/*
	* Ausgefüllte Übung wird zur Korrektur gespeichert
	*/
	this.solve = function(obj)
	{
		this.url = ajaxGetPopUp.url;
		var str = "ajax=info&postBack=view"+this.exercise+"&value[action]=load&value[object]=exercise";
		this.startPostRequest(str);
	}

	/*
	* Autokorrektur für eine Übung
	*/
	this.autocorrect = function(resultText, exerciseText, textarea)
	{
		//var correction = diffString(resultText, exerciseText);
		debuger();
	}
	
	/*
	* Erzeugt ein Preview
	*/
	this.preview = function() {
		if (!is_ie)
		{
			var previewDoc = document.implementation.createDocument("", "", null);
		}
		else
		{
			var previewDoc = new ActiveXObject("Microsoft.XMLDOM");
		}
		var root = previewDoc.createElement(this.exercise);
		
		var nameNode = previewDoc.createElement("name");
		nameNode.appendChild(previewDoc.createTextNode(document.getElementById('value['+this.exercise+'][0][name][0]').value));
		root.appendChild(nameNode);
		
		
		var str = this.convertBBCode(document.getElementById('value['+this.exercise+'][0][text][0]').value);
		try {
			var node = previewDoc.importNode(loadXMLString("<text><span>"+str+"</span></text>").documentElement, true);
			root.appendChild(node);
		}
		catch(e) {
			root.appendChild(loadXMLString("<text><span>"+str+"</span></text>").documentElement);
		}
		
		if (this.exercise == "readingexercise" && document.getElementById("cloze0").getElementsByTagName("img")[0])
		{
			var img = document.getElementById("cloze0").getElementsByTagName("img")[0];
			var imgNode = previewDoc.createElement("image");
			imgNode.appendChild(previewDoc.createTextNode(img.src.replace(/.*\/trainer\/upload/,"")));
			root.appendChild(imgNode);
		}
		if (this.exercise == "translation") {
			var str = this.convertBBCode(document.getElementById('value['+this.exercise+'][0][to][0]').value);
			try {
				var node = previewDoc.importNode(loadXMLString("<to><span>"+str+"</span></to>").documentElement, true);
				root.appendChild(node);
			}
			catch(e) {
				root.appendChild(loadXMLString("<to><span>"+str+"</span></to>").documentElement);
			}
		}
		
		previewDoc.appendChild(root);
		
		var result = this.xslt.transformToDocument(root);
		document.getElementById('preview').innerHTML = "";
		appendXSLTResult(document.getElementById('preview'), result);
	}
	
	/*
	* Wandelt BB-Code in HTML um und gibt den Text als Knoten zurück
	*/
	this.convertBBCode = function(str)
	{
		str = str.replace(/\[i\]/g,"<i>");
		str = str.replace(/\[\/i\]/g,"</i>");
		str = str.replace(/\[b\]/g,"<b>");
		str = str.replace(/\[\/b]/g,"</b>");
		return str;
	}
}
Exercise.prototype = new Ajax();

function PreviewExercise(name) {
	this.name = name;
	this.option = new Option();
}
PreviewExercise.prototype.setData = function(page, limit, orderBy) {
	this.option.page = page;
	this.option.limit = limit;
	this.option.orderBy = orderBy;
}

PreviewExercise.prototype.loadPage = function(page) {
	if (page) {
		this.option.page = page;
	}
	ajaxGetPopUp.startPostRequest("postBack=select" + this.name + "&lp=" + lp +"&lang=" + lang + encodeURI(this.option.toString()));
}

PreviewExercise.prototype.editExercise = function(id) {
	ajaxGetPopUp.startPostRequest("postBack=select" + this.name + "&lp=" + lp +"&lang=" + lang +"&value[" + this.name + "listing][0]="+id+"&selectbutton=select"+encodeURI(this.option.toString()));
}


/**
* Bricht einen Text in einzelne Wörter auf
*/
function splitText(str)
{
	var words =new Array();
	// Leerzeichen werden ersetzt
	str = str.replace(/[\t\v\u00a0\u2028\u2029]+/g, ' ');
	str = str.replace(/(\r|\n)+/g,' <br/> ');
	//str = str.replace(/["\.,\+\?:']+/g, ' ');
	str = str.replace(/\[i\]+/g, ' ');
	str = str.replace(/\[\/i\]+/g, ' ');
	str = str.replace(/\[b\]+/g, ' ');
	str = str.replace(/\[\/b\]+/g, ' ');
	str = str.replace(/\s+/g, ' ');
	return str.split(" ");
}
