var popupEditorCallback = null;
var popupEditorValidationCallback = null;

function popupEditorDo(prompt, text, callback, validationCallback, multiline) // callback(text, okOrCancel), validationCallback(text) { if (valid) return true; else return 'error message'; }
{
	if (popupEditorCallback) {
		popupEditorCallback(popupEditorText(), false);
	}
	document.getElementById('popup-editor-prompt').innerHTML = prompt;
	var editorField = document.getElementById('popup-editor-field');
	var editorTextarea = document.getElementById('popup-editor-textarea');
	var editControl = multiline ? editorTextarea : editorField;
	var otherControl = multiline ? editorField : editorTextarea;
	otherControl.style.display = 'none';
	editControl.style.display = 'block';
	editControl.value = text;
	popupEditorSetMessage(null);
	popupEditorCallback = callback;
	popupEditorValidationCallback = validationCallback;
	showPopupEditor(true);
	editControl.focus();
	editControl.select();
}


function showPopupEditor(show)
{
	escKeyHandler = show ? popupEditorHandleEscKey : null;
	document.getElementById('popup-editor').style.display = show ? 'block' : 'none';
}


function popupEditorHandleEscKey()
{
	endPopupEditor(false);
}


function popupEditorOK()
{
	validationResult = popupEditorValidationCallback ? popupEditorValidationCallback(popupEditorText()) : true;
	if (validationResult == true) {
		endPopupEditor(true);
	} else {
		popupEditorSetMessage(validationResult);
	}
}


function popupEditorText()
{
	var editorField = document.getElementById('popup-editor-field');
	var editorTextarea = document.getElementById('popup-editor-textarea');
	return editorField.style.display == 'none' ? editorTextarea.value : editorField.value;
}


function popupEditorSetMessage(msg)
{
	var messageNode = document.getElementById('popup-editor-message');
	messageNode.innerHTML = msg ? msg : '';
	messageNode.style.display = msg ? 'block' : 'none';
}


function endPopupEditor(okOrCancel)
{
	showPopupEditor(false);
	if (popupEditorCallback) {
		popupEditorCallback(popupEditorText(), okOrCancel);
		popupEditorCallback = null;
	}
}
