/**
 * Opens editing window.
 *
 * @return void
 */
function editingWindow(url, windowWidth, windowHeight) {

	var windowLeft = (screen.width - windowWidth) / 2;
	var windowTop = (screen.height - windowHeight) / 2 - 20;

	editingWindowRef = window.open(url, 'editingWindow', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, modal=yes, ' +
			'width=' + windowWidth + ', height=' + windowHeight + ', left=' + windowLeft + ', top=' + windowTop +', screenX=' + windowLeft + ', screenY=' + windowTop);

	if (window.focus) {
		editingWindowRef.focus()
	}
}

/**
 * Closes editing window.
 * 
 * @return void
 */
function closeWindow() {

	window.close();
}

function sendXmlHttpRequest(callback, method, url, content, headers) {

	var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false);
	if (!xmlHttp) {
		return false;
	}

	xmlHttp.open(method, url);
	xmlHttp.onreadystatechange = function() {
		callbackHandler(xmlHttp, callback);
	}

	if (headers) {
		for (var key in headers) {
			xmlHttp.setRequestHeader(key, headers[key]);
		}
	}

	xmlHttp.send(content);
	return true;
}

/**
 * XmlHttp request handler.
 *
 * @return void
 */
function callbackHandler(xmlHttp, callback) {

	switch (xmlHttp.readyState) {
		case 1:
			break;

		case 4:
			if (200 == xmlHttp.status) {
				callback(xmlHttp);
				xmlHttp = null;
			}
			else {
				alert("Internal error: error while retrieving the XML data: " + xmlHttp.statusText)
			}
			break;
	}
}

/**
 * Sends XmlHttp request to delete specified database record.
 *
 * @return void
 */
function editingDelete(url, target, recordID) {

	if (!confirm("Opravdu chcete smazat tento záznam?")) {
		return;
	}

	var content = "target=" + target + "&recordID=" + recordID;
	var headers = {"content-type":"application/x-www-form-urlencoded"};

	if (!sendXmlHttpRequest(editingDeleteHandler, "POST", url, content, headers)) {
		alert("Internal error: sendXmlHttpRequest failed!");
	}
}

/**
 * XmlHttp request handler for deleting database record.
 *
 * @return void
 */
function editingDeleteHandler(xmlHttp) {

	var response = xmlHttp.responseXML.getElementsByTagName("editingDelete")[0];
	if (null != response) {
		switch (getText(response, "exitCode")) {
			case "0":
				window.location.reload();
				break;
			case "1":
				alert("Nelze smazat tento záznam!");
				break;
			default:
				alert(getText(response, "message"));
				break;
		}
	}
	else {
		alert("Internal error: unable to get XML response!");
	}
}

/**
 * Gets text content from an element.
 *
 * @return String.
 */
function getText(parentElement, tagName) {

	try {
		return parentElement.getElementsByTagName(tagName)[0].firstChild.data;
	}
	catch (e) {
		return "";
	}
}
