function sendJson(modul,data,data2) // modul = function, data = data send by ajax, data2 = parameters as an object for javascript function
{
	if (!modul) return;
	
	$('#loading').show();
	var param = 'ajax=true';
	
	if (isArray(modul)){ // more functions
		for (var i=0; i<modul.length; i++) param += '&modul'+i+'='+modul[i];
		param += '&modulNumber='+modul.length;
	}	
	else param += '&modul='+modul;
	
	if (data) $.each(data, function(key,value){ param += '&'+key+'='+escape(nl2br(value)); });

	$.ajax({
		type: 'POST',
		url: file,
		success: function (answer){ answerAjax(answer,modul,data2) },
		dataType: 'json',
		data: param
	});
}
function sendEvt(element,data)
{
	if (isArray(data)){
		modul = data[0];
		sendJson(modul,data[1],data[2]);
	} 
	else sendJson(data);
}
function answerAjax(answer,modul,data2)
{
	answer = decodeObject(answer);
	$('#loading').hide();
	if (answer.error) write(answer.error);
	else if (isArray(modul)){
		for (var i=0; i<modul.length; i++){				
			if (data2 && data2[modul[i]]) window[modul[i]](answer,data2[modul[i]]);	
			else window[modul[i]](answer);					
		} 
	} 
	else if (data2) window[modul](answer,data2);
	else if (window[modul]) window[modul](answer);	
	else write(answer.success);
}
function answerPHP(json)
{
	var answer = eval('(' + json + ')');
	answerAjax(answer,answer.modul);
}
function write(text,noOverwrite)
{
	if (noOverwrite && infoFull()) return;
	
	window.clearInterval(infoInterval1);
	window.clearInterval(infoInterval2);
	
	var element = getObject('info');
	if (infoFull()) element.innerHTML += ' --- ' + text;
	else element.innerHTML = text;
	element.style.display = 'inline';
	element.style.marginTop = '-01px';
	infoInterval1 = window.setInterval('slideStatusPre()',10000); // wait 10 seconds
}
function object(key1,value1,key2,value2,key3,value3,key4,value4,key5,value5)
{
	var object = new Object();
	object[key1] = value1;
	if (key2) object[key2] = value2;
	if (key3) object[key3] = value3;
	if (key4) object[key4] = value4;
	if (key5) object[key5] = value5;
	return object;
}
function nl2br(str) 
{
    return (str + '').replace(/([^>]?)\n/g, '$1<br>');
}
function decodeObject(answer)
{
	$.each(answer,function(field1,value1){
		
		if (isArray(value1)) $.each(value1,function(field2,value2){

			if (isArray(value2)) $.each(value2,function(field3,value3){
				
				if (isArray(value3)) $.each(value3,function(field4,value4){
					answer[field1][field2][field3][field4] = decodeUrl(value4);
				});
				else answer[field1][field2][field3] = decodeUrl(value3);
			});
			else answer[field1][field2] = decodeUrl(value2);

		});
		else answer[field1] = decodeUrl(value1);
		
	});
	return answer;	
}
function decodeUrl(str)
{
	var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
	var ret = str.toString();
	
	var replacer = function(search, replace, str){
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
	
//	// The histogram is identical to the one in urlencode.
//	histogram['!'] = '%21';
//	histogram['%20'] = '+';
//
//	for (replace in histogram) {
//		alert(replace);	
//		search = histogram[replace]; // Switch order when decoding
//		ret = replacer(search, replace, ret) // Custom replace. No regexing 
//		//ret = ret.replace(search, replace) // Custom replace. No regexing    
//	}

	// End with decodeURIComponent, which most resembles PHP's encoding functions
	//ret = decodeURIComponent(ret); // just utf-8
	ret = unescape(ret); // also iso but obsolet
	
	return ret;
}
function slideStatusPre()
{
	window.clearInterval(infoInterval1);
	infoInterval2 = window.setInterval('slideStatus()',100); // then slide it back
}
function slideStatus()
{	
	var element = getObject('info');
	var pixel = parseInt(element.style.marginTop.substring(1,3));
	pixel++;
	element.style.marginTop = '-' + pixel + 'px';
	if (pixel == 20){
		window.clearInterval(infoInterval2);
		element.style.display = 'none';
	} 
}
function link(element,href)
{
	document.location.href = href;
}
function infoFull() 
{
	if (getObject('info').style.display == 'inline') return true;
	else return false;
}
function infoTip(element,text)
{
	if (text == undefined) return;
	var cont = createContainer(document.body,'','infoTip');
	createTextNew(cont,'','',text);		
	positionSet(element,cont);
}
function infoTipDelete()
{
	$('.infoTip').remove();
}
function positionSet(element,cont)
{
	var newLeft = positionLeft(element);

	var newTop = positionTop(element);
	newLeft -= 100;
	// IE doesn't support window.outerHeight
	if ($.browser.msie || newTop+100 > window.outerHeight) newTop -= 100; // so it won't be hidden in the bottom
	else newTop += 50; 
	cont.style.left = newLeft + 'px';
	cont.style.top = newTop + 'px';
}
function positionLeft(inputObj)
{
	var returnValue = inputObj.offsetLeft;
	while((inputObj = inputObj.offsetParent) != null){
		if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
	}
	return returnValue;
}
function positionTop(inputObj)
{		
	var returnValue = inputObj.offsetTop;
	while((inputObj = inputObj.offsetParent) != null){
		if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
	}
	return returnValue;
}
function refresh()
{
	location.reload();
}
function wait(seconds){
    
	time = seconds * 1000;    
	var starttime = (new Date).getTime();
	while (starttime+time>(new Date).getTime()){};
}
function firstBig(str)
{
	var first = str.substring(0,1);
	var first = first.toUpperCase();
	var second = str.substring(1,str.length);
	return first + second;
}
function getObject(id)
{
	return document.getElementById(id);
}
function getValue(id)
{
	return document.getElementById(id).value;
}
function getSelected(element)
{
	var index = element.options.selectedIndex;
	var value = element.options[index].value;
	return value;
}
function createImage(parentObj,source,onclick){
	
	var element = document.createElement('IMG');
	element.src = source;
	element.onclick = click;
	if (onclick) {
		element.id = onclick;
		element.style.cursor = 'pointer';
	}
	parentObj.appendChild(element);
	return element;
}
function showForm(){
	document.getElementById('userdata').style.display = 'inline';
}
function display(id,parent)
{
	var element = getObject(id);
	if (parent) element = element.parentNode;	
	var display = element.style.display;
	
	if (display == 'none') element.style.display = 'inline';
	else element.style.display = 'none';
}
function radioDisplay(id,radio)
{
	var element = getObject(id);
			
	if (getObject(radio).checked) element.style.display = 'inline';
	else element.style.display = 'none';
}
function getRestId(idArray,remove1,remove2)
{
	if (remove1 || remove1 == 0) idArray = arrayDrop(idArray,null,remove1);
	if (remove2 || remove2 == 0) idArray = arrayDrop(idArray,null,remove2);
	return idArray.join('_');
} 
function showTooltip(parentObj,text)
{
	var container = createContainer(document.body,'tooltip','tooltip');
	createText(container,text);
	newLeft = getLeftPos(parentObj);
	newTop = getTopPos(parentObj) + 50;
	container.style.left = newLeft + 'px';
	container.style.top = newTop + 'px';	
}
function removeTooltip()
{
	$('#tooltip').remove();
}
function removeElement(id)
{
	var element = getObject(id);
	element.parentNode.removeChild(element);
}
function getTopPos(inputObj)
{		
  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null){
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
  }
  return returnValue;
}

function getLeftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null){
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
  }
  return returnValue;
}
function removeChildren(element,leaveFirst)
{
	var children = element.childNodes;
	for (var i = children.length - 1; i >= 0; i--) { // start with the last
		if (leaveFirst && i == 0) continue;
		element.removeChild(children[i]);
	}
}
function isArray(variable)
{
	if (typeof variable == 'object') return true;
	else return false;
}
function local()
{
	if (document.location.host == 'localhost') return true;
	return false;
}
function deleteCookie()
{
	var expires = 'Fri, 02 Jan 1970 00:00:00 UTC;';
	document.cookie = 'name=; expires=' + expires + ';';
	document.cookie = 'user=; expires=' + expires + ';';
	document.cookie = 'pass=; expires=' + expires + ';';
}
function setCookie(varArray,valueArray)
{
	//var expires = 'Sat, 31 Dec 2050 20:00:00 UTC';
	var expires = 'Sat, 31 Dec 2050 20:00:00 GMT';
	document.cookie = 'name=materialDB; expires=' + expires + ';'; // add expires to every single variable
    for (var i=0; i<varArray.length; i++) document.cookie = varArray[i]+'='+valueArray[i]+'; expires='+expires+';';	 
}
function getCookie(varArray)
{
	var valueArray = new Array();
	var start;
	var value;
	var end;
	
	for (var i=0; i<varArray.length; i++){
		
		start = document.cookie.indexOf(varArray[i]);
		if (start == -1) continue;
		start = start + varArray[i].length + 1;
		value = document.cookie.substr(start);
		end = value.indexOf(';');
		if (end != -1) valueArray.push(value.substr(0,end));
		else valueArray.push(value.substr(0));
	}	
	return valueArray;
}
function withCookie()
{
	if(document.cookie) return true;
	else return false;
}
function checkInput(id,type,optional)
{	
	var element = getObject(id);
	if (optional && element.value == '') return true;
	var className = element.className.split('_')[0];

	if (!check(element.value,type)) {
		element.className = className + '_wrong';
		return false;
	}
	else {
		element.className = className + '_right';
		return true;
	}
}
function check(text,type)
{
	var reg;
	switch(type)
	{		
		case 'mail':		reg = eval('/^([a-zA-Z0-9_\.\-])+[\@](([a-zA-Z0-9\-])+[\.])+[a-zA-Z0-9]{2,4}$/'); break;
		case 'website':		reg = eval('/^(([a-zA-Z0-9\-])+[\.])+[a-zA-Z0-9]{2,4}$/'); break;
		case 'password':	reg = eval('/^[a-zA-Z0-9§(\x20-\x7E)]{4,20}[^\"\']$/i'); break; // x20-x7E special characters, without stringbreaker 
		case 'tel':			reg = eval('/^[0-9]{3,15}$/i'); break;
		case 'housenumber':	reg = eval('/^[0-9]{1,5}$/i'); break;
		case 'postcode':	reg = eval('/^[0-9]{1,5}$/i'); break;
		case 'text':		reg = eval('/^[a-z0-9\- ]{2,50}$/i'); break;
		default:			reg = eval('/^[a-z0-9\-äöüß ]{2,50}$/i'); break;
	}
	
	return reg.test(text);
}
function closeThickbox(id)
{
	var element = getObject(id);
	removeChildren(element);
}
function getAscii(text)
{
	while (text.search(/ä/) != -1) text = text.replace(/ä/,'&auml;');
	while (text.search(/ü/) != -1) text = text.replace(/ü/,'&uuml;');
	while (text.search(/ö/) != -1) text = text.replace(/ö/,'&ouml;');
	while (text.search(/ß/) != -1) text = text.replace(/ß/,'&szlig;');
	return text;
}
function encrypeText(text)
{
	text = getAscii(text);
	while (text.search(/\,/) != -1) text = text.replace(/\,/,'komma');
	while (text.search(/\=/) != -1) text = text.replace(/\=/,'istgleich');
	while (text.search(/\&/) != -1) text = text.replace(/\&/,'undzeichen');
	while (text.search(/\+/) != -1) text = text.replace(/\+/,'plus');
	while (text.search(/\*/) != -1) text = text.replace(/\*/,'sternchen');

	// stripslashes
	text=text.replace(/\\'/g,'\'');
	text=text.replace(/\\"/g,'"');
	text=text.replace(/\\\\/g,'\\');
	text=text.replace(/\\0/g,'\0');

	return text;
}
function descrypeText(text)
{
	while (text.search(/komma/) != -1) text = text.replace(/komma/,',');
	while (text.search(/istgleich/) != -1) text = text.replace(/istgleich/,'=');
	while (text.search(/undzeichen/) != -1) text = text.replace(/undzeichen/,'&');
	while (text.search(/sternchen/) != -1) text = text.replace(/sternchen/,'*');
	return text;
}
function encrypePassword(password)
{
	var newPassword = '';
	for (var i=0; i<password.length; i++){
		if (i != 0) newPassword += '-';
		newPassword += password.charCodeAt(i) + 5;		
	} 
	return newPassword;
}
function descrypePassword(password)
{
	var passwordArray = password.split('-');
	var newPassword = '';
	for (var i=0; i<passwordArray.length; i++) newPassword += String.fromCharCode(passwordArray[i] - 5);
	return newPassword;
}
function arrayDrop(array,value,id)
{
	var newArray = new Array();
	for (var i=0; i<array.length; i++) {
		
		if (i == id) continue;
		if (array[i] == value) continue;
		newArray.push(array[i]);
	};
	return newArray;
}
function arrayDropAss(array,value,title,startId)
{
	var newArray = new Array();
	if (startId) newArray.push(null);
	for (var i=0; i<array.length; i++) {
		
		if (!array[i] || array[i][title] == value) continue;
		newArray.push(array[i]);
	};
	return newArray;
}
function phpAnswer(json)
{
	write(json);
	var answer = eval('(' + json + ')');
	answer = decodeObject(answer);
	$('#loading').hide();
	
	if (answer.error) write(answer.error.id + ': ' + answer.error.text);
	else window[answer.modul](answer);
}
function phpVariable(variable,json)
{
	window[variable] = eval('(' + json + ')');
}
function addLabels(text)
{	
	var param = text.split(',')
	for (var i=0; i<param[0]; i++){
		
		var textArray = param[1+i].split('*');
		var text = descrypeText(textArray[2]);		
		labels[textArray[1]] = text;
		var element = getObject(textArray[1]);
		if (element) element.innerHTML = text;
	} 
	
}
function object(key1,value1,key2,value2,key3,value3,key4,value4,key5,value5)
{
	var object = new Object();
	object[key1] = value1;
	if (key2) object[key2] = value2;
	if (key3) object[key3] = value3;
	if (key4) object[key4] = value4;
	if (key5) object[key5] = value5;
	return object;
}
function obj(id)
{
	return document.getElementById(id);
}
function value(id)
{
	var element = obj(id);
	if (element) return element.value;
	return false;
}
function cValue(id)
{
	var element = obj(id);
	if (!element) return false;
	return element.checked;
}
function cgValue(id) // checkgroup
{
	var value = '';
	
	$('input[@name='+id+']').each(function(i){
		if (this.checked) value += 'x';
		else value += '-';
	});
	
	return value;
}
function sValue(id)
{
	var element = obj(id);
	var index = element.options.selectedIndex;
	var value = element.options[index].value;
	return value;
}
function evtOver(element)
{
	element.className += '_over';
}
function evtOut(element)
{
	element.className = element.className.split('_')[0];
}
function onAdmincell(evt)
{
	onText('',this,'admincell');
}
function onLongtext(evt)
{
	onText(evt,this,'longtext');
}
function onText(evt,parentObj,detail)
{
	if (detail != 'admincell'){
		if (!evt) evt = event; // for internet explorer
		if (user != adminUser || !evt.ctrlKey) { // just admin and with ctrl, otherwise normal function
			if (!parentObj) parentObj = this;
			click(evt,parentObj);
			return;
		}	
	}
	if (!parentObj) parentObj = this;
	if (!parentObj.id) return;
	
	oldText = parentObj.innerHTML;
	//while (oldText.search(/<br>/) != -1) oldText = oldText.replace(/<br>/,'\n');
	parentObj.innerHTML = '';
	
	if (detail == 'longtext') var textfield = createTextarea(parentObj,'','','areaedit','',oldText);
	else var textfield = createInput(parentObj,oldText,'text','','textedit');
	
	//textfield.focus();
	//textfield.style.font = parentObj.style.font;
	textfield.select();
	textfield.onblur = click;
	if (detail != 'longtext') textfield.onkeypress = click;
	textfield.id = 'link_submitText';
	if (detail) textfield.id += '_' + detail;
	parentObj.onclick = '';
}
function submitText(idArray)
{
	var element = getObject(idArray.join('_'))
	var text = element.parentNode;
	
	if (!idArray[2]) text.onclick = onText;
	else text.onclick = window['on'+firstBig(idArray[2])]; // onAdmincell or onLongtext
	
	//if (element.value == " ") return;
	newText = element.value;
	//while (newText.search(/(\r\n|\n|\r)/) != -1) newText = newText.replace(/(\r\n|\n|\r)/,'<br>');
	//while (newText.search(/\\"/) != -1) newText = newText.replace(/\\"/,'&#x22;');

	text.innerHTML = newText;
	saveText(text,idArray[2]);
}
function submitForm(element,formId)
{
	var data = new Object();
	
	if (formId){
		var modul = formId;
		var children = obj(formId).childNodes;
	}
	else{
		var modul = element.parentNode.id;
		var children = element.parentNode.childNodes;
	}
	
	// get the values of the textfields
	for (var i=0; i<children.length; i++){
		
		//if (formId){ // two container in between
			var children2 = children[i].childNodes;
			for (var j=0; j<children2.length; j++) data = submitChildrenValue(data,children2[j]);
		//} 
		data = submitChildrenValue(data,children[i]);
	} 
	
	// false input?
	if (data.error) write(labels['errorUncomplete']);
	else sendJson(modul,data);
}
function submitChildrenValue(data,element)
{
	if (element.tagName == 'INPUT') $(element).trigger('blur');
	else if (element.tagName == 'TEXTAREA' || element.tagName == 'SELECT') $(element).trigger('keyup');	
	else return data; // no textfield
	if (element.type == 'submit') return data; // no textfield -> return	
	
	if (element.name == 'error') data.error = true; // error
	else if (element.type == 'checkbox'){
		if (element.name == 'mandatory' && !element.checked) data.error = true; // is not checked
		else if (element.name) data[element.name] = cgValue(element.name); // checkbox group TODO just go in there once
		else data[element.id] = element.checked;	
	}
	else if (element.type == 'radio') data[element.name] = rValue(element.name); // radio group TODO just go in there once
	else if (element.tagName == 'SELECT') data[element.id] = sValue(element);
	else data[element.id] = element.value;
	return data;
}
function submitField(element,fieldId)
{
	if (fieldId) var element = obj(fieldId);
	$(element).trigger('blur');
	if (!element.value || element.style.borderColor == 'red') return;
	send(element.id,object(element.id,element.value));
}
function submit(element,form)
{
	form.submit();
}
function saveText(element,detail)
{
	var idArray = element.id.split('_');
	var id = element.id;
	var text = encrypeText(element.innerHTML);
	if (detail == 'admincell') changeData('saveAdminText',idArray[0],Array(idArray[2]),Array(text),Array('id'),Array(idArray[1]));
	else if (detail == 'longtext') sendJson('textSave',object('id',id,'text',text));
	else sendJson('textSave',object('id',id,'text',text,'type','short')); // short text
}
function textSave(answer)
{
	labels[answer.id] = answer.text;
	$('#'+answer.id+'_cont').html(answer.text);
}
function getXmlHttpRequestObject() 
{	
	if (window.XMLHttpRequest) return new XMLHttpRequest(); // Not IE	 
	else if(window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP'); //IE	
	else write('Your browser does not support the XmlHttpRequest object.');	
}
function answer(req)
{	
	if (req.readyState != 4) return;
			
	var answer = req.responseText;
	//alert(answer);		
	
	// xml
	if (answer.substr(0,1) == '<'){
		mailAvailableAnswer(req);
		return;
	}
	
	var param = answer.split(',');	
	if (!param[0] || !param[1]) return; // response incorrect
	else if (param[0] == 'editor') receiveEditor(req.responseText.split('***html***'));
	else {
		var functionArray = param[1].split('_');
		if (!functionArray[1]) window[functionArray[0]](param); 	
		else window[functionArray[0]](param,functionArray[1]); // with detail
	}
}
function getData(modul,table,selectArray,whereArray,valueArray,whileBool,sortArray,sortDirection,header,orWhereArray,orValueArray)
{
	var uri = file + '/?action=getDataAjax';
	var post = 'modul=' + modul;
	post += '&table=' + table;
	if (selectArray) post += '&selectArray=' + selectArray.join('*');
	else whileBool = true;
	if (whereArray) post += '&whereArray=' + whereArray.join('*');
	if (valueArray) post += '&valueArray=' + valueArray.join('*');
	if (whileBool) post += '&while=' + whileBool;
	if (sortArray) post += '&sortArray=' + sortArray.join('*');
	if (sortDirection) post += '&sortDirection=' + sortDirection;
	if (header) post += '&header=' + header;
	if (orWhereArray) post += '&orWhereArray=' + orWhereArray.join('*');
	if (orValueArray) post += '&orValueArray=' + orValueArray.join('*');
	var req = request(uri,post);
	return req;	
}
function send(modul,modul2,vars)
{
	var uri = file + '/?action=send';
	var post = 'modul=' + modul;
	post += '&modul2=' + modul2;
	for (var i=0; i<vars.length; i++) post += '&var'+(i+1)+'='+vars[i];
	request(uri,post);	
}
function sendUpload(name)
{
	uri = file + '/?action=upload&name=' + name;
	request(uri);
}
function request(uri,post)
{
	if(!post) post = '';
	var index;
	
	for (var i=0; i<reqArray.length; i++) if (reqArray[i].readyState == 0) index = i;
	//for (var i=0; i<reqArray.length; i++) if (reqArray[i].readyState == 4 || reqArray[i].readyState == 0) index = i;	
	
	// when all objects in the array are busy create new
	if (index == null){
		reqArray.push(getXmlHttpRequestObject());
		index = reqArray.length-1;
	} 
	else reqArray[index] = getXmlHttpRequestObject(); // add cause of problems in IE
	
	reqArray[index].onreadystatechange = function() { answer(reqArray[index]); };
	reqArray[index].open('POST',uri,true);
	reqArray[index].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	reqArray[index].setRequestHeader("Content-length", post.length);
	reqArray[index].setRequestHeader("Connection", "close");
	reqArray[index].send(post);
}
