/***************************************************************************
*   edwiki 3.0
*   (C) 2002-2009 Daniel Wrana
*   http://www.tools.selbstlernarchitekturen.info
*   Distributed under the terms of the GNU General Public License v3 or later
****************************************************************************/

browser = navigator.userAgent.toLowerCase();
MSIE    = browser.indexOf("msie") != -1;
MSIE6   = browser.indexOf("msie 6") != -1;
GECKO = browser.indexOf("gecko") != -1;
WEBKIT  = browser.indexOf("khtml") != -1 || browser.indexOf("safari") != -1 || browser.indexOf("webkit") != -1;

ajaxAction = new Array();
ajaxRequestBase = new Array();
formTable = new Array();
formId = new Array();
formBaseLink = new Array();
formRefObj = new Array();

emptyFunction = function () {};

// base functions

function removeHTMLComments(html) {
  return html.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g,'');
}

function locationReload() {
  location.reload();
}

function gotoLocation(tempNewLocation) {
  newLocation = (typeof(tempNewLocation)=="undefined" ||  typeof(tempNewLocation)=="object") ? newLocation : tempNewLocation;
  location.href = newLocation;
}

function gotoWikiPage(wikiPage, addArguments, basePath, addAnchor) {
  if (typeof(addArguments)=="undefined") addArguments = "";
  if (typeof(addAnchor)=="undefined") addAnchor = "";
  if (typeof(basePath)=="undefined") basePath = urlBase;
  var addPath = "wiki.php?wiki=" + fixArguments(wikiPage, addArguments);
  gotoLocation(fixPath(basePath, addPath) + (addAnchor ? "#" + addAnchor : ""));
}

function gotoElement(table, id) {
  gotoLocation(toolBaseLink + "&table=" + encodeURIComponent(table) + "&id=" + id);
}

function fixPath(basePath, addPath) {
  if (basePath=="") return addPath;
  if (basePath.match(/\/$/) || addPath.match(/^\//)) return basePath.addPath;
  return basePath + "/" + addPath;
}

function fixArguments(base, add) {
  if (base.match(/\&$/) || add.match(/^\&/)) return base + add;
  if (add) return base + "&" + add;
  return base;
}

function addArgument(base, add) {
  if (base.match(/\?/)) return base + "&" + add;
                   else return base + "?" + add;
}

function addAttributes(basePath, attributes) {
  if (basePath.match(/\&$/) || basePath.match(/\?$/)) {
    return basePath + attributes;
  } else if (!basePath.match(/\?/)) {
    return basePath + "?" + attributes;
  } else {
    return basePath + "&" + attributes;
  }
}

function closeAndLink(transLink) {
  gotoLocation(urlBase + encodeURIComponent(transLink));
}

function getHtml(ajaxHtml) {
  splits = ajaxHtml.split("<script type='text/javascript'>");
  return splits[0];
}

function nodeContent(node, tagName) {
  return node.getElementsByTagName(tagName)[0].childNodes[0].nodeValue;
}

// use of window functions

var alertWindowId = 1;

function openFile(fileTmp, pathTmp) {
  file = fileTmp; path = pathTmp;
  openFileAjax = new ajax();
  openFileAjax.successCallback = openFileResponse;
  var data = "ajaxAction=testFileExistence&file=" + file + "&path=" + path;
  openFileAjax.request(data);
}

function openFileResponse() {
  result = openFileAjax.getSimpleResponse();
  if (result == "OK") {
    if (MSIE && !MSIE6) {
      alertModal(emptyFunction, getLang("lang_filedownloadmsie7"), 200);
    }
    if (MSIE6) {
      openPopupWindow('openfile' + file, 'openFile', 'file=' + file + '&path=' + path);
    } else {
        gotoLocation('create_files.php?file=' + file + '&path=' + path);
    }
  } else {
    alertModal(emptyFunction, result, 200);
    return false;
  }
}

function uploadFile(addArguments) {
  var filePath = document.getElementById('filePath').value;
  if (typeof(addArguments)=="undefined") addArguments = "";
  openPopupWindow('uploadfile', 'uploadFile', 'path=' + filePath + addArguments);
}

function helpWindow(content, top, left, width, height) {
  helpTop = top; helpLeft = left; helpWidth = width; helpHeight = height;
  openPopupWindow('help' + encodeURIComponent(content), 'help', 
        'content=' + encodeURIComponent(content) + '&top=' + helpTop + '&left='
        + helpLeft + '&width=' + helpWidth + '&height=' + helpHeight);
}

function helpLink(content) {
  var divCollection = document.getElementsByTagName("div");
  for (count in divCollection) {
    try {
      var div = divCollection[count];
      if (div.id.match(/^help/)) div.parentNode.removeChild(div);
    } catch (e) {}
  }
  openPopupWindow('help' + encodeURIComponent(content), 'help', 'content=' + encodeURIComponent(content)
                   + '&top='+ helpTop + '&left=' + helpLeft + '&width=' + helpWidth + '&height=' + helpHeight);
}

if (typeof(top.windowTopIndex)=="undefined") top.windowTopIndex = 4000;
var windowOpeningFlag = false;

function rearrangeWindow(id) {
  var top = document.getElementById(id).style.top;
  // todo: get the cursor position and set the window to an adequate position
}

function openPopupWindow(id, action, addArguments) {
  if (typeof(id)!="undefined") winId = id;
  if (typeof(action)!="undefined") winAction = action;
  if (typeof(addArguments)=="undefined") addArguments = "dummy=dummy";
  if (windowOpeningFlag == true) {
    windowOpenWaiter = window.setInterval("openPopupWindow();", 200);
    return false;
  } else {
    windowOpeningFlag = true;
    if (typeof(windowOpenWaiter)!="undefined") clearInterval(windowOpenWaiter);
  }
  winNode = top.document.getElementById(winId + "_main");
  iframeNode = top.document.getElementById(winId + "_iframe");
  if (winNode) winNode.parentNode.removeChild(winNode);
  if (iframeNode) iframeNode.parentNode.removeChild(iframeNode);
  top.windowTopIndex = top.windowTopIndex + 2;
  windowAjax = new ajax();
  windowAjax.successCallback = writePopup;
  var data = 'ajaxAction=' + winAction + '&winId=' + winId + '&' + addArguments 
              + '&zindex=' + top.windowTopIndex + '&scrollTop=' + getScrollPosY();
  windowAjax.requestWindow(data);
}

function writePopup() {
  ajaxHtml = windowAjax.getTextResponse();
  if (ajaxHtml=="noAccess") pleaseLogin();
  var newWindow = document.createElement("div");
  newWindow.innerHTML = getHtml(ajaxHtml);
  topopo = top.document.getElementsByTagName('body')[0];
  try {
    topopo.appendChild(newWindow);
  } catch (e) {}
  setJavascript(ajaxHtml);
  setCss(ajaxHtml);
  windowOpeningFlag = false;
}

function setCss(ajaxHtml) {
  var head = document.getElementsByTagName("head")[0];
  splits = ajaxHtml.split("<style type=\"text/css\">");
  if (!splits[1]) return;
  splits = splits[1].split("</style>");
  cssScript = document.createElement("style");
  cssScript.setAttribute('type', 'text/css');
  cssScript.text = splits[0];
  head.appendChild(cssScript);
}

function setJavascript(ajaxHtml) {
  var head = document.getElementsByTagName("head")[0];
  splits = ajaxHtml.split("<script type='text/javascript'>");
  if (!splits[1]) return;
  splits = splits[1].split("</script>");
  javoScript = document.createElement("script");
  javoScript.setAttribute('type', 'text/javascript');
  javoScript.text = splits[0];
  head.appendChild(javoScript);
}

var loadedFiles = new Array();

function loadJavascriptFile(url) {
  for (i = 0; i < loadedFiles.length; i++) if (loadedFiles[i] == url) return;
  var head = document.getElementsByTagName("head")[0];
  var el = document.createElement("script");
  el.src = url;
  el.type="text/javascript";
  head.appendChild(el);
  loadedFiles[loadedFiles.length] = url;
}

function loadStylesheetFile(url) {
  for (i = 0; i < loadedFiles.length; i++) if (loadedFiles[i] == url) return;
  var head = document.getElementsByTagName("head")[0];
  var el = document.createElement("link");
  el.href = url;
  el.rel  = "stylesheet";
  el.type = "text/css";
  head.appendChild(el);
  loadedFiles[loadedFiles.length] = url;
}

function getFileType(filetype) {
  gotoLocation(urlBase + "create_images.php?filetype=" + filetype);
}

// formular functions

function toggle(keyRang, mode, targetValue) { 
  // first arg is the number of the split of the id
  var imgCollection = document.getElementsByTagName("img");
  for (count in imgCollection) {
    var image = imgCollection[count];
    if (typeof(image.id)=="undefined" || image.id == "") continue;
    imgIdArray = image.id.split("_");
    if (imgIdArray[keyRang] != currIdArray[keyRang]) continue;
    var val = typeof(image.parentNode.val)=="undefined" ? image.parentNode.value 
                                                        : image.parentNode.val;
    if (val==targetValue) {
      image.src = urlIcons + (mode=="boxes" ? "box" : "round") + "_checked.gif";
    } else {
      image.src = urlIcons + (mode=="boxes" ? "box" : "round")+ "_unchecked.gif";
    }
  }
}

function ajaxSelectChange(elTemp, fieldTemp, idTemp, translation) {
  el = elTemp; field = fieldTemp; id = idTemp;
  if (typeof(translation)=="undefined") translation = getLang('lang_setnewentry');
  if (el.value=="pleaseselect") {
    return false;
  } else if (el.value=="newentry") {
    promptModal(addSelectEntry, translation, '');
  } else {
    selectChangeOption = el.value;
    ajaxFormChange(el, "select", "", field, id);
  }
}

function addSelectEntry(valueTemp) {
  if (valueTemp == null || valueTemp == "") return false;
  addSelectOption(el.id, valueTemp, valueTemp);
  selectChangeOption = valueTemp;
  ajaxFormChange(el, "select", "", field, id);
}

function ajaxFormChange(elTemp, mode, languageTemp, fieldName, targetId) {
  el = elTemp;
  formLanguage = (typeof(languageTemp)=="undefined") ? "" : languageTemp;
  refObj = (typeof(formRefObj[el.form.name]) == "undefined") 
              ? "" : formRefObj[el.form.name];
  formAjax = new ajax();
  if (mode=='radio') {
    formAjax.successCallback = processResponseRadio;
    field = el.name;
    specOption = storeValue = el.id.split("_")[1];
  } else if (mode=='check') {
    formAjax.successCallback = processResponseCheck;
    fieldSplit = el.name.match(/\[(.*)\]$/);
    specOption = field = (fieldSplit==null) ? el.name : fieldSplit[1];
    if (typeof(el.val)!="undefined") {
      storeValue = el.val = (el.val=='TRUE' ? 'FALSE' : 'TRUE');
    } else {
      storeValue = el.value = (el.value=='TRUE' ? 'FALSE' : 'TRUE');
    }
  } else if (mode=='checklist') {
    formAjax.successCallback = processResponseCheckList;
    valueArray = el.name.match(/\[(.*)\]$/);
    specOption = storeValue = (valueArray==null) ? el.name : valueArray[1];
    if (typeof(el.val)!="undefined") {
      el.val = (el.val=='TRUE' ? 'FALSE' : 'TRUE');
    } else {
      el.value = (el.value=='TRUE' ? 'FALSE' : 'TRUE');
    }
  } else if (mode=='select') {
    formAjax.successCallback = processResponseSelect;
    fieldSplit = el.name.match(/\[(.*)\]$/);
    field = (fieldSplit==null) ? el.name : fieldSplit[1];
    if (typeof(selectChangeOption)!="undefined") {
      storeValue = specOption = selectChangeOption;
    } else {
      storeValue = specOption = el.value;
    }
  } else {
    formAjax.successCallback = processResponse;
    fieldSplit= el.name.match(/\[(.*)\]$/);
    field = (fieldSplit==null) ? el.name : fieldSplit[1];
    if (field=='passKlar') {
      var passKlar = document.getElementById('pass').value;
      storeValue = (passKlar=='') ? '' : MD5(passKlar);
      field = 'pass';
    } else {
      storeValue = el.value;
      el.value = 'Updating...';
    }
  }
  field = (typeof(fieldName)=="undefined" || fieldName=="") ? field : fieldName;
  id = (typeof(targetId)=="undefined" || targetId=="") ? formId[el.form.name] : targetId;
  var data = "ajaxAction=" + ajaxAction[el.form.name]
            + ajaxRequestBase[el.form.name]
            + "&id=" + id + "&mode=" + mode 
            + "&field=" + field + "&language=" + formLanguage
            + "&storeValue=" + encodeURIComponent(storeValue)
            + ((refObj != "") ? "&refObj=" + refObj : "");
  formAjax.request(data);
}

function processResponse() {
  result = formAjax.getSimpleResponse();
  addData = formAjax.getComplexResponse();
  if (!result && result != "") return; 
  if (result=='doubleEntry') {
    alertModal(emptyFunction, getLang("lang_doubleentry"));
    el.value = "";
  } else if (result=='doubleTitle') {
    prevId = nodeContent(addData, 'id');
    confirmModal(doubleTitleProcess, nodeContent(addData, 'message') + "<br><br>" + nodeContent(addData, 'biblio'));
  } else if (result=='notallowedValue') {
    alertModal(emptyFunction, getLang("lang_notallowedvalue"));
    el.value = "";
  } else if (field!='passKlar') {
    el.value = (result || result == "") ? result : storeValue;
  } else {
    el.value = storeValue;
  }
  if (typeof formChangePlugin != "undefined") formChangePlugin(el.form.name);
}

function doubleTitleProcess(value) {
  if (value==false) {
    el.value = storeValue;
  } else {
    delId = id;
    id = prevId;
    doubTitAjax = new ajax();
    doubTitAjax.successCallback = toolShowId;
    var data = "ajaxAction=deleteElement&table=" + encodeURIComponent(table) + "&id=" + delId + "&refObj=rhizomObj";
    doubTitAjax.request(data);
  }
}

function toolShowList() {
  gotoLocation(addArgument(urlBasePVAR, actionBasePVAR) + "showList");
}

function toolShowId() {
  gotoLocation(addArgument(urlBasePVAR, actionBasePVAR) + "show&id=" + id);
}

function processResponseSelect() {
  if (!(result = formAjax.getSimpleResponse())) return;
  setPreSelection(el.id, result);
  if (typeof formChangePlugin != "undefined") formChangePlugin(el.form.name);
}

function processResponseCheckList() {
  currIdArray = el.id.split("_");
  toggle(1, 'boxes', "TRUE");
  if (typeof formChangePlugin != "undefined") formChangePlugin(el.form.name);
}

function processResponseCheck() {
  currIdArray = el.id.split("_");
  document.getElementById(currIdArray[0] + "_hiddenValue").value = storeValue;
  toggle(0, 'boxes', "TRUE"); 
  if (typeof formChangePlugin != "undefined") formChangePlugin(el.form.name);
}

function processResponseRadio() {
  currIdArray = el.id.split("_");
  document.getElementById(currIdArray[0] + "_hiddenValue").value = currIdArray[1];
  toggle(0, 'rounds', currIdArray[1]); 
  if (typeof formChangePlugin != "undefined") formChangePlugin(el.form.name);
}

function changeFieldFile(formularName) {
  document.getElementById(formularName + 'Action').value = "edit";
  document.getElementById(formularName).submit();
}

function formChange(elTemp, mode) {
  el = elTemp;
  if (mode=='radio') {
    if (typeof(el.val)!="undefined") {
      specOption = storeValue = el.val;
    } else {
      specOption = storeValue = el.value;
    }
    currIdArray = el.id.split("_");
    document.getElementById(currIdArray[0] + "_hiddenValue").value = storeValue;
    toggle(0, 'rounds', currIdArray[1]); 
  } else if (mode=='check') {
    if (typeof(el.val)!="undefined") {
      specOption = storeValue = el.val = (el.val=='TRUE' ? 'FALSE' : 'TRUE');
    } else {
      specOption = storeValue = el.value = (el.value=='TRUE' ? 'FALSE' : 'TRUE');
    }
    currIdArray = el.id.split("_");
    document.getElementById(currIdArray[0] + "_hiddenValue").value = storeValue;
    toggle(0, 'boxes', storeValue); 
  }
}

function doSubmitForm(el, crypt) {
  inputs = document.getElementsByTagName('input');
  for(var i = 0; i < inputs.length; i++) {
    if (inputs[i].type=='password') {
      var passKlar = inputs[i].value;
      document.getElementById(inputs[i].id + 'Crypt').value = (crypt && crypt=="md5") ? MD5(passKlar) : passKlar;
      inputs[i].value = '';
    }
    if (inputs[i].type=='hidden' && inputs[i].id.match(/^(.*)ItemList$/)) {
      var itemListName = inputs[i].id.match(/^(.*)ItemList$/);
      inputs[i].value = document.getElementById('span' + itemListName[1]).innerHTML;
    }
  }
  var value = (typeof el.val == 'undefined') ? el.value : el.val;
  document.getElementById(el.form.name + "Action").value = value;
  document.getElementById(el.form.name).submit();
}

function check4Return(formEl, evt) {
  var obj = evt.target || evt.srcElement;
  if (obj.type == "submit") return true;
  if (obj.type != "textarea" && obj.type != "button" && evt.keyCode == 13 ) {
    if (evt.preventDefault) evt.preventDefault()
    else evt.returnValue = false;
    var myElements = formEl.elements,
    newIndex = 0;
    for (var i = 0; i < myElements.length; i++ ) {
      if ( myElements[ i ] != obj ) continue;
      for (var j = i + 1; j < myElements.length; j++ ) {
        if ("input,textarea,submit,button".indexOf( myElements[ j ].type ) != -1 ) {
          newIndex = j;
          break;
        }
      }
      try { myElements[newIndex].focus(); } catch (e) {}
    }
  };
  return true;
}

function simpleChangeSelect(el, baseLink) {
  gotoLocation(baseLink + el.value);
}

function simpleButtonInput(inputId, baseLink) {
  var inputValue = document.getElementById(inputId).value;
  gotoLocation(baseLink + inputValue);
}

function markChecks(mode) {
  var rowsChecks = document.getElementsByName("markArray[]");
  for (var i = 0; i < rowsChecks.length; i++) {
    if (mode=="all") {
      rowsChecks[i].checked = true;
    } else {
      rowsChecks[i].checked = (rowsChecks[i].checked==true) ? false : true;
    }
  }
}

function focusElement(id) {
  try {
    document.getElementById(id).focus();
  } catch (e) {}
}

function toggleInsertPolicy() {
  val = (typeof(el.val)!="undefined") ? el.val : el.value;
  if (val=="FALSE" && specOption=="page") {
    setDisplayMode("none", "toolinsertfieldset", "", "noParent");
  } else if (val=="TRUE" && specOption=="page") {
    setDisplayMode("block", "toolinsertfieldset", "", "noParent");
  }
} 

// functions to operate on itemlists

function iteminputChange(el, storeField, listItemField, prefix, table, id) {
  processListItemAction("addListItem", el.value, storeField, listItemField, prefix, table, id);
  el.value = "";
}

function itemlistChange(el, storeField, listItemField, prefix, table, id, allModeTemp) {
  itemlistAddEl = el; storeFieldK = storeField; listItemFieldK = listItemField;
  prefixK = prefix; tableK = table; idK = id; allMode = allModeTemp;
  if (el.value == "newlistitem") {
    promptModal(responseItemList, getLang('lang_setnewlistitem'), '');
  } else if (el.value == "pleaseselect") {
    return;
  } else {
    responseItemList(el.value)
  }
}

function responseItemList(storeValue) {
  if (storeValue == null || storeValue == "") return false;
  if (storeValue.match(/[\|\;\,\:\#\'\"\}\{\&\%\$\~\<\>\=\\\/]/)) {
    alertModal(emptyFunction, getLang('lang_please_nospecial'));
  } else {
    processListItemAction("addListItem", storeValue, storeFieldK, listItemFieldK, prefixK, tableK, idK);
  }
  itemlistAddEl.value = "pleaseselect";
}

function listitemDelete(el, delValue, storeField, listItemField, prefix, table, id, allModeTemp) {
  allMode = allModeTemp;
  processListItemAction("deleteListItem", delValue, storeField, listItemField, prefix, table, id);
}

function processListItemAction(listItemAction, storeValue, storeField, listItemField, prefix, table, id) {
  formAjax = new ajax();
  formAjax.successCallback = processResponseItemlist;
  itemlistSpanEl = document.getElementById("span" + listItemField);
  var data = "ajaxAction=" + listItemAction
      + "&field=" + encodeURIComponent(storeField) 
      + "&listItemField=" + encodeURIComponent(listItemField)
      + "&prefix=" + prefix + "&table=" + encodeURIComponent(table) + "&id=" + id 
      + "&storeValue=" + encodeURIComponent(storeValue);
  if (typeof(allMode)!="undefined" && allMode == "TRUE") {
    data += "&allMode=TRUE";
  }
  formAjax.request(data);
}

function processResponseItemlist() {
  result = formAjax.getSimpleResponse();
  itemlistSpanEl.innerHTML = result;
}

// functions for searching and selecting

function itemListSearch(fieldname, term) {
  searchAction = "tagSearch";
  searchField = fieldname; 
  searchTerm = term;
  searchUrl = (typeof(urlBasePVAR)!="undefined" && urlBasePVAR!="") ? urlBasePVAR : urlBase + "wiki.php";
  searchActionBase = (typeof(actionBasePVAR)!="undefined" && actionBasePVAR!="") ? actionBasePVAR : "searchAction=";
  searchTable = (typeof(searchTablePVAR)!="undefined" && searchTablePVAR!="") ? searchTablePVAR : "all";
  refObj = (typeof(refObjPVAR)!="undefined" && refObjPVAR!="") ? refObjPVAR : "pageObj";
  ajaxSearchBase();
}

function ajaxSearchLink(tableTmp, fieldnameTmp, termTmp, actionTmp,
                        searchUrlTmp, actionBaseTmp, refObjTmp) {
  searchTable = tableTmp; searchField = fieldnameTmp; searchTerm = termTmp;
  refObj = (typeof(refObjTmp)!="undefined" && refObjTmp != "") ? refObjTmp : "pageObj";
  searchUrl = (typeof(searchUrlTmp)!="undefined" && searchUrlTmp != "") ? searchUrlTmp : urlBase + "wiki.php";
  searchActionBase = (typeof(actionBaseTmp)!="undefined" && actionBaseTmp != "") ? actionBaseTmp : "searchAction=";
  searchAction = (typeof(actionTmp)!="undefined") ? actionTmp : "simpleSearch";
  ajaxSearchBase();
}

function ajaxSearch(actionTmp, refObjTmp, searchUrlTmp, actionBaseTmp) {
  refObj = (typeof(refObjTmp)!="undefined" && refObjTmp != "") ? refObjTmp : "pageObj";
  searchUrl = (typeof(searchUrlTmp) == "undefined") ? urlBase + "wiki.php" : searchUrlTmp;
  searchActionBase = (typeof(actionBaseTmp) == "undefined") ? "searchAction=" : actionBaseTmp;
  searchAction = (typeof(actionTmp)!="undefined") ? actionTmp : "simpleSearch";
  try { searchTable = document.getElementById(searchAction + 'Table').value;
  } catch (e) { 
    try { searchTable = document.getElementById('searchTable').value;
    } catch (e) { searchTable = "" }
  }
  try { searchField = document.getElementById(searchAction + 'Field').value;
  } catch (e) { 
    try { searchField = document.getElementById('searchField').value;
    } catch (e) { searchField = "" }
  }
  try { searchTerm = document.getElementById(searchAction + 'Term').value;
  } catch (e) {
    try { searchField = document.getElementById('searchTerm').value;
    } catch (e) { searchTerm = "" }
  }
  ajaxSearchBase();
}

function ajaxSearchBase() {
  searchAjax = new ajax();
  searchAjax.successCallback = searchResponse;
  var data = "ajaxAction=" + searchAction 
               + "&searchTable=" + encodeURIComponent(searchTable)
               + "&searchField=" + encodeURIComponent(searchField)
               + "&searchTerm=" + encodeURIComponent(searchTerm)
               + "&refObj=" + refObj;
  searchAjax.request(data);
}

function ajaxChangeSearchField(el, searchUrlTmp, actionBaseTmp) {
  searchUrl = (typeof(searchUrlTmp) == "undefined") 
                 ? urlBase + "wiki.php" : searchUrlTmp;
  searchActionBase = (typeof(actionBaseTmp) == "undefined") 
                 ? "searchAction=" : actionBaseTmp;
  data = addArgument(searchUrl, searchActionBase) + "simpleSearch"
            + "&searchField=" + encodeURIComponent(el.value);
  gotoLocation(data);
}

function searchResponse() {
  result = searchAjax.getSimpleResponse();
  if (result=="syntaxerror") {
    alertModal(emptyFunction, getLang("lang_sqlsyntaxerror"));
  } else if (result=="unknownColumn") {
    alertModal(emptyFunction, getLang("lang_sqlunknowncolumn"));
  } else {
    data = addArgument(searchUrl, searchActionBase) + searchAction
            + "&searchTable=" + encodeURIComponent(searchTable)
            + "&searchField=" + encodeURIComponent(searchField)
            + "&searchTerm=" + encodeURIComponent(searchTerm);
    gotoLocation(data);
  }
}

// functions to set the ranked element of a collection

function setRank(actionTmp, formNameTmp) {
  elAction = (typeof(actionTmp) == "undefined") ? "" : actionTmp;
  formName = (typeof(formNameTmp) == "undefined") ? "" : formNameTmp;
  if (elAction=='selectRank') {
    promptModal(setRankProcess, getLang('lang_setnewrank'), '');
  } else {
    setRankProcess();
  }
}

function setRankProcess(rank) {
  var rank = (typeof(rank) == "undefined") ? "" : rank;
  if (rank.match(/[a-z\|\;\,\.\:\#\'\"\*\+\}\]\[\{\&\%\$\§\!\~\<\>\=\?\\\/]/)) {
    alertModal(emptyFunction, getLang('lang_please_nospecial'));
  } else {
    var refObj = (typeof(formRefObj[formName])=="undefined") ? refObj : formRefObj[formName];
    var table = (typeof(formTable[formName])=="undefined") ? "" : formTable[formName];
    setRankAjax = new ajax();
    setRankAjax.successCallback = setRankResponse;
    var data = "ajaxAction=setElement&action=" + elAction + "&refObj=" + refObj 
             + "&rank=" + rank + "&gridName=" + formName + "&table=" + table;
    setRankAjax.request(data);
  }
}

function setRankResponse() {
  var result = setRankAjax.getComplexResponse();
  var baseLink = (typeof(formBaseLink[formName])=="undefined") ? toolBaseLink : formBaseLink[formName];
  var nextTable = nodeContent(result, 'table');
  if (nextTable!="none") {
    data = "&table=" + encodeURIComponent(nextTable) + "&id=" + nodeContent(result, 'id');
  }
  gotoLocation(baseLink + data);
}

// general functions to manage applets

function createAppletHead(appletName) {
  return "<span class='appletHead' onclick=\"hideApplet('" + appletName + "')\">X</span>";
}

function createAppletEntry(command, value, transCommand) {
  if (typeof(transCommand)=="undefined") transCommand = getLang("lang_" + command); 
  return "<div class='appletListEntry' "
       + " onclick=\"tagCloudMenuEntry('" + command + "', '" + value + "'); \">"
       + "<span class='appletListText'>" + transCommand + "</span></div>";
}

function appletDirectPosition(listEl, listWidth) {
  listEl.style.top = getScrollPosY() + clickEventY + "px";
  x = getScrollPosX() + clickEventX - (listWidth/2); 
  listEl.style.left = x + "px";
  listEl.style.width = listWidth + "px";
  listEl.style.display = "block";
}

function appletPosition(fireEl, listEl, listWidth) {
  elTop = fireEl.style.top.replace(/px/, '');
  elLeft = fireEl.style.left.replace(/px/, '');
  etop = String(Number(elTop) + 2) + "px";
  eleft = String(Number(elLeft) + 6) + "px";
  listEl.style.top = etop;
  listEl.style.left = eleft;
  listEl.style.width = listWidth;
  listEl.style.display = "block";
}

function hideApplet(appletId) {
  document.getElementById(appletId).style.display = "none";
}

// grid - functions

function doAction(newLocationTemp, confirmText) {
  newLocation = newLocationTemp;
  if (!confirmText) {
    actionProcess();
  } else {
    confirmModal(actionProcess, confirmText, 200);
  }
}

function actionProcess(result) {
  if (result==false) return false;
  gotoLocation();
}

function gridConfig(gridName, baseLinkTemp, configAction) {
  newLocation = baseLinkTemp;
  data = 'gridName=' + gridName + '&configAction=' + configAction;
  openPopupWindow('gridConfig', 'gridConfig', data);
}

function gridProcess() {
  try {
    newLocation += "&gridOrder=" + document.getElementById('gridOrder').value;
  } catch (e) {}
  try {
    newLocation += "&rowLimit=" + document.getElementById('rowLimit').value;
  } catch (e) {}
  try {
    newLocation += "&activeColumns=" + document.getElementById('activeColumns').value;
  } catch (e) {}
  gotoLocation();
}

function gridImageDelete(name, baseLinkTemp) {
  fileName = name;
  baseLink = baseLinkTemp;
  confirmModal(gridFileDeleteConfirmed, getLang('lang_confirmimagedelete'), 160);
}

function gridFileDelete(obj, col, name, baseLinkTemp) {
  fileName = name;
  baseLink = baseLinkTemp;
  confirmModal(gridFileDeleteConfirmed, getLang('lang_confirmfiledelete'), 160);
}

function gridFileDeleteConfirmed(result) {
  if (result==false) return false;
  newLocation = addAttributes(baseLink, "done=fileDeleted");
  gridfiledeleteAjax = new ajax();
  gridfiledeleteAjax.successCallback = gotoLocation;
  var filePath = document.getElementById('filePath').value;
  var data = "ajaxAction=deleteFile&path=" + encodeURIComponent(filePath) 
                                + "&name=" + encodeURIComponent(fileName);
  gridfiledeleteAjax.request(data);
}

function fileDelete(path, fileName, target) {
  newLocation = ((target !="") ? target : location.search) + "&done=fileDeleted";
  filedeleteAjax = new ajax();
  filedeleteAjax.successCallback = gotoLocation;
  var data = "ajaxAction=deleteFile&path=" + encodeURIComponent(path) + "&name=" + encodeURIComponent(fileName);
  filedeleteAjax.request(data);
}

function gridFileShow(el, col, name) {
  var filePath = document.getElementById('filePath').value;
  openFile(name, filePath);
}

function gridFileDisplayImage(el, col, name) {
  var filePath = document.getElementById('filePath').value;
  openPopupWindow('displayImage', 'displayImage', 'path=' + filePath + '&name=' + name);
}

function toolConfig(toolName, baseLinkTemp, pageName, windowHeight) {
  newLocation = baseLinkTemp;
  data = 'toolName=' + toolName + '&baseLink=' + baseLinkTemp + '&pageName=' + pageName + '&windowHeight=' + windowHeight;
  openPopupWindow('toolConfig', 'toolConfig', data);
}

function showElementFromTrash(el, action, id) {
  alertModal(emptyFunction, "showElementFromTrash" + "text" + id);
}

function rename(target, text, oldName) {
  newLocation = target + "&newName=" + encodeURIComponent(newName);
  promptModal(renameProcess, text, oldName);
}

function renameProcess(newName) {
  if (newName) gotoLocation();
}

function onCancel() {
  self.close();
  return false;
};

function messageForm(name, prefix, table, elementId, addArguments) {
  if (typeof(addArguments)=="undefined") addArguments = "";
  openPopupWindow('messageForm', 'messageForm', 'prefix=' + prefix + '&table=' + table + '&id=' + elementId + addArguments);
}

function sendMessageForm(targetTmp) {
  newLocation = (typeof(targetTmp)!="undefined") ? targetTmp : "";
  sendMessageFormAjax = new ajax();
  sendMessageFormAjax.successCallback = sendMessageResponse;
  messageId = document.getElementById("messageId").value;
  var data = "ajaxAction=editField&table=messages&field=messageBody&id=" + messageId
                               + "&storeValue=" + encodeURIComponent(document.getElementById("messageBody").value);
  sendMessageFormAjax.request(data);
}

function sendMessageResponse() {
  sendMessage(messageId, newLocation);
}

function sendMessage(idTmp, targetTmp) {
  newLocation = (typeof(targetTmp)!="undefined") ? targetTmp : "";
  try {
    closeWin('messageForm');
  } catch(e) {}
  openPopupWindow('sendMessage', 'sendMessage', 'id=' + idTmp + '&target=' + newLocation);
}

function buttonTooltip(buttonEl, tooltipText, tooltipAlign,
         tooltipWidth, tooltipOffset) {
  if (tooltipText=="") return;
  tooltipDiv = document.createElement("div");
  addClass(tooltipDiv, 'tooltip');
  if (tooltipAlign == "right") {
    tooltipDiv.style.marginLeft = MSIE ? "-210px" : "-160px";
  } else {
    tooltipDiv.style.marginLeft = MSIE ? "-40px" : "4px";
  }
  tooltipDiv.name = "tooltipDiv";
  if (typeof tooltipWidth != "undefined") tooltipDiv.style.width = tooltipWidth + "px";
  if (typeof tooltipOffset != "undefined") tooltipDiv.style.marginTop = tooltipOffset + "px";
  tooltipDiv.innerHTML = tooltipText;
  buttonEl.appendChild(tooltipDiv);
}

function previewTooltip(el, table, id) {
  linkEl = el;
  previewTooltipAjax = new ajax();
  previewTooltipAjax.successCallback = previewTooltipResponse;
  var data = "ajaxAction=getPreviewTooltip&table=" + encodeURIComponent(table) + "&id=" + id + "&refObj=rhizomObj";
  previewTooltipAjax.request(data);
}

function previewTooltipResponse() {
  if (!(result = previewTooltipAjax.getSimpleResponse())) return;
  if (result=="") return;
  var tooltipDiv = document.createElement("div");
  addClass(tooltipDiv, 'tooltip');
  tooltipDiv.style.marginLeft = MSIE ? "-40px" : "4px";
  tooltipDiv.style.width = "400px";
  tooltipDiv.name = "tooltipDiv";
  tooltipDiv.innerHTML = result;
//  linkEl.appendChild(tooltipDiv);
}

function removeTooltip(buttonEl) {
  var divs = document.getElementsByTagName('div');
  for (var i = 0; i < divs.length; i++) {
    try {
      if (divs[i].name.match(/tooltipDiv/)) divs[i].style.display = "none";
    } catch (e) {}
  }
}

langStrings = new Array();

function addToLang(prefix, ar) {
  for (var key in ar) {
     if (typeof(ar[key]) == 'function') continue;
     langStrings[(key.indexOf('lang_') == -1 ? 'lang_' : '')
        + (prefix != '' ? (prefix + "_") : '') + key] = ar[key];
  }
}

function getLang(name, default_value) {
  return (typeof(langStrings[name]) == "undefined") ? default_value : langStrings[name];
}

function setDisplayMode(mode, idString, base, noParent) {
  if (typeof(base)=="undefined") base = "";
  if (typeof(noParent)=="undefined") noParent = "";
  if (idString=="") return;
  idCollection = idString.split(",");
  for (count in idCollection) {
    id = base + idCollection[count];
    var el = document.getElementById(id);
    try {
      if (el.tagName!="DIV" && noParent=="") {
        if (el.parentNode.tagName=="SPAN") {
            el.parentNode.parentNode.parentNode.style.display = mode;
        } else {
          el.parentNode.style.display = mode;
        }
      } else {
        el.style.display = mode;
      }
   } catch (e) { alert("Element not Found: " + id); }
  }
}

function toggleDisplayMode(base, state1, ids1, state2, ids2, state3, ids3, state4, ids4) {
  if (typeof(state2)=="undefined") state2 = "";
  if (typeof(state3)=="undefined") state3 = "";
  if (typeof(state4)=="undefined") state4 = "";
  setDisplayMode("none", ids1, base);
  if (state2) setDisplayMode("none", ids2, base);
  if (state3) setDisplayMode("none", ids3, base)
  if (state4) setDisplayMode("none", ids4, base)
  if (specOption==state1) {
    setDisplayMode("block", ids1, base);
  } else if (state2 && specOption==state2) {
    setDisplayMode("block", ids2, base);
  } else if (state3 && specOption==state3) {
    setDisplayMode("block", ids3, base);
  } else if (state4 && specOption==state4) {
    setDisplayMode("block", ids4, base);
  }
}

function activateCard(el, showValue, navName) {
  setDisplayMode ("none", navName, "stdTab_", "parent");
  if (el.value==showValue) {
    setDisplayMode ("inline", navName, "stdTab_", "parent");
  }
}

function changeTab(idBase, activeTab, activeTabClass, formNameTemp) {
  formName = formNameTemp;
  var linkCollection = document.getElementsByTagName("a");
  for (count in linkCollection) {
    var linkEl = linkCollection[count];
    if (typeof(linkEl.id) != "undefined" && linkEl.id.indexOf(idBase + "Tab")!="-1") {
      removeClass(linkEl, activeTabClass);
    }
  }
  var divCollection = document.getElementsByTagName("div");
  for (count in divCollection) {
    var divEl = divCollection[count];
    if (typeof(divEl.id) != "undefined" && divEl.id.indexOf(idBase + "Card")!="-1") {
      divEl.style.display = 'none';
    }
  }
  document.getElementById(idBase + "Card_" + activeTab).style.display = 'block';
  addClass(document.getElementById(idBase + "Tab_" + activeTab), activeTabClass);
  activeLangCard = activeTab;

  changeCardAjax = new ajax();
  changeCardAjax.successCallback = emptyFunction;
  var data = "ajaxAction=changeCard&formName=" + formName + "&tab=" + activeTab;
  changeCardAjax.request(data);

  if (typeof(changeCardPlugin) != "undefined") changeCardPlugin(activeTab);
}

function changeCardPlugin(activeCard) {
  if (activeCard=="related") {
    fillBacklinksAjax = new ajax();
    fillBacklinksAjax.successCallback = reloadedBacklinks;
    var data = "ajaxAction=fillBacklinks&refObj=rhizomObj";
    fillBacklinksAjax.request(data);
    fillRelationsAjax = new ajax();
    fillRelationsAjax.successCallback = reloadedRelations;
    var data = "ajaxAction=fillRelations&refObj=rhizomObj";
    fillRelationsAjax.request(data);
    var el = document.getElementById('parenPageDiv');
    if (el!=null) {
      fillParentDocsAjax = new ajax();
      fillParentDocsAjax.successCallback = reloadedParentDocs;
      var data = "ajaxAction=fillParentDocs&refObj=rhizomObj";
      fillParentDocsAjax.request(data);
    }
  }
}

// close and open editors

mceCancelCallback = function () {};
mceSaveCallback = function () {};
mceAlertSaveCallback = function () {};

function openDivEditor(idTemp, elementTableTmp, elementIdTmp, languageTemp, buttonModeTemp, heightTemp, elementPrefixTmp) {
  divLanguage = (typeof(languageTemp) == "undefined") ? "" : languageTemp;
  mceSaveCallback = function (value) { saveElementContent (value); };
  mceCancelCallback = function (value) { gotoTableId(); };
  mceAlertSaveCallback = function (value) { alertContentSave (); };
  elementTable = elementTableTmp;
  elementId = elementIdTmp;
  elementPrefix = elementPrefixTmp;
  editorId = idTemp;
  editorHeight = heightTemp;
  editorButtonMode = buttonModeTemp;
  getContentAjax = new ajax();
  getContentAjax.successCallback = openDivEditorResponse;
  var data = "ajaxAction=getEditableContent&language=" + divLanguage
               + "&prefix=" + encodeURIComponent(elementPrefix) 
               + "&table=" + encodeURIComponent(elementTable) + "&id=" + elementId;
  getContentAjax.request(data);
}

function openDivEditorResponse() {
  var result = getContentAjax.getTextResponse();
  document.getElementById(editorId).innerHTML = result;
  if (tinyMCE.get(editorId) == null) {
    setupEditor(editorButtonMode, editorHeight);
    ed = new tinymce.Editor(editorId, tinyMCE.settings);
    ed.render();
  }
  document.getElementById(editorId + "_nonedittoolbar").style.display = 'none';
}

alertContentSaveFlag = true;

function alertContentSave(value) {
  if (MSIE) return false;
  if (alertContentSaveFlag==false) return false;
  contentSaveAjax = new ajax();
  contentSaveAjax.successCallback = "";
  var data = "ajaxAction=saveContent&prefix=" + elementPrefix + "&table=" + elementTable + "&id=" + elementId + "&storeValue=" + encodeURIComponent(value);
  waitMilliSec(100);
  contentSaveAjax.request(data);
}

function saveElementContent(value) {
  alertContentSaveFlag = false;
  contentSaveAjax = new ajax();
  contentSaveAjax.successCallback = gotoTableId;
  var data = "ajaxAction=saveContent&prefix=" + elementPrefix + "&table=" + elementTable + "&id=" + elementId + "&storeValue=" + encodeURIComponent(value);
  contentSaveAjax.request(data);
}

function gotoTableId() {
  gotoElement(elementTable, elementId);
}

function openEditor(editorId, buttonMode, height) {
  if (tinyMCE.get(editorId) == null) {
    setupEditor(buttonMode, height);
    ed = new tinymce.Editor(editorId, tinyMCE.settings);
    ed.render();
  }
  editorSetFocus(editorId);
}

function editorSetFocus(editorId) {
  setTimeout(function () {
    ed = (editorId=="current") ? tinyMCE.activeEditor : tinyMCE.get(editorId);
    try {
      ed.getWin().focus();
    } catch (e) {}
  }, 500);
}

function setupEditor(buttonMode,height) {
  if (buttonMode=="fullButtons") {
    var buttons1 = buttonsFull1;
    var buttons2 = buttonsFull2;
  } else {
    var buttons1 = buttonsShort;
    var buttons2 = '';
  }
  tinyMCE.init({
    mode : 'none',
    height : height,
    language : language,
    content_css : urlTheme + 'css/' + styleName + '.css',
    css_file : urlTheme + 'css/' + styleName + '.css',
    theme : 'advanced',
    cleanup_callback : 'mceCustomCleanup',
    onchange_callback : 'mceChangeHandler',
    handle_event_callback : 'mceEventHandler',
    cleanup_on_startup : true,
    convert_urls : 'false',
    table_inline_editing : true,
    gecko_spellcheck : true,
    use_native_selects : true,
    font_size_style_values : '8,10,12,14,16,18',
    plugins : 'autosave,inlinepopups',
    theme_advanced_imgPath : urlIcons,
    extended_valid_elements : 'img[src|alt|name|id|class|style|height|width|title|map|onmouseover|onmouseout],form[name|method|class|action|onsubmit]',
    wikistamp_format : '%y-%m-%d',
    wikistamp_user : userName,
    wikistamp_initials : userInitials,
    stylesheets : stylesheets,
    buttons1 : buttons1,
    buttons2 : buttons2
  });
}

function getContentFromEditors() {
  var divCollection = document.getElementsByTagName("div");
  var contentData = "";
  for (count in divCollection) {
    try {
      var div = divCollection[count];
      if (div.id.match(/^contenteditor/)) {
        saveNeedle = div.id.match(/^contenteditor_(.*)$/);
        content = "";
        try {
          content = tinyMCE.get(div.id).getContent();
        } catch (e) {
          try {
            content = div.innerHTML;
          } catch (e) {}
        }
        contentData += "&storeValue[" + saveNeedle[1] + "]=" +  encodeURIComponent(content);
      }
    } catch (e) {}
  }
  return contentData;
}

// language related

function chooseLanguage(language, langnavareas) {
  if (location.href.match(/index\.php/) || !location.href.match(/\.php/)) {
    gotoLocation("index.php?lang=" + language);
  } else if (location.href.match(/install\.php/)) {
      gotoLocation("install.php?lang=" + language);
  } else if (location.href.match(/registration\.php/)) {
    gotoLocation("registration.php?lang=" + language);
  } else {
    if (langnavareas) {
      setLanguageAjax = new ajax();
      setLanguageAjax.successCallback = setLanguageHomepageResponse;
      var data = "ajaxAction=getLangHomepage&language=" + language;
    } else {
      setLanguageAjax = new ajax();
      setLanguageAjax.successCallback = locationReload;
      var data = "ajaxAction=setLanguage&language=" + language;
    }
    setLanguageAjax.request(data);
  }
}

function startWithLanguage(language) {
  setLanguageAjax = new ajax();
  setLanguageAjax.successCallback = setLanguageHomepageResponse;
  var data = "ajaxAction=getLangHomepage&language=" + language;
  setLanguageAjax.request(data);
}

function setLanguageHomepageResponse() {
  if (!(result = setLanguageAjax.getComplexResponse())) return;
  try {
    pageName = result.getElementsByTagName('pageName')[0].childNodes[0].nodeValue;
  } catch (e) { pageName = ""; }
  try {
    startURL = result.getElementsByTagName('startURL')[0].childNodes[0].nodeValue;
  } catch (e) { startURL = ""; }
  basePath = (startURL != "") ? startURL : urlBase;
  gotoWikiPage(pageName, "", basePath);
}

// routines for mce

var lastEvent = "";
function mceEventHandler(e) {
  lastEvent = e;
  return true;
}

function mceChangeHandler(inst) {
  string = "";
  try {
    var charCode = lastEvent.charCode ? lastEvent.charCode : lastEvent.keyCode;
    if (charCode == 13) {
      if (tinyMCE.selectedElement != null 
        && tinyMCE.selectedElement.nodeName.toLowerCase() == "p") {
          pPart = tinyMCE.selectedElement;
          pPart.className = "p";
      }
    }
    lastEvent = "";
  } catch (e) {}
}

function mceCustomCleanup(type, value) {
  //alert(type + " Value HTML string: |" + value + "|");
  switch (type) {
    case "get_from_editor":
//      value = value.replace(/\„/g, "&laquo;");
//      value = value.replace(/\“/g, "&raquo;");
//      value = value.replace(/(\>|\s|\(|\[)\"/g, "&laquo;");
//      value = value.replace(/\"(\s|\<|\n|\t|\.|\?|\:|\;|\,|\!|\)|\])/g, "&raquo;");
    break;
    case "insert_to_editor":
      if (value=="") value='<p class="p">&nbsp;</p>';
    break;
    case "get_from_editor_dom":
      //value = value.replace(/<img(S)>/g,"<img$1 />");
    break;
    case "insert_to_editor_dom":
      // Do custom cleanup code here
    break;
  }
  return value;
}

function createGroup() {
  promptModal(createGroupProcess, getLang('lang_insertgroupname'), '');
}

function createGroupProcess(groupName) {
  if (groupName==null || groupName=="") return false;
  creategroupAjax = new ajax();
  creategroupAjax.successCallback = createGroupResponse;
  var data = "ajaxAction=groupAdmin&mode=create&storeValue=" + encodeURIComponent(groupName);
  creategroupAjax.request(data);
}

function createGroupResponse() {
  if (!(result = creategroupAjax.getSimpleResponse())) return;
  newLocation = 'owndata.php?userAction=groupsareas';
  if (result=='doubleEntry') {
    alertModal(gotoLocation, getLang("lang_doubleentry"));
  } else if (result=='notallowedValue') {
    alertModal(gotoLocation, getLang("lang_notallowedvalue"));
  } else {
    alertModal(gotoLocation, getLang("lang_groupcreated"));
  }
}

// private functions for the modal window

top.modalCallback = emptyFunction;

function createModalText(modalText) {
  var el = top.document.getElementById('modalDiv');
  newDiv = top.document.createElement("div");
  newDiv.id = 'modalText';
  newDiv.innerHTML = modalText;
  el.appendChild(newDiv);
}

function createModalInputfield(standardValue) {
  var el = top.document.getElementById('modalDiv');
  newInput = top.document.createElement("input");
  newInput.id = 'modalResponse';
  newInput.value= standardValue;
  addClass(newInput, 'sfInput');
  addEvent(newInput, 'click', modalKeypress);
  el.appendChild(newInput);
}

function createModalSelectfield(options) {
  var el = top.document.getElementById('modalDiv');
  newSelect = top.document.createElement("select");
  newSelect.id = 'modalResponse';
  populateSelect(newSelect, options.split(","));
  addClass(newSelect, 'sfSelect');
  addEvent(newSelect, 'click', modalKeypress);
  el.appendChild(newSelect);
}

function createModalButton(buttonId, buttonText, buttonJavascript) {
  var el = top.document.getElementById('modalDiv');
  buttonPanel = top.document.getElementById('modalButtons');
  if (typeof(buttonPanel)=="undefined" || buttonPanel == null) {
    buttonPanel = top.document.createElement("div");
    buttonPanel.id = 'modalButtons';
    addClass(buttonPanel, 'modalButtons');
    el.appendChild(buttonPanel);
  }
  var newButton = top.document.createElement("button");
  newButton.id = buttonId;
  newButton.innerHTML = buttonText;
  addClass(newButton, 'sfButton');
  newButton.style.display = 'inline';
  addEvent(newButton, 'click', buttonJavascript);
  buttonPanel.appendChild(newButton);
}

function setModalSize(modalWidth, modalHeight, modalPadding) {
  try {
    top.document.getElementById('modalIframe').style.width = modalWidth;
    if (MSIE6) top.document.getElementById('modalIframe').style.height = modalHeight;
    top.document.getElementById('modalIframe').style.minHeight = modalHeight;
    top.document.getElementById('modalIframe').style.padding = modalPadding;
  } catch (e) {};
  top.document.getElementById('modalDiv').style.width = modalWidth;
  if (MSIE6) top.document.getElementById('modalDiv').style.height = modalHeight;
  top.document.getElementById('modalDiv').style.minHeight = modalHeight;
  top.document.getElementById('modalDiv').style.padding = modalPadding;
}

function initiateModal(callback) {
  top.modalCallback = callback;
  try {
    top.document.getElementById('modalIframeFrame').style.display = 'block';
  } catch (e) {};
  top.document.getElementById('modalFrame').style.display = 'block';
  top.document.getElementById('modalDiv').style.display = 'block';
  top.document.getElementById('modalDiv').innerHTML = '';
}

function closeModal() {
  try {
    top.document.getElementById('modalIframeFrame').style.display = 'none';
  } catch (e) {};
  top.document.getElementById('modalFrame').style.display = 'none';
  top.document.getElementById('modalDiv').style.display = 'none';
}

function modalKeypress(e) {
  if ((e.keyCode==10) || (e.keyCode==13)) modalClick();
  if (e.keyCode==27) modalCancel();
}

function modalClick() {
  top.closeModal();
  if (top.document.getElementById('modalResponse')) {
    top.modalCallback(document.getElementById('modalResponse').value);
  } else {
    top.modalCallback(true);
  }
}

function modalCancel() {
  top.closeModal();
  top.modalCallback(false);
}

// This is replace alert function it saves function callback and sets up dialog with an ok button
function alertModal(callback, modalText, height, width) {
  if (typeof(width)=="undefined") width = 300;
  if (typeof(height)=="undefined") height = 150;
  if (MSIE6 && typeof(document.getElementById('modalDiv'))=="undefined") {
    alert(modalText);
    callback();
  } else {
    initiateModal (callback, modalText);
    setModalSize (width + 'px', height +  'px', '20px');
    createModalText(modalText);
    createModalButton ('okModalBut', getLang('lang_ok'), modalClick);
    top.document.getElementById('okModalBut').focus();
  }
}

// This is replace prompt function it saves function callback and sets up dialog with ok/cancel buttons
function promptModal(callback, modalText, standardValue) {
  if (MSIE6 && typeof(document.getElementById('modalDiv'))=="undefined") {
    result = prompt(modalText, standardValue);
    callback();
  } else {
    initiateModal(callback);
    setModalSize('300px', '100px', '20px');
    createModalText(modalText);
    createModalInputfield(standardValue);
    createModalButton('okModalBut', getLang('lang_ok'), modalClick);
    createModalButton('cancelModalBut', getLang('lang_cancel'), modalCancel);
    top.document.getElementById('modalResponse').focus();
    top.document.getElementById('modalResponse').select();
  }
}

// This is replace select function it saves function callback and sets up dialog with ok/cancel buttons
function selectModal(callback, modalText, options) {
  if (MSIE6 && typeof(document.getElementById('modalDiv'))=="undefined") {
    result = prompt(modalText, "");
    callback();
  } else {
    initiateModal(callback);
    setModalSize('300px', '100px', '20px');
    createModalText(modalText);
    createModalSelectfield(options);
    createModalButton('okModalBut', getLang('lang_ok'), modalClick);
    createModalButton('cancelModalBut', getLang('lang_cancel'), modalCancel);
    top.document.getElementById('modalResponse').focus();
  }
}

// This is replace confirm function it saves function callback and sets up dialog with yes/no buttons
function confirmModal(callback, modalText, height) {
  initiateModal(callback);
  setModalSize('300px', '100px', '20px');
  createModalText(modalText);
  createModalButton('yesModalBut', getLang("lang_yes"), modalClick);
  createModalButton('noModalBut', getLang("lang_no"), modalCancel);
  top.document.getElementById('yesModalBut').focus();
}

function pleaseLogin() {
  initiateModal(emptyFunction);
  setModalSize ('300px', '100px', '13px');
  modalText  = getLang("lang_noaccesstextlogin");
  modalText += (authProfile != 'adminReg' ? " " + getLang("lang_noaccesstextregister") : "");
  createModalText(modalText);
  createModalButton ('loginModalBut', getLang("lang_login"), pleaseLoginLogin);
  if (authProfile != 'adminReg') {
    createModalButton ('registerModalBut', getLang("lang_register"), pleaseLoginRegister);
  }
  createModalButton ('cancelModalBut', getLang("lang_cancel"), modalCancel);
  top.document.getElementById('loginModalBut').focus();
}

function pleaseLoginLogin() {
  closeModal();
  loginWindow();
}

function pleaseLoginRegister() {
  closeModal();
  gotoLocation(urlBase + "registration.php");
}

function deleteAccount(userName) {
  alert(userName);
}

// routines for datePicker

function pickDate(id) {
  top.dateFieldEl = document.getElementById(id);
  pickDateAjax = new ajax();
  pickDateAjax.successCallback = pickDateResponse;
  var data = "ajaxAction=pickDate&date=" + top.dateFieldEl.value;
  pickDateAjax.request(data);
}

function changeMonth(year, month) {
  pickDateAjax = new ajax();
  pickDateAjax.successCallback = pickDateResponse;
  var data = "ajaxAction=pickDate&yearID=" + year + "&monthID=" + month;
  pickDateAjax.request(data);
}

function pickDateResponse() {
  var modalText = pickDateAjax.getTextResponse();
  initiateModal(emptyFunction);
  setModalSize('160px', '170px', '4px');
  createModalText(modalText);
  createModalButton('cancelModalBut', getLang("lang_cancel"), modalCancel);
}

function selectDate(year, month, day) {
  var date = year + "-" + month + "-" + day;
  closeModal();
  top.dateFieldEl.value = date;
  if (typeof(ajaxAction[top.dateFieldEl.form.name])!="undefined") {
    ajaxFormChange(top.dateFieldEl);
  }
}

// routines for colorPicker

function pickColor(id) {
  top.colorInputEl = document.getElementById(id);
  top.colorFieldEl = document.getElementById(id + '_colorField');
  pickColorAjax = new ajax();
  pickColorAjax.successCallback = pickColorResponse;
  var data = "ajaxAction=pickColor";
  pickColorAjax.request(data);
}

function pickColorResponse() {
  var modalText = pickColorAjax.getTextResponse();
  initiateModal(emptyFunction);
  setModalSize('350px', '250px', '6px');
  createModalText(modalText);
  updateLight(top.colorInputEl.value);
  changeFinalColor(top.colorInputEl.value);
}

function changeFinalColor(color) {
  if (color.indexOf('#') == -1) color = convertRGBToHex(color);
  try {
    top.document.getElementById("colorPreview").style.backgroundColor = color;
    top.document.getElementById("colorValue").value = color;
  } catch (e) {
    document.getElementById("colorPreview").style.backgroundColor = color;
    document.getElementById("colorValue").value = color;
  }
}

function selectColor() {
  var color = top.document.getElementById("colorValue").value;
  closeModal();
  top.colorInputEl.value = color;
  top.colorFieldEl.style.backgroundColor = color;
  if (typeof(ajaxAction[top.colorInputEl.form.name])!="undefined") {
    ajaxFormChange(top.colorInputEl);
  }
}

function mouseMoverOver1(event) {
  if (isMouseDown && isMouseOver) computeColor(event); return false;
}

function mouseMoverOver2(el) {
  if (isMouseDown && isMouseOver) changeFinalColor(el.style.backgroundColor); return false;
}

// color functions

function convertRGBToHex(col) {
  if (!col) return false;
  var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
  var rgb = col.replace(re, "$1,$2,$3").split(',');
  if (rgb.length == 3) {
    r = parseInt(rgb[0]).toString(16);
    g = parseInt(rgb[1]).toString(16);
    b = parseInt(rgb[2]).toString(16);
    r = r.length == 1 ? '0' + r : r;
    g = g.length == 1 ? '0' + g : g;
    b = b.length == 1 ? '0' + b : b;
    return "#" + r + g + b;
  }
  return col;
}

function convertHexToRGB(col) {
  if (col.indexOf('#') != -1) {
    col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
    r = parseInt(col.substring(0, 2), 16);
    g = parseInt(col.substring(2, 4), 16);
    b = parseInt(col.substring(4, 6), 16);
    return {r : r, g : g, b : b};
  }
  return null;
}

var colorLightDetail = 50;
var i, isMouseDown = false, isMouseOver = false;

function dechex(n) {
  var strhex = "0123456789abcdef";
  return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16);
}

function computeColor(el, e) {
  var x, y, partWidth, partDetail, imHeight, r, g, b;

  x = (e.offsetX ? e.offsetX : e.layerX) - 15;
  y = (e.offsetY ? e.offsetY : e.layerY) - 15;

  partWidth = document.getElementById('colorImage').width / 6;
  partDetail = 25;
  imHeight = document.getElementById('colorImage').height;

  r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255;
  g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255  + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth);
  b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth);


  coef = (imHeight - y) / imHeight;

  r = 128 + (r - 128) * coef;
  g = 128 + (g - 128) * coef;
  b = 128 + (b - 128) * coef;

  changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b));
  updateLight('#' + dechex(r) + dechex(g) + dechex(b));
}

function updateLight(inputColor) {
  col = convertHexToRGB(inputColor);
  var i, partDetail = 25, finalCoef, finalR, finalG, finalB, color;
  for (i=0; i< 50; i++) {
    if ((i>=0) && (i<partDetail)) {
      finalCoef = i / partDetail;
      finalR = dechex(255 - (255 - col.r) * finalCoef);
      finalG = dechex(255 - (255 - col.g) * finalCoef);
      finalB = dechex(255 - (255 - col.b) * finalCoef);
    } else {
      finalCoef = 2 - i / partDetail;
      finalR = dechex(col.r * finalCoef);
      finalG = dechex(col.g * finalCoef);
      finalB = dechex(col.b * finalCoef);
    }
    color = '#' + finalR + finalG + finalB;
    try { document.getElementById('gs' + i).style.backgroundColor = color; } catch (e) {}
  }
}

// date functions

function addZeros(value, len) {
  value = "" + value;
  if (value.length < len) {
    for (var i=0; i<(len-value.length); i++) value = "0" + value;
  }
  return value;
}

function getDateTime(d, fmt) {
  var ed = this.editor;

  var fullYear = "" + d.getFullYear();
  var shortYear = fullYear.substr(2, 2);
  fmt = fmt.replace("%D", "%m/%d/%y");
  fmt = fmt.replace("%r", "%I:%M:%S %p");
  fmt = fmt.replace("%Y", fullYear);
  fmt = fmt.replace("%y", shortYear);
  fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2));
  fmt = fmt.replace("%d", addZeros(d.getDate(), 2));
  fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2));
  fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2));
  fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2));
  fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1));
  fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM"));
  fmt = fmt.replace("%b", "" + getLang("lang_datetime_months")[d.getMonth()]);
  fmt = fmt.replace("%a", "" + getLang("lang_datetime_days")[d.getDay()]);
  fmt = fmt.replace("%%", "%");
  return fmt;
}

// different base and helper functions

function getElVal(id) {
  return document.getElementById(id).value;
}

function waitMilliSec(milliSec) {
  var sDate = new Date();
  var sMsec = sDate.getTime();
  do {
    eDate = new Date();
    eMsec = eDate.getTime();
  } while ((eMsec-sMsec)<milliSec);
}

function populateSelect(selectObj, valuesArray, formatPageName) {
  selectObj.options.length = 0;
  for (var i = 0; i < valuesArray.length; i++ ) {
    var code = valuesArray[ i ];
    var codeText = code.replace(/&#039;/, "\'");
    if (typeof(formatPageName)!="undefined") codeText = formatPageNameNS(codeText);
    var opt = new Option(codeText, code);
    try {
      selectObj.add(opt, null); // standards compliant; doesn't work in IE
    } catch(ex) {
      selectObj.add(opt); // IE only
    }
  }
}

function addSelectOption(id, text, value) {
  var selection = document.getElementById(id);
  if (selection == null) return false;
  selection.options[selection.length] = new Option(text, value);
}

function setPreSelection(id, preselectValue) {
  var selection = document.getElementById(id);
  if (selection == null) return false;
  for(var i = 0; i < selection.length; i++) {
    if (selection.options[i].value == preselectValue) {
      selection.selectedIndex = i;
      break;
    }
  }
}

function splitPageNameNS(pageNameNS) {
  matches = pageNameNS.match(/^([^\:\:]*?)\:\:(.*)$/);
  return (matches) ? matches : false;
}

function formatPageNameNS(pageNameNS) {
  if (matches = splitPageNameNS(pageNameNS)) {
    return matches[2] + " (" + matches[1] + ")";
  } else {
    return pageNameNS;
  }
}

function changeSelectionContent(el, ajaxFunction, targetObjId) {
  targetObj = document.getElementById(targetObjId);
  selectContentAjax = new ajax();
  selectContentAjax.successCallback = changeSelectionContentProcess;
  var data = "ajaxAction=" + ajaxFunction + "&value=" + el.value;
  selectContentAjax.request(data);
}

function changeSelectionContentProcess() {
  options = selectContentAjax.getSimpleResponse();
  populateSelect(targetObj, options.split(","), true);
}

function setSrc(imgEl, imageName) {
  if (document.all) {
    imgEl.src = "js/blank.gif";
    imgEl.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader("
                + "src='" + urlIcons + imageName + "',sizingMethod='image')";
  } else {
    imgEl.src = urlIcons + imageName;
  }
}

function getScrollPosX() {
   var h = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
   return h ? h : 0;
}

function getScrollPosY() {
   var h = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
   return h ? h : 0;
}

function getCursorPosX(event) {
  return (!document.all) ? event.clientX : window.event.clientX;
}

function getCursorPosY(event) {
  return (!document.all) ? event.clientY : window.event.clientY;
}

var clickEventY = 300;
var clickEventX = 300;

addEvent(document, "mousedown", setPosition);

function setPosition(event)  {
  clickEventX = getCursorPosX(event);
  clickEventY = getCursorPosY(event);
}

function addEvent(el, evname, func) {
  if (el.addEventListener) el.addEventListener(evname, func, false);
  else                     el.attachEvent("on" + evname, func);
}

function removeEvent(el, evname, func) {
  if (el.removeEventListener) el.removeEventListener(evname, func, false);
  else                        el.detachEvent("on" + evname, func);
}

function stopEvent(event) {
  if (event.preventDefault) {
    event.preventDefault();
  } else {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
}

function addClass(el, className) {
  try {
    removeClass(el, className);
    el.className += " " + className;
  } catch (e) {}
}

function removeClass(el, className) {
  if (!(el && el.className)) return;
  var cls = el.className.split(" ");
  var ar = new Array();
  for (var i = cls.length; i > 0;) {
    if (cls[--i] != className) {
      ar[ar.length] = cls[i];
    }
  }
  el.className = ar.join(" ");
}

function deleteElement(elTmp, tableTmp, idTmp, linkTmp, doConfirm, refObjTmp) {
  el = elTmp; id = idTmp; table = tableTmp; refObj = refObjTmp; newLocation = linkTmp;
  if (typeof(doConfirm)!="undefined" && doConfirm == true) {
    confirmModal(deleteElementConfirmed, getLang('lang_confirmdelete'), 160);
  } else {
    deleteElementConfirmed();
  }
}

function deleteElementConfirmed(confirmation) {
  if (confirmation==false) return;
  if (typeof(refObj)=="undefined") {
    refObj = (el.form == null || typeof(formRefObj[el.form.name]) == "undefined") 
                ? "contentObj" : formRefObj[el.form.name];
  }
  deleteElementAjax = new ajax();
  deleteElementAjax.successCallback = deleteElementResponse;
  var data = "ajaxAction=deleteElement&table=" + encodeURIComponent(table) + "&id=" + id + "&refObj=" + refObj;
  deleteElementAjax.request(data);
}

function deleteElementResponse() {
  var result = deleteElementAjax.getComplexResponse();
  var selType = result.getElementsByTagName('type')[0].childNodes[0].nodeValue;
  if (selType=="emptyselection") {
    gotoLocation(newLocation + "showList");
  } else {
    nextId    = result.getElementsByTagName('id')[0].childNodes[0].nodeValue;
    nextTable = result.getElementsByTagName('table')[0].childNodes[0].nodeValue;
    data = "&table=" + encodeURIComponent(nextTable) + "&id=" + nextId;
    gotoLocation(newLocation + data);
  }
}

function PageQuery(q) {
  if (q.length > 1) this.q = q.substring(1, q.length);
  else this.q = null;
  this.keyValuePairs = new Array();
  if (q) {
    for(var i=0; i < this.q.split("&").length; i++) {
      this.keyValuePairs[i] = this.q.split("&")[i];
    }
  }
  this.getKeyValuePairs = function() { return this.keyValuePairs; }
  this.getValue = function(s) {
    for (var j=0; j < this.keyValuePairs.length; j++) {
      if (this.keyValuePairs[j].split("=")[0] == s)
      return this.keyValuePairs[j].split("=")[1];
    }
    return false;
  }
  this.getParameters = function() {
    var a = new Array(this.getLength());
    for(var j=0; j < this.keyValuePairs.length; j++) {
      a[j] = this.keyValuePairs[j].split("=")[0];
    }
    return a;
  }
  this.getLength = function() { return this.keyValuePairs.length; }
}

function queryString(key) {
  var page = new PageQuery(window.location.search);
  return unescape(page.getValue(key));
}

function setAnchor() {
  hashValue = queryString("anchor");
  if (hashValue != "false") location.hash = hashValue;
}

function getSelectedText() {
  if (window.getSelection) {
    selectedText = window.getSelection();
  } else if (document.selection) { // should come last; Opera!
    var textRange = document.selection.createRange();
    selectedText = textRange.text;
  }
  return selectedText;
}

function fillDiv(id, value) {
  var el = document.getElementById(id);
  if (value!="") {
    el.style.display = "block";
    el.innerHTML = value;
  } else {
    el.style.display = "none";
  }
}

function stripHTML(arg) {
  return arg.replace(/<\S[^><]*>/g, "");
}

function trim(content) {
  return content.replace(/[\n\r]/g, '').replace(/ +/g, ' ').replace(/^\s+/g, '').replace(/\s+$/g, '');
}
/* embed media */

function writeFlash(p) {
  writeEmbed(
    'D27CDB6E-AE6D-11cf-96B8-444553540000',
    'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
    'application/x-shockwave-flash',
  p
  );
}

function writeEmbed(cls, cb, mt, p) {
  var h = '', n;

  h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
  h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
  h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
  h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
  h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
  h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
  h += '>';
  for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">';
  h += '<embed type="' + mt + '"';
  for (n in p) h += n + '="' + p[n] + '" ';
  h += '></embed></object>';
  document.write(h);
}

function updateFileList(table, id, baseLink) {
  fileListAjax = new ajax();
  fileListAjax.successCallback = fileListResponse;
  var data = "ajaxAction=fileList&table=" + encodeURIComponent(table) + "&id=" + id 
             + "&refObj=rhizomObj";
  fileListAjax.request(data);
}

function fileListResponse() {
  var result = fileListAjax.getTextResponse();
  fileList = document.getElementById('fileList');
  fileList.innerHTML = result;
}

function showCitation(biblio) {
  alertModal(emptyFunction, biblio);
}

function showOrderList(el, table, id, value) {
  orderListFireEl = el;
  orderListAjax = new ajax();
  orderListAjax.successCallback = orderListResponse;
  var data = "ajaxAction=orderList&table=" + encodeURIComponent(table) + "&refObj=rhizomObj";
  if (typeof(value)!="undefined") {
    data += "&value=" + encodeURIComponent(value);
  } else {
    data += "&id=" + id;
  }
  orderListAjax.request(data);
}

function orderListResponse() {
  if (!(result = orderListAjax.getSimpleResponse())) return;
  orderList = document.getElementById('orderList');
  orderList.innerHTML = result;
  appletPosition(orderListFireEl, orderList, "200px");
}

function openBibLink(bibLink) {
  countWin = (typeof countWin == "undefined") ? 0 : countWin + 1;
  bibLinkWindow = window.open(bibLink, 'bibWin' + countWin,
         'left=120,top=120,width=1040,height=600,toolbar=1,resizable=1, dependent=1, scrollbars=1, location=1');
  orderList.style.display = "none";
}

// manage the applet for choosing archives

function showArchiveList(el) {
  archiveListFireEl = el;
  archiveListAjax = new ajax();
  archiveListAjax.successCallback = archiveListResponse;
  var data = "ajaxAction=archiveList";
  archiveListAjax.request(data);
}

function archiveListResponse() {
  archiveList = document.getElementById('archiveList');
  archiveList.innerHTML = archiveListAjax.getSimpleResponse();
  appletPosition(archiveListFireEl, archiveList, "120px");
}

function setArchive(archive) {
  setArchiveAjax = new ajax();
  setArchiveAjax.successCallback = locationReload;
  var data = "ajaxAction=userAdmin&field=archive&storeValue=" + encodeURIComponent(archive);
  setArchiveAjax.request(data);
}

// manage the applet for choosing selection 

function showSelectionList(el) {
  selectionList = document.getElementById('selectionList');
  appletPosition(el, selectionList, "150px;");
}

function setSelection(sel) {
  setSelectionAjax = new ajax();
  setSelectionAjax.successCallback = setSelectionResponse;
  var data = "ajaxAction=setSelection&selection=" + sel + "&refObj=rhizomObj";
  setSelectionAjax.request(data);
}

function setSelectionResponse() {
  var result = setSelectionAjax.getComplexResponse();
  var selType = result.getElementsByTagName('type')[0].childNodes[0].nodeValue;
  if (selType=="emptyselection") {
    gotoLocation(toolBaseLink + "&action=emptyselection");
  } else {
    nextId    = result.getElementsByTagName('id')[0].childNodes[0].nodeValue;
    nextTable = result.getElementsByTagName('table')[0].childNodes[0].nodeValue;
    if (nextTable!="none") {
      data = "&table=" + encodeURIComponent(nextTable) + "&id=" + nextId;
    }
    gotoLocation(toolBaseLink + data);
  }
}

// manage the applet for tagClouds

function tagCloudMenu(fieldTemp, tableTemp, selectedTag, 
                      elementLinkTemp, newLocationTemp) {
  tagTable = tableTemp; tagField = fieldTemp;
  newLocation = newLocationTemp; elementLink = elementLinkTemp;
  html = createAppletHead("tagCloudMenu");
  if (elementLink) {
    html += createAppletEntry("goto", selectedTag, getLang("lang_gotoWord"));
  }
  html += createAppletEntry("rename", selectedTag, getLang("lang_renameWord"));
  html += createAppletEntry("merge", selectedTag, getLang("lang_mergeWord"));
  html += createAppletEntry("delete", selectedTag, getLang("lang_deleteWord"));
  appletFrame = document.getElementById('tagCloudMenu');
  appletFrame.innerHTML = html;
  appletDirectPosition(appletFrame, 100);
}

function tagCloudMenuEntry(action, oldTagTemp) {
  hideApplet('tagCloudMenu');
  oldTag = oldTagTemp;
  if (action=="merge") {
    tagCloudMergeAjax = new ajax();
    tagCloudMergeAjax.successCallback = tagCloudMergeResponse;
    var data = "ajaxAction=getTagsFromField&field=" + encodeURIComponent(tagField)
                 + "&table=" + encodeURIComponent(tagTable);
    tagCloudMergeAjax.request(data);
  } else if (action=="goto") {
    gotoLocation(elementLink + oldTagTemp);
  } else if (action=="delete") {
    confirmModal(renameAllTag, getLang("lang_deleteAsk"));
  } else if (action=="rename") {
    promptModal(renameAllTag, getLang("lang_renameAsk"), oldTag);
  }
}

function tagCloudMergeResponse() {
  if (!(result = tagCloudMergeAjax.getSimpleResponse())) return;
  selectModal(renameAllTag, getLang("lang_mergeAsk"), result);
}

function renameAllTag(newTag) {
  if (newTag==false) return;
  if (newTag==true) newTag = "";
  renameAllTagAjax = new ajax();
  renameAllTagAjax.successCallback = gotoLocation;
  var data = "ajaxAction=renameAllTag&field=" + encodeURIComponent(tagField)
                 + "&table=" + encodeURIComponent(tagTable)
                 + "&newTag=" + encodeURIComponent(newTag)
                 + "&oldTag=" + encodeURIComponent(oldTag);
  renameAllTagAjax.request(data);
}

// set a related list as selection

function setasSelection(currTable, ids) {
  batchactionAjax = new ajax();
  batchactionAjax.successCallback = setAsSelectionResponse;
  var data = "ajaxAction=batchAction&batchAction=selectionSnew&refObj=rhizomObj";
  idsarray = ids.split("|");
  for (var i = 0; i < idsarray.length; i++) {
    data += "&markArray[" + i + "] =" + encodeURIComponent(currTable) + "_" + idsarray[i];
  }
  batchactionAjax.request(data);
}

function setAsSelectionResponse() {
    gotoLocation("wiki.php?rhizomatAction=showList");
}

// wiki helper functions

function validWikiPageName(pageName) {
  if (pageName == "") {
    alertModal(emptyFunction, getLang('lang_please_notemptyname'));
    return false;
  } else if (pageName.length > 100) {
    alertModal(emptyFunction, getLang('lang_please_toolong'));
    return false;
  } else if (pageName.match(/[\|\;\,\.\:\#\'\"\*\+\}\]\[\{\&\%\$\§\!\~\<\>\=\?\\\/]/)) {
    alertModal(emptyFunction, getLang('lang_please_nospecial'));
    return false;
  }
  return true;
}

function changeWikiName(elTemp) {
  el = elTemp;
  valid = validWikiPageName (el.value);
  if (valid==false) {
    return false;
  } else {
    renamePageAjax = new ajax();
    renamePageAjax.successCallback = renamePageResponse;
    var data = "ajaxAction=testPageExistence&name=" + encodeURIComponent(el.value);
    renamePageAjax.request(data);
  }
}

function renamePageResponse() {
  if (!(result = renamePageAjax.getSimpleResponse())) return;
  if (result == "OK") {
    ajaxFormChange(el, "input", el.lang);
  } else {
    alertModal(emptyFunction, result, 200);
    return false;
  }
}

// open and save pages

function editPage(pageNameNSTemp) {
  pageNameNS = pageNameNSTemp;
  if (MSIE6 || GECKO && navigator.productSub < 20030210) {
    alertModal(emptyFunction, getLang("lang_isOldBrowser",200));
    return false;
  }
  if (WEBKIT) {
    confirmModal(editPageConfirmed, getLang('lang_isOtherBrowser'), 200);
  } else {
    editPageConfirmed();
  }
}

function editPageConfirmed(result) {
  if (result==false) return false;
//  editPageAjax = new ajax();
//  editPageAjax.successCallback = responseEditPage;
  gotoWikiPage(pageNameNS, "&action=edit");
}

function responseEditPage() {
  if (!(result = editPageAjax.getSimpleResponse())) return;
  if (result=='TRUE') {
    alertModal(emptyFunction, getLang("lang_isBlocked", 200));
  } else {
    gotoWikiPage(pageNameNS, "&action=edit");
  }
}

alertContentSaveFlag = true;

function alertContentSave() {
  if (MSIE) return false;
  if (alertContentSaveFlag==false) return false;
  var contentData = getContentFromEditors();
  contentSaveAjax = new ajax();
  contentSaveAjax.successCallback = emptyFunction;
  doit = confirm(getLang('lang_ask_save_urgently'));
  if (!doit) return false;
  var data = "ajaxAction=savePageContent&pageId=" + top.pageId + contentData;
  contentSaveAjax.request(data);
}

function saveAllCards() {
  alertContentSaveFlag = false;
  var contentData = getContentFromEditors();
  contentSaveAjax = new ajax();
  contentSaveAjax.successCallback = cardSaveResponse;
  var data = "ajaxAction=savePageContent&pageId=" + top.pageId + contentData;
  contentSaveAjax.request(data);
}

function cardSaveResponse() {
  if (!(pageName = contentSaveAjax.getSimpleResponse())) return;
  gotoWikiPage(pageName);
}

function cancelEditor() {
  wikiIdLink(top.pageId);
}

// delete pages

function setPageCurrent(pageId, versionId) {
  setcurrentPageAjax = new ajax();
  setcurrentPageAjax.successCallback = responseSetcurrentPage;
  var data = "ajaxAction=setPageCurrent&pageId="+ pageId + "&versionId=" + versionId;
  setcurrentPageAjax.request(data);
}

function responseSetcurrentPage() {
  if (!(pageName = setcurrentPageAjax.getSimpleResponse())) return;
  gotoWikiPage(pageName);
}

function deletePage(text, pageIdTemp, versionIdTemp) {
  pageId = pageIdTemp;
  versionId = (typeof(versionIdTemp) != "undefined") ? versionIdTemp : "";
  confirmModal(deletePageConfirmed, text);
}

function deletePageConfirmed(result) {
  if (result==false) return false;
  deletePageAjax = new ajax();
  deletePageAjax.successCallback = responseDeletePage;
  var data = "ajaxAction=deletePage&pageId=" + pageId + "&versionId=" + versionId;
  deletePageAjax.request(data);
}

function responseDeletePage() {
  if (!(pageName = deletePageAjax.getSimpleResponse())) return;
  gotoWikiPage(pageName);
}

// page buttons functions

function printVersion(pageName) {
  printWindow = window.open(urlBase + "wiki.php?wiki=" + encodeURIComponent(pageName) + "&action=print", "print", "top=20,left=20,width=900,height=600,menubar=yes,scrollbars=yes");
  printWindow.focus();
}

function openPageOptions(pageId) {
  openPopupWindow("pageOptions2", "pageOptions", "pageId=" + pageId);
}

function openPageVersions(pageId) {
  openPopupWindow("pageVersions", "pageVersions", "pageId=" + pageId);
}

function openRelatedPages(pageId) {
  openPopupWindow("relatedPages", "relatedPages", "pageId=" + pageId);
}

// process bookmarks

function bookmark(pageName) {
  bookmarkAjax = new ajax();
  bookmarkAjax.successCallback = responseBookmark;
  var data = "ajaxAction=bookmark&page=" + encodeURIComponent(pageName);
  bookmarkAjax.request(data);
}

function responseBookmark() {
  if (!(result = bookmarkAjax.getSimpleResponse())) return;
  var iconButton = document.getElementById("bookmarkIconButton");
  var textButton = document.getElementById("bookmarkTextButton");
  if (result=="added") {
    if (iconButton) {
      iconButton.firstChild.src = urlIcons + "bookmark_add.png";
    } else {
      var bookmarkHint = document.createElement("img");
      bookmarkHint.id = "bookmarkHint";
      addClass(bookmarkHint, 'bookmarkHint');
      setSrc(bookmarkHint, "bookmark-set.png");
      textButton.appendChild(bookmarkHint);
    }
  } else {
    if (iconButton) {
      setSrc(iconButton.firstChild, "bookmark.png");
    } else {
      var eleme = document.getElementById("bookmarkHint");
      eleme.parentNode.removeChild(eleme);
    }
  }
}

// process commments

function writeComment(pageId) {
  openPopupWindow('writeComment', 'writeComment', 'pageId=' + pageId);
}

function saveComment() {
  alertContentSaveFlag = false;
  var ed = tinyMCE.get('comment');
  commentSaveAjax = new ajax();
  commentSaveAjax.successCallback = commentSaveResponse;
  var data = "ajaxAction=addComment&pageId=" + encodeURIComponent(top.pageId)
                          + "&storeValue=" +  encodeURIComponent(ed.getContent());
  commentSaveAjax.request(data);
}

function commentSaveResponse() {
  var  result = commentSaveAjax.getComplexResponse();
  try {
    var pageName = nodeContent(result, 'pageName');
  } catch (e) { pageName = ""; };
  try {
    var commentId = nodeContent(result, 'commentId');
  } catch (e) { commentId = ""; };
    gotoWikiPage(pageName, "&showComments=true&anchor=" + commentId);
}

function deleteComment(pageId, commentId) {
  deleteCommentAjax = new ajax();
  deleteCommentAjax.successCallback = responseDeleteComment;
  var data = "ajaxAction=deleteComment&pageId=" + pageId + "&commentId=" + commentId;
  deleteCommentAjax.request(data);
}

function responseDeleteComment() {
  if (!(pageName = deleteCommentAjax.getSimpleResponse())) return;
  gotoWikiPage(pageName);
}

// other wiki functions

function wikiLink(pageName, addArguments) {
  var pageName = pageName.replace(/&#039;/, "\'");
  if (typeof(addArguments)=="undefined") addArguments = "";
  gotoWikiPage(pageName, addArguments);
}

function wikiIdLink(pageId, addArgumentsTemp, addAnchorTemp) {
  addArguments = (typeof(addArgumentsTmp)=="undefined") ? "" : addArgumentsTemp;
  addAnchor = (typeof(addAnchorTmp)=="undefined") ? "" : addAnchorTemp ;
  namefromIdAjax = new ajax();
  namefromIdAjax.successCallback = responseNamefromId;
  var data = "ajaxAction=getNameFromId&pageId=" + pageId;
  namefromIdAjax.request(data);
}

function responseNamefromId() {
  if (!(pageName = namefromIdAjax.getSimpleResponse())) return;
  gotoWikiPage(pageName, addArguments, "", addAnchor);
}

function createPage(pageName, refPageIdTmp, categoryTmp) {
  refPageId = (typeof(refPageIdTmp)=="undefined") ? "" : refPageIdTmp
  category = (typeof(categoryTmp)=="undefined") ? "" : categoryTmp;
  newPageName = pageName;
  newpageAjax = new ajax();
  newpageAjax.successCallback = createPageResponse;
  var data = "ajaxAction=createPage&storeValue=" + encodeURIComponent(newPageName)
           + "&category=" + category + "&refPageId=" + refPageId;
  newpageAjax.request(data);
}

function createPageResponse() {
  if (!(response = newpageAjax.getSimpleResponse())) return;
  if (!isNaN(response)) {
    wikiIdLink(response);
  } else {
    alertModal(emptyFunction, response, 200);
  }
}

function onCancel() {
  self.close();
  return false;
};

/*
url = http://www.erwachsenenbildung.uni-giessen.de/searchplugins/
url = http://mycroft.mozdev.org/external.php/
*/
function addSearchPlugin(name,url,extension, cat) {
  if ((typeof window.sidebar == "object") 
    && (typeof window.sidebar.addSearchEngine == "function")) {
      window.sidebar.addSearchEngine(
        url + name + ".src",
        url + name + extension, name, cat);
  } else {
    alert(getLang('lang_searchplugin_gecko'));
  }
}

/*
url = "http://mycroft.mozdev.org/installos.php/" + pid + "/"
*/
function addOpenSearch(name,url,meth) {
  if ((typeof window.external == "object") 
     && ((typeof window.external.AddSearchProvider == "unknown")
       || (typeof window.external.AddSearchProvider == "function"))) {
    if ((typeof window.external.AddSearchProvider == "unknown") && meth == "p") {
      alert(getLang('lang_searchplugin_post'));
    } else {
      window.external.AddSearchProvider(url + "/" + name + ".xml");
    }
  } else {
    alert(getLang('lang_searchplugin_browser'));
  }
}

function verifyEmail(string) {
  var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
  return (string.search(emailRegEx) == -1) ? false : true;
}

function sendaTestmail() {
  openPopupWindow('sendTestmail', 'sendTestmail');
}

function changeMailMode() {
  mailMode = document.getElementById('adminOptMailmailMode').value;
  setDisplayMode("none", "sendmailPath,smtpHost,smtpPort,smtpUser,smtpSecure", "adminOptMail");
  setDisplayMode("none", "smtpPass");
  if (mailMode=="sendmail") {
    setDisplayMode("block", "sendmailPath", "adminOptMail");
  } else {
    setDisplayMode("block", "smtpHost,smtpPort,smtpUser,smtpSecure", "adminOptMail");
    setDisplayMode("inline", "smtpPass");
  }
}

// biblio functions

function changeBiblio(base) {
  newType       = document.getElementById(base + 'type').value;
  setDisplayMode("none", "hostinfos,placepub,article,onlinearticle,serialsupplement,"
                        + "serialspecialissue,conferencepaper,workingpaper,media",
                   "", "parent");
  if (newType=="incollection") {
    setDisplayMode("block", "hostinfos", "", "parent");
  } else if (newType=="article") {
    setDisplayMode ("block", "article", "", "parent");
  } else if (newType=="onlinearticle") {
    setDisplayMode("block", "onlinearticle", "", "parent");
  } else if (newType=="serialspecialissue") {
    setDisplayMode("block", "serialspecialissue", "", "parent");
  } else if (newType=="serialsupplement") {
    setDisplayMode("block", "serialsupplement,placepub", "", "parent");
  } else if (newType=="conferencepaper") {
    setDisplayMode("block", "conferencepaper,placepub", "", "parent");
  } else if (newType=="workingpaper") {
    setDisplayMode("block", "workingpaper,placepub", "", "parent");
  } else if (newType=="moving image" || newType=="still image" || newType=="sound recording-musical" ||
             newType=="sound recording-nonmusical") {
    setDisplayMode("block", "media,placepub", "", "parent");
  } else {
    setDisplayMode("block", "placepub", "", "parent");
  }
}

function formChangePlugin() {
  if (document.getElementById('placeholderEl')!=null) {
    updateBiblioAjax = new ajax();
    updateBiblioAjax.successCallback = updateBiblioAjaxResponse;
    var data = "ajaxAction=updateBiblio&refObj=" + formRefObj[el.form.name] + "&table=" + encodeURIComponent(formTable[el.form.name]) + "&id=" + formId[el.form.name];
    updateBiblioAjax.request(data);
  }
  if (document.getElementById('stampEl')!=null) {
    updateDataAjax = new ajax();
    updateDataAjax.successCallback = updateDataAjaxResponse;
    var data = "ajaxAction=updateData&refObj=" + formRefObj[el.form.name] + "&table=" + encodeURIComponent(formTable[el.form.name]) + "&id=" + formId[el.form.name];
    updateDataAjax.request(data);
  }
}

function updateDataAjaxResponse() {
  var  result = updateDataAjax.getComplexResponse();
  try {
    document.getElementById('stampEl').innerHTML = nodeContent(result, 'stamp');
  } catch (e) {};
}

function updateBiblioAjaxResponse() {
  var  result = updateBiblioAjax.getComplexResponse();
  try {
    document.getElementById('browseEl').innerHTML = nodeContent(result, 'biblio');
  } catch (e) {};
  try {
    document.getElementById('labelEl').innerHTML = nodeContent(result, 'label');
  } catch (e) {};
  try {
    document.getElementById('placeholderEl').innerHTML = nodeContent(result, 'placeholder');
  } catch (e) {};
}

// area functions

function openCreateAreaWizard() {
  openPopupWindow('createarea', 'createarea');
}

function createNewArea() {
  var areaName = document.getElementById('areasareaname').value;
  var startPage = document.getElementById('areasstartPage').value;
  var presetArea = document.getElementById('areasareapreset').value;
  createareaAjax = new ajax();
  createareaAjax.successCallback = responseCreateNewArea;
  var data = "ajaxAction=createArea&storeValue=" + areaName + "&startPage=" + startPage + "&presetArea=" + presetArea;
  createareaAjax.request(data);
}

function responseCreateNewArea() {
  if (!(result = createareaAjax.getSimpleResponse())) return;
  if (result.match(/^[0-9]*$/)) {
    gotoLocation("admin.php?areaAction=edit&id=" + result);
  } else {
    alertModal(emptyFunction, result, 200);
    return false;
  }
}

function deleteArea(el, name, id, baseLinkTemp) {
  baseLink = baseLinkTemp; areaId = id;
  deleteAreaAjax = new ajax();
  deleteAreaAjax.successCallback = deleteAreaResponse;
  var data = "ajaxAction=getAreaNames&withoutAreaId=" + id;
  deleteAreaAjax.request(data);
}

function deleteAreaResponse() {
  if (!(result = deleteAreaAjax.getSimpleResponse())) return;
  selectModal(deleteAreaProcess, getLang("lang_areaReplace"), result);
}

function deleteAreaProcess(replaceArea) {
  newLocation = baseLink + "&replaceArea=" + replaceArea;
  gotoLocation(newLocation);
}

function choosen() {
  document.getElementById('spanGroup');
  document.getElementById('span' + itemListName[1]).innerHTML
}

// login functions

function loginWindow() {
  openPopupWindow('login', 'login');
}

function authLogin(crypt) {
  user = document.getElementById('loginpuser').value;
  pass = document.getElementById('ppass').value;
  if (crypt && crypt=="md5") pass = MD5(pass);
  loginAjax = new ajax();
  loginAjax.successCallback = responseLoginPopup;
  var data = "ajaxAction=loginAuth" + "&user=" + user + "&pass=" + pass;
  loginAjax.request(data);
}

function responseLoginPopup() {
  if (!(result = loginAjax.getSimpleResponse())) return;
  if (result=="OK") {
    gotoLocation(urlBase + "wiki.php" + location.search);
  } else {
    try {
      loginError = document.getElementById('loginErrorPopup');
      loginError.innerHTML = result;
    } catch (e) {
      alert(result);
    }
  }
}

function setUserPassword(id) {
  openPopupWindow('setuserpass', 'setuserpass', 'id=' + id);
}

function saveUserPassword(id) {
  userId = id;
  try {
    oldPass = document.getElementById('oldpassword').value;
  } catch (e) { oldPass = false; }
  newPass = document.getElementById('newpassword').value;
  newPassW = document.getElementById('retypepassword').value;
  if (newPass!=newPassW) {
    alertModal(emptyFunction, getLang("lang_wrongpassdouble"));
    return false;
  } else if (newPass.length < 6) {
    alertModal(emptyFunction, getLang("lang_passtooshort"));
    return false;
  }
  setpassAjax = new ajax();
  setpassAjax.successCallback = responseSetUserPass;
  var data = "ajaxAction=userAdmin&id=" + userId
               + "&oldpass=" + (oldPass ? MD5(oldPass) : "")
               + "&field=pass&storeValue=" + MD5(newPass);
  setpassAjax.request(data);
}

function responseSetUserPass() {
  if (!(result = setpassAjax.getSimpleResponse())) return;
  if (result == "wrongoldpass") {
    alertModal(emptyFunction, getLang('lang_nopassentry'));
  } else if (oldPass) {
    alertModal(lastPassword, getLang('lang_loginwithnewpass'));
  } else {
    gotoLocation("admin.php?userAction=edit&id=" + userId);
  }
}

function lastPassword() {
  gotoLocation("index.php");
}

// create user wizard 

function openCreateUserWizard() {
  openPopupWindow('createuser', 'createuser');
}

function createNewUser() {
  var userName = document.getElementById('username').value;
  var preName = document.getElementById('userpreName').value;
  var surName = document.getElementById('usersurName').value;
  var niveau = document.getElementById('userniveau').value;
  var language= document.getElementById('userlanguage').value;
  createUserAjax = new ajax();
  createUserAjax.successCallback = responseCreateNewUser;
  var data = "ajaxAction=createUser&userName=" + userName
                                + "&preName=" + preName + "&surName=" + surName 
                                + "&niveau=" + niveau + "&language=" + language;
  createUserAjax.request(data);
}

function responseCreateNewUser() {
  if (!(result = createUserAjax.getSimpleResponse())) return;
  if (result.match(/^[0-9]*$/)) {
    gotoLocation("admin.php?userAction=edit&id=" + result);
  } else {
    alertModal(emptyFunction, result, 200);
    return false;
  }
}

// smtp-password setting

function setSMTPPassword() {
  openPopupWindow('setsmtppass', 'setsmtppass');
}

function saveSMTPPassword() {
  newPass = document.getElementById('newpassword').value;
  newPassW = document.getElementById('retypepassword').value;
  if (newPass!=newPassW) {
    alertModal(emptyFunction, getLang('lang_wrongpassdouble'));
    return false;
  }
  newLocation = "admin.php?action=editMail";
  setpassAjax = new ajax();
  setpassAjax.successCallback = gotoLocation;
  var data = "ajaxAction=adminConf&field=smtpPass&storeValue=" + newPass;
  setpassAjax.request(data);
}

// rhizom-functions

function createNewElement(table, formName) {
  formNameNewElement = formName;
  newElementAjax = new ajax();
  newElementAjax.successCallback = createNewElementResponse;
  var data = "ajaxAction=newElement&table=" +table + "&formName=" + formName;
  newElementAjax.request(data);
}

function newRhizomElement(table, actionType, value, formName) {
  formNameNewElement = formName;
  newElementAjax = new ajax();
  newElementAjax.successCallback = createNewElementResponse;
  var data = "ajaxAction=newElement&actionType=" + actionType
            + "&value=" + encodeURIComponent(value) + "&formName=" + formName + "&refObj=rhizomObj";
  newElementAjax.request(data);
}

function createNewElementResponse() {
  var result = newElementAjax.getComplexResponse();
  data = "&table=" + encodeURIComponent(nodeContent(result, 'table')) + "&id=" + nodeContent(result, 'id');
  if (typeof(formNameNewElement)!="undefined") data += "&" + formNameNewElement + "Action=edit";
  gotoLocation(baseLink + data);
}

function validateLitEntry(idTmp, trueBaseTmp, falseBaseTmp) {
  trueBase = trueBaseTmp; falseBase = falseBaseTmp; id = idTmp;
  validateLitAjax = new ajax();
  validateLitAjax.successCallback = validateLitEntryResponse;
  var data = "ajaxAction=validateLit&id=" + id + "&refObj=rhizomObj";
  validateLitAjax.request(data);
}

function validateLitEntryResponse() {
  var result = validateLitAjax.getSimpleResponse();
  if (result=="OK") {
    toolShowId();
  } else {
    var addData = validateLitAjax.getComplexResponse();
    confirmModal(validateLitProcess, nodeContent(addData, 'message'));
  }
}

function validateLitProcess(value) {
  if (value==false) {
    toolShowId();
  }
}
  
function reloadedBacklinks() {
  fillDiv('backLinksDiv', fillBacklinksAjax.getTextResponse());
}

function reloadedRelations() {
  fillDiv('relationsDiv', fillRelationsAjax.getTextResponse());
}

function reloadedParentDocs() {
  fillDiv('parentDocsDiv', fillParentDocsAjax.getTextResponse());
}

function loadtags(field, id, prefix) {
  fillTagsId = id;
  fillTagsAjax = new ajax();
  fillTagsAjax.successCallback = loadedTags;
  var data = "ajaxAction=loadTags&field=" + field + "&prefix=" + prefix;
  fillTagsAjax.request(data);
}

function loadedTags() {
  fillTagsEl = document.getElementById(fillTagsId);
  filled = fillTagsAjax.getTextResponse();
  fillTagsEl.innerHTML = filled;
}

// functions to manage batchActions

function doBatchAction(el, toolNameTemp) {
  toolNameBatchAction = toolNameTemp;
  batchactionAjax = new ajax();
  batchactionAjax.successCallback = batchactionResponse;
  currAction = document.getElementById('batchAction').value;
  rowsChecks = document.getElementsByName("markArray[]");
  marks = "";
  for (var i = 0; i < rowsChecks.length; i++) {
    if (rowsChecks[i].checked==true) marks += "&markArray[" + i + "]=" + rowsChecks[i].value;
  }
  if (currAction.match("Set") || currAction.match("Delete")) {
    promptModal(batchtaggingProcess, getLang('lang_pleaseinserttag'), '');
  } else if (currAction.match("selection")) {
    var data = "ajaxAction=batchAction&batchAction=" + encodeURIComponent(currAction) + marks + "&refObj=rhizomObj";
    batchactionAjax.request(data);
  } else if (currAction == "deleteFromDatabase") {
    batchDelete(currAction, marks);
  }
}

function batchtaggingProcess(storeValue) {
  if (storeValue == null || storeValue == "") return false;
  data = "ajaxAction=batchTagging&batchAction=" + encodeURIComponent(currAction) + marks + "&tagWord=" + encodeURIComponent(storeValue) + "&refObj=rhizomObj";
  batchactionAjax.request(data);
}

function batchDelete(currAction, marks) {
  sure = confirm('Wollen Sie die Elemente wirklich loeschen?');
  if (sure == false) return false;
  var data = "ajaxAction=batchAction&batchAction=deleteFromDatabase" + marks + "&refObj=rhizomObj";
  batchactionAjax.request(data);
}

function batchactionResponse() {
  var result = batchactionAjax.getComplexResponse();
  var alertText = nodeContent(result, 'text');
  if (alertText == "none") {
    gotoLocation(toolBaseLink + "&" + toolNameBatchAction + "Action=showList");
  } else {
    alertModal(emptyFunction, alertText, 200);
  }
}

function setListFormat(value, toolName) {
   newLoc = toolBaseLink + "&" + toolName + "Action=showList&format=" + value;
   gotoLocation(newLoc);
}
