// ==============================================================
// telepark.cms

// This Software is copyright (c) 2007 by telepark, 
// Inh. Patrick Thomas, www.telepark.de. 
// All rights reserved. 

// You may not modify, extend, alter, reverse engineer or emulate
// the functionality, or create derivative works of the 
// Software in parts or it's entirety without the prior
// written consent of telepark.
// ==============================================================

var currentTime;
//var tmpID;
var locked = false;

// HTTPPost initialization
// ctype - content type
// encode - encoding
function HTTPPost(ctype, encode)	{
	if (ctype)
		this.ContentType = ctype;
	else
		this.ContentType = 'application/x-www-form-urlencoded';

	if (encode)
		this.Encoding = encode;
	else
		this.Encoding = 'UTF-8'; //ISO-8859-1

	this.httpRequest = null;
	
	// all browsers except IE6 and older
 	try {
 		this.httpRequest = new XMLHttpRequest();
 	}
 	// IE 6 and older
 	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 i = 0; i<xmlHttpVersions.length && !this.httpRequest; i++) {
 			try {
 				this.httpRequest = new ActiveXObject(xmlHttpVersions[i]);
 			}
 			catch(e) {
 			}
 		}
 	}
	
 	if (!this.httpRequest) {
 		alert("Unfortunately your browser doesn't support the required technology.");
 	}
 	
	this.postData = HTTPPost_postData;
	this.encodeValue = HTTPPost_encodeValue;
	this.showResponseText = HTTPPost_showResponseText;
	this.abort = HTTPPost_abort;
}


function HTTPPost_abort()	{
	this.httpRequest.abort();
}


// send AJAX POST request
// url - AJAX script url
// data - submited data
// callback - request processor
// async - false if sync method
function HTTPPost_postData(url, data, callback, async)	{
	var httpRequest = this.httpRequest;
	if (httpRequest)	{
		if (async == null)
			async = true;
		httpRequest.open('POST', url, async);
		if (async)	{
			httpRequest.onreadystatechange = function()	{
				callback(httpRequest);
			}
		}
		httpRequest.setRequestHeader('Content-Type',this.ContentType);
		httpRequest.setRequestHeader('Accept-Encoding',this.Encoding);
		//httpRequest.setRequestHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT');
		//httpRequest.setRequestHeader('Cache-Control','no-store, no-cache, must-revalidate');
		//httpRequest.setRequestHeader('Pragma','no-cache');
		var requestBody = null;
		if (typeof data != 'string')	{
			for (var argName in data)	{
				var encodedArgName = this.encodeValue(argName);
				var value = data[argName];
				if (typeof value == 'object')	{
					for (var i = 0; i < value.length; i++) {
						requestBody += encodedArgName + '=' + this.encodeValue(value[i]) + '&';
					}
				}else	{
					requestBody += encodedArgName + '=' + this.encodeValue(value) + '&';
				}
			}
			requestBody = requestBody.substring(0, requestBody.length - 1);
		}else	{
			requestBody = data;
		}
		httpRequest.send(requestBody);
		if (!async)	{
			callback(httpRequest);
		}
	}
}

// encode value
function HTTPPost_encodeValue(value)	{
	if (typeof encodeURIComponent != 'undefined')	{
		return encodeURIComponent(value);
	}else	{
		return escape(value);
	}
}

// alert response text
function HTTPPost_showResponseText() {
   alert(this.httpRequest.responseText);
}

// Usage examples
//postData('test.php', 'GOD=Kibo&devil=Xibo', showResponseText);
//postData('test.php', {'GOD': 'Kibo', 'devil': 'Xibo'},showResponseText);
//postData('test.php', {'riders': ['Lance', 'Jan', 'Erik'],'year': 2004}, showResponseText);


// get xml data
function getXMLData(p1)	{
	return (p1 && p1[0] && p1[0].firstChild)?p1[0].firstChild.data:'';
}

// ============
// UNLOCK PAGES
// ============

// unlock tree item
function unLockTreeitem(treeID,pre) {
	if (!pre || pre == "undefined") pre = "";
	if (treeID==-1) return;
	var hp = new HTTPPost();
	param = "treeID=" + treeID;
	hp.postData(pre + 'ajax/unLockFile.php', param, unLockFileResult, true);
}

// check lock tree items
function checkLockFiles(pre) {
	if (!pre || pre == "undefined") pre = "";
	var hp = new HTTPPost();
	hp.postData(pre + 'ajax/checkLockFiles.php', '', nofunction, false);
}


// unlock tree item result
function unLockFileResult(req) {
	if (req.readyState == 4)	{
		if (req.status == 200 && req.responseXML && req.responseXML.documentElement)	{
			var err = getXMLData(req.responseXML.documentElement.getElementsByTagName('error'));
			if (err != "") logError(err);
		}
	}
}

// log error
function logError(err,pre) {
	if (!pre || pre == "undefined") pre = "";
	var hp = new HTTPPost();
	var err = 'error=' + err;
	hp.postData(pre + 'ajax/logError.php', err, nofunction, true);
}

// no function
function nofunction(req) {
	if (req.readyState == 4)	{
		if (req.status == 200)	{
			//displaySystemMessage(req);
		}
	}
	return;
}

// write change timestamp
function writeChangestamp(pre){
	if (!pre || pre == "undefined") pre = "";
	var hp = new HTTPPost();
	hp.postData(pre + 'ajax/writeChangestamp.php', '', proceedWriteChangestamp, true);
}

// read change timestamp
function readChangestamp(pre){
	if (!pre || pre == "undefined") pre = "";
	var hp = new HTTPPost();
	hp.postData(pre + 'ajax/readChangestamp.php', '', proceedReadChangestamp, true);
}

// proceed action based on timestamp
function proceedReadChangestamp(req) {
	if (req.readyState == 4)	{
		if (req.status == 200 && req.responseXML && req.responseXML.documentElement)	{
			var timestamp = getXMLData(req.responseXML.documentElement.getElementsByTagName('timestamp'));
			var err = getXMLData(req.responseXML.documentElement.getElementsByTagName('error'));
			if (err != "") logError(err);
			if (timestamp != "" && timestamp != getCurrentTime()) {
				//alert("timestamp " + timestamp);
				setCurrentTime(timestamp);
				reloadTree(tree.getSelectedItemId());
			}
		}
	}
	status();
}

// proceed action based on timestamp
function proceedWriteChangestamp(req) {
	if (req.readyState == 4)	{
		if (req.status == 200 && req.responseXML && req.responseXML.documentElement)	{
			var timestamp = getXMLData(req.responseXML.documentElement.getElementsByTagName('timestamp'));
			setCurrentTime(timestamp);
		}
	}
}

// display system messages
function displaySystemMessage(message) {
	if (message != '' && message != 'undefined') {
		document.getElementById('innerMessage').innerHTML = message;
		document.getElementById('messageBox').style.display = 'block';
	}
}

// check if item is locked
function isLocked(treeItemId){
	var hp = new HTTPPost();
	hp.postData('ajax/checkLock.php', 'treeid=' + treeItemId, proceedIsLocked, false);
}

// proceed action based on lock
function proceedIsLocked(req) {
	if (req.readyState == 4)	{
		if (req.status == 200 && req.responseXML && req.responseXML.documentElement)	{
			var status = getXMLData(req.responseXML.documentElement.getElementsByTagName('status'));
			if (status == 1) {
				displaySystemMessage('Der aufgerufene Eintrag wird gerade von einer anderen Person bearbeitet. Bitte versuchen Sie es in einigen Minuten nochmals.');
				document.getElementById('locked').value = 1;
			} else {
				document.getElementById('locked').value = '';
			}
		}
	}
}

// get locked state
function getLockState() {
	if (document.getElementById('locked') && document.getElementById('locked').value == 1) {
		return true;
	}
	else return false;
}

// read unregistered companies
function readUnregisteredCompanies(pre){
	if (!pre || pre == "undefined") {
		pre = "";
	}
	var hp = new HTTPPost();
	hp.postData(pre + 'ajax/unconfirmedCompanies.php', '', proceedUnconfirmedCompanies, true);
}

// proceed action based on unregistered companies
function proceedUnconfirmedCompanies(req) {
	if (req.readyState == 4)	{
		if (req.status == 200 && req.responseXML && req.responseXML.documentElement)	{
			var unconfirmed = getXMLData(req.responseXML.documentElement.getElementsByTagName('unconfirmed'));
			var err = getXMLData(req.responseXML.documentElement.getElementsByTagName('error'));
			if (err != "") logError(err);
			if (unconfirmed != 0) {
				if (document.getElementById('anzUnconfirmed')) {
					document.getElementById('anzUnconfirmed').innerHTML = unconfirmed;
					document.getElementById('submessage').style.display = "block";
				} else if (parent.document.getElementById('anzUnconfirmed')) {
					parent.document.getElementById('anzUnconfirmed').innerHTML = unconfirmed;
					parent.document.getElementById('submessage').style.display = "block";
				} else if (opener.document.getElementById('anzUnconfirmed')) {
					opener.document.getElementById('anzUnconfirmed').innerHTML = unconfirmed;
					opener.document.getElementById('submessage').style.display = "block";
				}
			} else {
				if (document.getElementById('anzUnconfirmed')) {
					document.getElementById('anzUnconfirmed').innerHTML = 0;
					document.getElementById('submessage').style.display = "none";
				} else if (parent.document.getElementById('anzUnconfirmed')) {
					parent.document.getElementById('anzUnconfirmed').innerHTML = 0;
					parent.document.getElementById('submessage').style.display = "none";
				} else if (opener.document.getElementById('anzUnconfirmed')) {
					opener.document.getElementById('anzUnconfirmed').innerHTML = 0;
					opener.document.getElementById('submessage').style.display = "none";
				}
			}
		}
	}
}
