/* ajax framework */

var id;

// creates a xml HTTP Request Object
function createXmlHttpRequestObject() {
	var xmlTemp;
	
	try {
		xmlTemp = new XMLHttpRequest();	
	}
	catch(e) {
		var xmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0', 
                                    	'MSXML2.XMLHTTP.5.0', 
                                    	'MSXML2.XMLHTTP.4.0', 
                                    	'MSXML2.XMLHTTP.3.0', 
                                    	'MSXML2.XMLHTTP', 
                                    	'Microsoft.XMLHTTP');	
		for(var c = 0; c < xmlHttpVersions.length && !xmlTemp; c++) {
			try {
				xmlTemp = new ActiveXObject(xmlHttpVersions[i]);
			}
			catch(e) {}
		}
	}
	if(!xmlTemp)
		alert("Error creating XMLHttpRequest object. (" + e.toString() + ")");
	else
		return xmlTemp;
}

function trim (zeichenkette) {
  return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function validate(element, type) {
	xml = createXmlHttpRequestObject();
	openRequest(xml, "POST", "_system/validate.php", true, handleValidation, "value=" + element.value + "&type=" + type + "&name=" + element.name);
}

function handleValidation(xmlHttp) {
	var xmlResponse = xmlHttp.responseXML;
	var xmlRoot = xmlResponse.documentElement;
	
	var message = xmlRoot.getElementsByTagName("message").item(0).firstChild.data;
	var name = xmlRoot.getElementsByTagName("name").item(0).firstChild.data;
	
	if(message == "OK") {
		document.forms[0].elements[name].style.borderColor = "#0F0";	
	}
	else {
		document.getElementById(name + "Error").innerHTML = message;
		document.forms[0].elements[name].style.borderColor = "#F00";
	}
}

function jsValidate(value) {
	if(trim(value.value) == "") {
		value.style.borderColor = "#F00";
		return false;
	}
	else {
		value.style.borderColor = "#0F0";
		return true;
	}
}

function checkValidation(value, id) {
	for(var c = 0; c < document.forms[0].elements.length; c++) {
		if(document.forms[0].elements[c].type == 'text' || document.forms[0].elements[c].type == 'textarea') {
			
			if(document.forms[0].elements[c].name == "hp") continue;
			
			if(document.forms[0].elements[c].style.borderColor.toString() != 'rgb(0, 255, 0) rgb(0, 255, 0) rgb(0, 255, 0) rgb(0, 255, 0)') {
				if(jsValidate(document.forms[0].elements[c]) == false)
					alert('Alle Felder mit einem * muessen ausgefuellt werden.');
				else
					continue;
				return false;
			}
		}
	}
	if(value == "comment") {
		addComment(id);
	}
	if(value == "guestbook") {
		addGBEntry();
	}
	return true;
}

function addGBEntry() {
	xml = createXmlHttpRequestObject();
	
	openRequest(xml, "POST", "content/guestbook/addEntry.php", true, handleNewGBEntry, "name=" + document.forms[0].elements['name'].value +
																					"&rating=" + document.forms[0].elements['rating'].value + 
																					"&text=" + document.forms[0].elements['text'].value + 
																					"&email=" + document.forms[0].elements['email'].value + 
																					"&hp=" + document.forms[0].elements['hp'].value);
	
	document.getElementById('newEntry').innerHTML = '';
	document.getElementById('newEntry').appendChild(getLoadingScreen('Ihr Beitrag wird eingetragen...'));
}

function handleNewGBEntry(xmlHttp) {
	var xmlResponse = xmlHttp.responseXML;
	var xmlRoot = xmlResponse.documentElement;
	
	document.getElementById('newEntry').innerHTML = '';
	var p = document.createElement('p');
	p.style.textAlign = "center";
	
	if(xmlRoot.firstChild.data == "true") {
		
		p.style.color = "lime";
		p.innerHTML = 'Ihr Beitrag wurde erfolgreich eingetragen.';
		
		document.getElementById('newEntry').appendChild(p);
		
		loadEntries();
	}
	else  {
		
		p.style.color = "red";
		p.innerHTML = 'Bei Ihrem Beitrag gab es Probleme, bitte aktualisieren Sie die Seite (F5 (Windows), Command + R (Mac) und versuchen Sie es erneut.';
		document.getElementById('newEntry').appendChild(p);
																																						  
	}
}

function addComment(id) {
	xml = createXmlHttpRequestObject();
	
	openRequest(xml, "POST", "content/news/addComment.php", true, handleNewComment, "name=" + document.forms[0].elements['name'].value +
																					"&rating=" + document.forms[0].elements['rating'].value + 
																					"&text=" + document.forms[0].elements['text'].value + 
																					"&nid=" + id);
	
	document.getElementById('newComment').innerHTML = '';
	document.getElementById('newComment').appendChild(getLoadingScreen('Ihr Beitrag wird eingetragen...'));
}

function handleNewComment(xmlHttp) {
	location.href = location.href;
}

// starts asynchronouse request
function openRequest(xmlHttp, method, path, async, handle, send) {
	if(xmlHttp) {
		try {
			xmlHttp.open(method, path, async);
			xmlHttp.onreadystatechange = function() {
				if(xmlHttp.readyState == 4) {
					if(xmlHttp.status == 200) {
						//try {
							if(xmlHttp.responseXML == null)
								alert("Invalid XML Structure.");
							else
								handle(xmlHttp);
						/*}
						catch(e) {
							alert("Error reading response: " + e.toString());	
						}*/
					}
					else {
						alert("Error occured during recieving response.");	
					}
				}
			}
			if(method == "POST")
				xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xmlHttp.send(send);
		}
		catch(e) {
			alert("Error by opening request. (" + e.toString() + ")");
		}
	}
}

/* design framework */
function getLoadingScreen(text) {
	var p = document.createElement("p");
	var img = document.createElement("img");
	var text = document.createTextNode(text);
	
	// setting attributes
	p.className = "loading";
	img.src = "img/common/ajax-loader.gif";
	
	p.appendChild(img);
	p.appendChild(text);
	
	return p;
}

function openImage(id) {
	if(document.getElementById("document")) {
		closeImage();
		
		var div  = document.createElement("div");
		div.id = "imageView";
		document.getElementById("document").appendChild(div);
		div.style.visibility = "visible";
			
		document.getElementById("imageView").innerHTML = '';
		document.getElementById("imageView").appendChild(getLoadingScreen("Laden..."));
		
		xmlImage = createXmlHttpRequestObject();
		openRequest(xmlImage, "POST", "content/home/loadImage.php", true, displayImage, "id=" + id);
	}
	else {
		alert("document div not found");	
	}
}

function displayImage(xmlHttp) {
	var xmlResponse = xmlHttp.responseXML;
	var xmlRoot = xmlResponse.documentElement;
	
	if(xmlRoot.getElementsByTagName("name").item(0).firstChild.data != null)
		var name = xmlRoot.getElementsByTagName("name").item(0).firstChild.data;
	else
		var name = "Kein Name";
	
	var path = xmlRoot.getElementsByTagName("path").item(0).firstChild.data;
	var date = xmlRoot.getElementsByTagName("date").item(0).firstChild.data;
	
	if(xmlRoot.getElementsByTagName("text").item(0).firstChild.data != null)
		var text = xmlRoot.getElementsByTagName("text").item(0).firstChild.data;
	else
		var text = "";
	
	document.getElementById("imageView").innerHTML = '';
	view = document.getElementById("imageView");
	view.onclick = closeImage;
	
	var head = document.createElement('h1');
	head.innerHTML = name;
	
	var img = document.createElement('img');
	img.src = path;
	
	var datum = document.createElement('p');
	datum.innerHTML = date;
	datum.className = "date";
	
	var content = document.createElement('p');
	content.innerHTML = text;
	content.className = "content";
	
	view.appendChild(head);
	view.appendChild(img);
	view.appendChild(datum);
	view.appendChild(content);
	
	
}

function closeImage() {
	if(document.getElementById("imageView") != null) {
		document.getElementById("imageView").innerHTML = '';
		document.getElementById("document").removeChild(document.getElementById("imageView"));
	}
}

/* functionality */
function addTag(text, control, form) {
	document.forms[form].elements[control].value += text;
}

function showImage(path, id) {
	document.getElementById(id).innerHTML = '';
	if(path != '') {
		var img = document.createElement('img');
		img.src = path;
		document.getElementById(id).appendChild(img);
	}
}

function toggleContent(show, hide) {
	document.getElementById(show).style.visibility = "visible";
	document.getElementById(hide).style.visibility = "hidden";
}
