/***************************************************************************
*   framework.zwo 1.1
*   Copyright 2002-2008 Daniel Wrana
*   http://www.edwiki.selbstlernarchitekturen.info
*   Distributed under the terms of the GNU General Public License v2 or later
****************************************************************************/

browser   = navigator.userAgent.toLowerCase();
MSIE      = browser.indexOf("msie") != -1;
MSIE6     = browser.indexOf("msie 6") != -1;
MSIE7     = browser.indexOf("msie 7") != -1;
GECKO  = navigator.product == "gecko";

ajaxAction = new Array();
ajaxRequestURL = new Array();
ajaxRequestBase = new Array();
ajaxRequestRefObj = new Array();
ajaxRequestLangDiffFields = new Array();

emptyFunction = function () {};

function changeTab (idBase, activeTab, activeTabClass) {
  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.match(idBase + "Card")) {
      divEl.style.display = 'none';
    }
  }
  document.getElementById(idBase + "Card_" + activeTab).style.display = 'block';
  addClass(document.getElementById(idBase + "Tab_" + activeTab), activeTabClass);
  activeLangCard = activeTab;
  if (typeof(changeCardPlugin) != "undefined") changeCardPlugin(activeTab);
}

// login functions

function loginWindow() {
  openPopupWindow('login', 'login');
}

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(pathBase + 'ajax.php', data);
}

function responseSetUserPass() {
  result = setpassAjax.getSimpleResponse();
  if (result == "wrongoldpass") {
    alertModal(emptyFunction, getLang("lang_nopassentry"));
  } else if (oldPass) {
    location.href = 'index.php';
  } else {
    location.href = 'admin.php?userAction=useredit&id=' + userId;
  }
}

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;
  }
  setpassAjax = new ajax();
  setpassAjax.successCallback = responseSetSMTPPass;
  var data = 'ajaxAction=saveConfig&field=smtpPass&storeValue=' + newPass;
  setpassAjax.request(pathBase + 'ajax.php', data);
}

function responseSetSMTPPass() {
  location.href = 'admin.php?action=editMail';
}

function sendaTestmail() {
  openPopupWindow('sendTestmail', 'sendTestmail');
}

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(pathBase + 'ajax.php', data);
}

function responseLoginPopup() {
  result = loginAjax.getSimpleResponse();
  if (result=="OK") {
    location.href = pathBase + "wiki.php" + location.search;
  } else {
    try {
      loginError = document.getElementById('loginErrorPopup');
      loginError.innerHTML = result;
    } catch (e) {
      alert(result);
    }
  }
}

// use of window functions

var alertWindowId = 1;

function openFile(file, path) {
  openPopupWindow('openfile' + file, 'openFile', 'file=' + file + '&path=' + path);
}

function uploadFile() {
  var filePath = document.getElementById('filePath').value;
  openPopupWindow('uploadfile', 'uploadFile', 'path=' + filePath);
}

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);
}

// windowfunctions

top.windowResponseValue = '';

function testWindowResponseValue() {
  if (top.windowResponseValue == 'yes') {
    top.windowResponseValue = '';
    clearInterval(windowResponseInterval);
    try { windowResponseFunction(); } catch(e) {};
    return true;
 } else if (top.windowResponseValue == 'no') {
    top.windowResponseValue = '';
    clearInterval(windowResponseInterval);
    return false;
 } else if (top.windowResponseValue != '') {
    try { windowResponseFunction(top.windowResponseValue); } catch(e) {};
    top.windowResponseValue = '';
    clearInterval(windowResponseInterval);
    return true;
  }
}

if (typeof(top.windowTopIndex)=="undefined") top.windowTopIndex = 1000;
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 = document.getElementById(winId + "_main");
  iframeNode = 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 + '&clickTop=' + clickEventY
              + '&baseTop=' + (document.documentElement.scrollTop + document.body.scrollTop);
  windowAjax.request('window_content.php', 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);
  windowOpeningFlag = false;
}

function pleaseLogin() {
    windowAjax = new ajax();
    windowAjax.successCallback = writePopup;
    var data = 'ajaxAction=alertLogin&winId=alertLogin'
                 + '&zindex=' + top.windowTopIndex + '&clickTop=' + clickEventY;
    windowAjax.request('window_content.php', data);
    windowResponseFunction = new Function("attribut", "loginConfirmed();");
    windowResponseInterval = window.setInterval("testWindowResponseValue();", 200);
}

function loginConfirmed() {
  if (top.windowResponseValue=="register") {
    location.href = pathBase + "registration.php";
  } else if (top.windowResponseValue=="login") {
    loginWindow();
  }
}

function getHtml (ajaxHtml) {
  splits = ajaxHtml.split("<script type='text/javascript'>");
  return splits[0];
}

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) {
  location.href = pathBase + "create_images.php?filetype=" + filetype;
}

// formular functions

function changeFieldFile (formularName) {
  document.getElementById(formularName + 'Action').value = "edit";
  document.getElementById(formularName).submit();
}

function focusElement(id) {
  try {
    document.getElementById(id).focus();
  } catch (e) {}
}

function formChange (formName, el, language) {
  if (typeof(language) == "undefined") language = "";
  if (ajaxAction[formName] == "") return;
  if (typeof beforeFormChangePlugin != "undefined") beforeFormChangePlugin(formName, el);
  callFormAjax(el, 'standard', ajaxRequestURL[formName], ajaxRequestBase[formName], language,
                               ajaxRequestLangDiffFields[formName], ajaxRequestRefObj[formName]);
}

function formBooleanChange(formName, el) {
  if (ajaxAction[formName] == "") return;
  callFormAjax(el, 'boolean', ajaxRequestURL[formName], ajaxRequestBase[formName], "",
                              ajaxRequestLangDiffFields[formName], ajaxRequestRefObj[formName]);
}

function formRadioChange(formName, el) {
  if (ajaxAction[formName] == "") {
    toggleRadio(el);
  } else {
    callFormAjax(el, 'radio', ajaxRequestURL[formName], ajaxRequestBase[formName], "",
                              ajaxRequestLangDiffFields[formName], ajaxRequestRefObj[formName]);
  }
}

function formCheckChange(formName, el) {
  if (ajaxAction[formName] == "") {
    storeValue = el.value == "FALSE" ? "TRUE" : "FALSE";
    toggleCheck(el);
  } else {
    callFormAjax(el, 'check', ajaxRequestURL[formName], ajaxRequestBase[formName], "",
    ajaxRequestLangDiffFields[formName], ajaxRequestRefObj[formName]);
  }
}

function callFormAjax (el, mode, url, basedata, language, langDiffFields, refObj) {
  if (typeof(language) == "undefined") language = "";
  if (typeof(refObj) == "undefined") refObj = "";
  formAjax = new ajax();
  if (mode=='boolean') {
    formAjax.successCallback = processResponseBoolean;
  } else if (mode=='radio') {
    formAjax.successCallback = processResponseRadio;
  } else if (mode=='check') {
    formAjax.successCallback = processResponseCheck;
  } else {
    formAjax.successCallback = processResponse;
  }
  ajaxEle = el;
  if (mode=='radio' || mode=='check') {
    field = ajaxEle.name;
  } else {
    field = ajaxEle.name.match(/\[(.*)\]$/);
    field = (field==null) ? ajaxEle.name : field[1];
  }
  if (field=='passKlar') {
    var passKlar = document.getElementById('pass').value;
    storeValue = (passKlar=='') ? '' : MD5(passKlar);
    var sendField = 'pass';
  } else if (mode=='boolean') {
    var sendField = field;
    storeValue = (ajaxEle.value=='TRUE' ? 'FALSE' : 'TRUE');
  } else if (mode=='radio') {
    var sendField = field;
    storeValue = ajaxEle.id.split("_")[1];
  } else if (mode=='check') {
    var sendField = field;
    storeValue = (ajaxEle.value=='TRUE' ? 'FALSE' : 'TRUE');
  } else {
    storeValue = ajaxEle.value;
    ajaxEle.value = 'Updating...';
    var sendField = field;
  }

  var transLanguage = "";
  if (typeof(langDiffFields) != "undefined" && langDiffFields != "") {
    for (i in langDiffFields.split("|")) {
      for (var i = 0; i < langDiffFields.length; ++i)
        if (langDiffFields[i] = sendField) transLanguage = language;
    }
  }
  data = basedata + '&field=' + sendField + '&language=' + transLanguage
                  + '&storeValue=' + encodeURIComponent(storeValue)
                  + ((refObj != "") ? '&refObj=' + refObj : "");

  formAjax.request(url, data);
}

function processResponse() {
  result = formAjax.getSimpleResponse();

  if (result=='doubleEntry') {
    alertModal(emptyFunction, getLang("lang_doubleentry"));
    ajaxEle.value = "";
  } else if (result=='notallowedValue') {
    alertModal(emptyFunction, getLang("lang_notallowedvalue"));
    ajaxEle.value = "";
  } else if (field!='passKlar') {
    ajaxEle.value = (result || result == "") ? result : storeValue;
  }
  if (typeof formChangePlugin != "undefined") formChangePlugin();
}

function processResponseBoolean() {
  result = formAjax.getSimpleResponse();
  imgEl = document.getElementById(ajaxEle.id + 'Img');
  if (result=='FALSE') {
    ajaxEle.value = 'FALSE';
    imgEl.src = urlIcons + 'off.png';
  } else {
    ajaxEle.value = 'TRUE';
    imgEl.src = urlIcons + 'on.png';
  }
}

function processResponseRadio() {
  toggleRadio(ajaxEle);
}

function processResponseCheck() {
  toggleCheck(ajaxEle);
}

function closeAndLink(transLink) {
  location.href = pathBase + encodeURIComponent(transLink);
}

function toggleRadio(el) {
  var currIdArray = el.id.split("_");
  var hiddenValueEl = document.getElementById(currIdArray[0] + "_hiddenValue");
  hiddenValueEl.value = currIdArray[1];
  var imgCollection = document.getElementsByTagName("img");
  for (count in imgCollection) {
    try {
      var img = imgCollection[count];
      imgIdArray = img.id.split("_");
      if (imgIdArray[0] != currIdArray[0]) continue;
      var val = (typeof img.parentNode.val == "undefined") ? img.parentNode.value 
                                                           : img.parentNode.val;
      if (val == currIdArray[1]) {
        img.src = urlIcons + "round_checked.gif";
      } else {
        img.src = urlIcons + "round_unchecked.gif";
      }
    } catch (e) {}
  }
}

function toggleCheck(el) {
  var currIdArray = el.id.split("_");
  var hiddenValueEl = document.getElementById(currIdArray[0] + "_hiddenValue");
  hiddenValueEl.value = storeValue;
  el.value = storeValue;
  var imgCollection = document.getElementsByTagName("img");
  for (count in imgCollection) {
    try {
      var img = imgCollection[count];
      imgIdArray = img.id.split("_");
      if (imgIdArray[0] != currIdArray[0]) continue;
      if (storeValue=="TRUE") {
        img.src = urlIcons + "box_checked.gif";
      } else {
        img.src = urlIcons + "box_unchecked.gif";
      }
    } catch (e) {}
  }
}

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;
        }
      }
      myElements[ newIndex ].focus();
    }
  };
  return true;
}

function doSubmitForm (obj, formularName, crypt, selectTest) {
  var submit = true;
  if (window.XMLHttpRequest && selectTest == true) {
    selects = document.getElementsByTagName('select');
    for(var i = 0; i < selects.length; i++) {
      if (selects[i].value=='pleaseselect') {
        alert(getLang('lang_pleaseselectoption'));
        submit = false;
        break;
      }
    }
  }
  var email = document.getElementById('valuesemailenforce');
  if (email != null && email.value == '') {
    alert(getLang('lang_pleasesetemail'));
    submit = false;
  }
  if (submit == true) {
    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 obj.val == 'undefined') ? obj.value : obj.val;
    document.getElementById(formularName + "Action").value = value;
    document.getElementById(formularName).submit();
  }
}

// config function

function saveEditedConfiguration (field, value) {
  var contentData = getContentFromEditors();
  configSaveAjax = new ajax();
  configSaveAjax.successCallback = saveEditedConfigurationResponse;
  var data = "ajaxAction=saveConfig&table=configuration&field=" + field + contentData;
  configSaveAjax.request(pathBase + "ajax.php", data);
}

function saveEditedConfigurationResponse () {
  location.href =  pathBase + "admin.php"; //?action=returnSavedConfig&id=" + elementId;
}

function saveActionEditorValue (table, field, id, storeValue, language, refObj) {
  if (typeof(refObj) == "undefined") refObj = "";
  if (typeof(language) == "undefined") language = "";
  configSaveAjax = new ajax();
  configSaveAjax.successCallback = emptyFunction;
  var data = "ajaxAction=editField&id=" + id + "&table=" + table
            + '&field=' + field + '&storeValue=' + encodeURIComponent(storeValue)
            + ((language != "") ? '&language=' + language : "");
            + ((refObj != "") ? '&refObj=' + refObj : "");
  configSaveAjax.request(pathBase + "ajax.php", data);
}

// grid - functions

function gridBooleanChange(el) {
  ele = el;
  alert(ajaxEle.data);
}

function gridAction(name, actionValue, idValue, confirmText) {
  gridName = name;
  gridActionValue = actionValue;
  gridIdValue = idValue;
  if (!confirmText) {
    gridActionProcess();
  } else {
    confirmModal(gridActionProcess, getLang('lang_' + confirmText), 200);
  }
}

function gridActionProcess(result) {
  if (result==false) return false;
  document.getElementById(gridName + 'Action').value = gridActionValue;
  if (gridIdValue) document.getElementById(gridName + 'Id').value = gridIdValue;
  document.getElementById(gridName + 'Form').submit();
}

function gridImageDelete(name) {
  fileName = name;
  confirmModal(gridFileDeleteConfirmed, getLang('lang_confirmimagedelete'), 160);
}

function gridFileDelete(obj, col, name) {
  fileName = name;
  confirmModal(gridFileDeleteConfirmed, getLang('lang_confirmfiledelete'), 160);
}

function gridFileDeleteConfirmed(result) {
  if (result==false) return false;
  gridfiledeleteAjax = new ajax();
  gridfiledeleteAjax.successCallback = gridFileDeleteResponse;
  var filePath = document.getElementById('filePath').value;
  var data = "ajaxAction=deleteFile&path=" + encodeURIComponent(filePath) 
                                + "&name=" + encodeURIComponent(fileName);
  gridfiledeleteAjax.request(pathBase + "ajax.php", data);
}

function gridFileDeleteResponse() {
  location.href = location.search;
}

function fileDelete(path, fileName, target) {
  linkTarget = target;
  filedeleteAjax = new ajax();
  filedeleteAjax.successCallback = fileDeleteResponse;
  var data = "ajaxAction=deleteFile&path=" + encodeURIComponent(path) + "&name=" + encodeURIComponent(fileName);
  filedeleteAjax.request(pathBase + "ajax.php", data);
}

function fileDeleteResponse() {
  location.href = (linkTarget!="") ? linkTarget : location.search;
}

function gridFileShow(el, col, name) {
  var filePath = document.getElementById('filePath').value;
  openFile(name, filePath);
}

function showElementFromTrash (el, action, id) {
  alertModal(emptyFunction, "showElementFromTrash" + "text" + id);
}

function rename (target, text, oldName) {
   newName = prompt(text,oldName);
   if (newName) location.href = target + "&newName=" + encodeURIComponent(newName);
}

function onCancel() {
  self.close();
  return false;
};

function createMessage(name, prefix, table, id, addArguments) {
  if (typeof(addArguments)=="undefined") addArguments = "";
  openPopupWindow('messageForm', 'messageForm', 'prefix=' + prefix + '&table=' + table + '&id=' + id + addArguments);
}

function sendMessage(target) {
  linkTarget = (typeof(target)!="undefined") ? target : "";
  messageSubject = document.getElementById("messageSubject").value;
  messageBody = document.getElementById("messageBody").value;
  messageCategory = document.getElementById("messageCategory").value;
  recipientGroups = document.getElementById("messageGroups").value;
  languages = document.getElementById("messageLanguages").value;
  table = document.getElementById("table").value;
  sendMessageAjax = new ajax();
  sendMessageAjax.successCallback = sendMessageResponse;
  var data = "ajaxAction=sendMessage&body=" + encodeURIComponent(messageBody) 
                                 + "&subject=" + encodeURIComponent(messageSubject)
                                 + "&category=" + encodeURIComponent(messageCategory)
                                 + "&recipientGroups=" + encodeURIComponent(recipientGroups)
                                 + "&languages=" + encodeURIComponent(languages)
                                 + "&table=" + encodeURIComponent(table);
  sendMessageAjax.request(pathBase + "ajax.php", data);
}

function sendMessageResponse() {
//alert(sendMessageAjax.getSimpleResponse());
  if (linkTarget != "") {
    location.href = linkTarget;
  } else {
    location.href = location.href;
  }
}

// functions for tooltips

tooltipArray = new Array;

function tooltipRegister(id) {
  tooltipArray[id] = true;
}

function tooltipUnregister(id) {
  tooltipArray[id] = false;
}

function buttonTooltip(buttonEl, tooltipText, tooltipAlign, tooltipWidth, tooltipOffset) {
  if (MSIE) return false;
  tooltipRegister(buttonEl.id);
  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) {
  tooltipRegister(el.id);
  linkEl = el;
  previewTooltipAjax = new ajax();
  previewTooltipAjax.successCallback = previewTooltipResponse;
  var data = "ajaxAction=getPreviewTooltip&table=" + encodeURIComponent(table) + "&id=" + id;
  previewTooltipAjax.request(pathBase + "ajax.php", data);
}

function previewTooltipResponse() {
  if (tooltipText=="") return;
  var tooltipText = previewTooltipAjax.getSimpleResponse();
  if (typeof tooltipArray[linkEl.id] == "undefined" || tooltipArray[linkEl.id] == false) return;
  var tooltipDiv = document.createElement("div");
  addClass(tooltipDiv, 'tooltip');
  tooltipDiv.style.marginLeft = MSIE ? "-40px" : "4px";
  tooltipDiv.style.width = "400px";
  tooltipDiv.name = "tooltipDiv";
  tooltipDiv.innerHTML = tooltipText;
  linkEl.appendChild(tooltipDiv);
}

function removeTooltip(buttonEl) {
  try { tooltipUnregister(buttonEl.id); } catch (e) {}
  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 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 setDisplayMode (mode, idString, parent) {
  idCollection = idString.split(",");
  for (count in idCollection) {
    if (parent) {
      try {
        document.getElementById(idCollection[count]).parentNode.style.display = mode;
      } catch (e) {}
    } else {
      document.getElementById(idCollection[count]).style.display = mode;
    }
  }
}

// functions for tagging

function categorySelectChange(el) {
  catSelEl = el;
  if (el.value=="pleaseselect") {
    return false;
  } else if (el.value=="newcat") {
    promptModal(categorySelectProcess, getLang('lang_setnewcategory'), '');
  } else {
    categorySelectProcess(el.value);
  }
}

function categorySelectProcess(storeValue) {
  if (storeValue == null || storeValue == "") return false;
  if (ajaxAction[catSelEl.form.name] == "") return false;
  formAjax = new ajax();
  formAjax.successCallback = categorySelectResponse;
  field = catSelEl.name.match(/\[(.*)\]$/);
  data = ajaxRequestBase[catSelEl.form.name] + '&field=' + field[1]
           + '&storeValue=' + encodeURIComponent(storeValue);
  formAjax.request(ajaxRequestURL[catSelEl.form.name], data);
}

function categorySelectResponse() {
  result = formAjax.getSimpleResponse();
  catSelEl.value = result;
  addSelectOption(catSelEl.id, result, result);
  setPreSelection(catSelEl.id, result);
}

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) {
  itemlistAddEl = el; storeFieldK = storeField; listItemFieldK = listItemField;
  prefixK = prefix; tableK = table; idK = id;
  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;
  processListItemAction("addListItem", storeValue, storeFieldK, listItemFieldK, prefixK, tableK, idK);
  itemlistAddEl.value = "pleaseselect";
}

function listitemDelete(el, delValue, storeField, listItemField, prefix, table, id) {
  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);
  searchLink = document.getElementById(listItemField + "SearchLink").value;
  var data = "ajaxAction=" + listItemAction
               + "&field=" + encodeURIComponent(storeField) 
               + "&listItemField=" + encodeURIComponent(listItemField)
               + "&prefix=" + prefix + "&table=" + encodeURIComponent(table) + "&id=" + id 
               + "&storeValue=" + encodeURIComponent(storeValue)
               + "&listitems=" +  encodeURIComponent(itemlistSpanEl.innerHTML);
  if (searchLink != "") data += "&searchLink=" + encodeURIComponent(listItemField);
  formAjax.request("ajax.php", data);
}

function itemListSearch(phrase, fieldname) {
  searchLink = document.getElementById(fieldname + "SearchLink").value;
  location.href = searchLink + phrase;
}

function processResponseItemlist() {
  itemlistSpanEl.innerHTML = formAjax.getSimpleResponse();
}

// functions for searching and selecting

function ajaxSearchLink(tempTable, tempField, tempTerm) {
  searchAction = "simpleSearch"; searchTable = tempTable;
  searchField = tempField; searchTerm = tempTerm;
  searchAjax = new ajax();
  searchAjax.successCallback = searchResponse;
  var data = "ajaxAction=simpleSearch&searchTable=" + encodeURIComponent(searchTable)
               + "&searchField=" + encodeURIComponent(searchField)
               + "&searchTerm=" + encodeURIComponent(searchTerm);
  searchAjax.request(pathBase + "ajax.php", data);
}

function ajaxSearch(mode, refObj) {
  if (typeof(refObj) == "undefined") refObj = "";
  searchAction = mode;
  searchAjax = new ajax();
  searchAjax.successCallback = searchResponse;
  try { searchTable = document.getElementById(mode + 'Table').value;
  } catch (e) { searchTable = "" }
  try { searchField = document.getElementById(mode + 'Field').value;
   } catch (e) { searchField = "" }
  try { searchTerm = document.getElementById(mode + 'Term').value;
   } catch (e) { searchTerm = "" }
  var data = "ajaxAction=" + searchAction + "&searchTable=" + encodeURIComponent(searchTable)
               + "&searchField=" + encodeURIComponent(searchField)
               + "&searchTerm=" + encodeURIComponent(searchTerm) + "&refObj=" + refObj;
  searchAjax.request(pathBase + "ajax.php", data);
}

function searchResponse () {
  error = searchAjax.getSimpleResponse();
  if (error=="syntaxerror") {
    alertModal(emptyFunction, getLang("lang_sqlsyntaxerror"));
  } else if (error=="unknownColumn") {
    alertModal(emptyFunction, getLang("lang_sqlunknowncolumn"));
  } else {
    location.href = pathMain + "searchAction=" + searchAction
                      + "&searchTable=" + encodeURIComponent(searchTable)
                      + "&searchField=" + encodeURIComponent(searchField)
                      + "&searchTerm=" + encodeURIComponent(searchTerm);
  }
}

function setRank (elAction, refObj) {
  if (typeof(refObj) == "undefined") refObj = "";
  if (elAction=='selectRank') var rank = prompt(getLang('lang_setnewrank'),'');
  setRankAjax = new ajax();
  setRankAjax.successCallback = setRankResponse;
  var data = "ajaxAction=setElement&action=" + elAction + "&refObj=" + refObj + (rank ? "&rank=" + rank : "");
  setRankAjax.request(pathBase + "ajax.php", data);
}

function setRankResponse () {
  setElement(setRankAjax.getComplexResponse());
}

function setElement(result) {
  nextId    = result.getElementsByTagName('id')[0].childNodes[0].nodeValue;
  nextTable = result.getElementsByTagName('table')[0].childNodes[0].nodeValue;
  if (nextTable=="none") {
    location.href =  pathMain;
  } else {
    data = pathMain + "table=" + encodeURIComponent(nextTable) + "&id=" + nextId;
    location.href =  data;
  }
}

// close and open editors

function openEditor(contentLocalId, toolbarLocalId, elementLocalTable, elementLocalId, language) {
  openedEditorLanguage = (typeof(language) == "undefined") ? "": language;
  contenteditorId = contentLocalId;
  noneditToolbarId = toolbarLocalId;
  elementTable = elementLocalTable;
  elementId = elementLocalId;
  getContentAjax = new ajax();
  getContentAjax.successCallback = openEditorResponse;
  var data = "ajaxAction=getEditableContent&language=" + openedEditorLanguage
               + "&table=" + encodeURIComponent(elementTable) + "&id=" + elementId;
  getContentAjax.request(pathBase + "ajax.php", data);
}

function openEditorResponse() {
  var result = getContentAjax.getTextResponse();
  var contenteditorEl = document.getElementById(contenteditorId);
  contenteditorEl.innerHTML = result;
  if (tinyMCE.getInstanceById(contenteditorId) == null) {
    tinyMCE.execCommand('mceAddControl', false, contenteditorId);
    document.getElementById(noneditToolbarId).style.display = 'none';
  }
}

function closeEditor(id, idNoneditToolbar) {
  if (tinyMCE.getInstanceById(id) != null) {
    tinyMCE.execCommand('mceRemoveControl', false, id);
    document.getElementById(idNoneditToolbar).style.display = 'block';
  }
}

function openEditorCard(needle) {
  contentEditorId = "contenteditor_" + needle;
  if (tinyMCE.getInstanceById(contentEditorId) == null) {
    tinyMCE.execCommand('mceAddControl', false, contentEditorId);
  }
}

mceSaveCallback = function () {};
mceAlertSaveCallback = function () {};

function openFormEditor(contentEditorId, saveIcons, height) {
  if (tinyMCE.getInstanceById(contentEditorId) == null) {
    tinyMCE.execCommand('mceAddEditor', false, contentEditorId);
    try {
      document.getElementById('mce_editor_0').style.height = height + "px";
    } catch (e) {}
    if (typeof(saveIcons)=="undefined" || saveIcons != "displaySaveIcons") {
      document.getElementById('mce_editor_0_save').style.display = "none";
      document.getElementById('mce_editor_0_cancel').style.display = "none";
    } 
  }
}

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 {
          var inst = tinyMCE.getInstanceById(div.id);
          content = inst.getHTML();
        } catch (e) {
          try {
            content = div.innerHTML;
          } catch (e) {}
        }
        contentData += "&storeValue[" + saveNeedle[1] + "]=" +  encodeURIComponent(content);
      }
    } catch (e) {}
  }
  return contentData;
}

// language related

function chooseLanguage(language) {
  if (location.href.match(/index\.php/)) {
    location.href = "index.php?lang=" + language;
  } else if (location.href.match(/install\.php/)) {
    location.href = "install.php?lang=" + language;
  } else if (location.href.match(/registration\.php/)) {
    var arguments = ((location.search != "") ? location.search +  "&" : "?") + "lang=" + language;
    location.href = location.href + arguments;
  } else {
    setLanguageAjax = new ajax();
    setLanguageAjax.successCallback = setLanguageResponse;
    var data = "ajaxAction=setLanguage&language=" + language;
    setLanguageAjax.request(pathBase + "ajax.php", data);
  }
}

function setLanguageResponse () {
  location.reload();
}

// 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":
      // Do custom cleanup code here
      break;
      case "insert_to_editor":
        if (value=="") value='<p class="p">&nbsp;</p>';
      break;
      case "get_from_editor_dom":
        // Do custom cleanup code here
      break;
      case "insert_to_editor_dom":
        // Do custom cleanup code here
      break;
  }
  return value;
}

// routines for datePicker

function pickDate(id, absTop, formName) {
  var addArgs = 'date=' + encodeURIComponent(document.getElementById(id).value);
  if (typeof absTop != "undefined") addArgs += '&absTop=' + absTop;
  openPopupWindow('datePicker', 'datePicker', addArgs);
  updateDateId = id;
  ajaxDateFormName = formName;
  windowResponseFunction = new Function("date", "updateDateInput(date);");
  windowResponseInterval = window.setInterval("testWindowResponseValue();", 200);
}

function updateDateInput(date) {
  document.getElementById(updateDateId).value = date;
  formChange (ajaxDateFormName, document.getElementById(updateDateId));
}

function selectDate(year, month, day) {
  var date = year + "-" + month + "-" + day;
  closeTopWin("datePicker", date);
}

// routines for colorPicker

function pickColor(id, color, absTop, formName) {
  var addArgs = 'color=' + encodeURIComponent(color);
  if (typeof absTop != "undefined") addArgs += '&absTop=' + absTop;
  openPopupWindow('colorPicker', 'colorPicker', addArgs);
  updateColorId = id;
  ajaxColorFormName = formName;
  windowResponseFunction = new Function("color", "updateColorInput(color);");
  windowResponseInterval = window.setInterval("testWindowResponseValue();", 200);
}

function updateColorInput(color) {
  document.getElementById(updateColorId + '_colorField').style.backgroundColor = color;
  document.getElementById(updateColorId).value = color;
  formChange (ajaxColorFormName, document.getElementById(updateColorId));
}

function selectColor(id) {
  var color = document.getElementById("selectedColorBox").value;
  closeWin(id, color);
}

function showColor(color) {
  document.getElementById("selectedColor").style.backgroundColor = color;
  document.getElementById("selectedColorBox").value = color;
}

function convertRGBToHex(col) {
  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 "rgb(" + r + "," + g + "," + b + ")";
  }
  return col;
}

// 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) {
  selectObj.options.length = 0;
  for (var i = 0; i < valuesArray.length; i++ ) {
    var code = valuesArray[ i ];
    var opt = new Option(code, 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 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 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 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 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 addClass (el, className) {
  try {
    removeClass(el, className);
    el.className += " " + className;
  } catch (e) {}
}

function Element (table, id, link) {
  newLink = link;
  deleteElementAjax = new ajax();
  deleteElementAjax.successCallback = deleteElementResponse;
  var data = "ajaxAction=deleteElement&table=" + table + "&id=" + id;
  deleteElementAjax.request(pathBase + "ajax.php", data);
}

function deleteElementResponse() {
  location.href = newLink;
}

// This is variable for storing callback function
top.modalCallback = emptyFunction;

function initiateModal (callback, text) {
  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('modalText').innerHTML = text;
  top.document.getElementById('modalResponse').style.display = 'none';
  top.document.getElementById('modalResponse').value = "";
  top.document.getElementById('okModalBut').style.display = 'none';
  top.document.getElementById('cancelModalBut').style.display = 'none';
  top.document.getElementById('yesModalBut').style.display = 'none';
  top.document.getElementById('noModalBut').style.display = 'none';
}

// This is replace alert function it saves function callback and sets up dialog with an ok button
function alertModal (callback, text, height) {
  initiateModal (callback, text);
  top.document.getElementById('okModalBut').style.display = 'inline';
  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, text, standardValue) {
  initiateModal (callback, text);
  top.document.getElementById('okModalBut').style.display = 'inline';
  top.document.getElementById('cancelModalBut').style.display = 'inline';
  top.document.getElementById('modalResponse').style.display = 'block';
  top.document.getElementById('modalResponse').value = standardValue;
  top.document.getElementById('modalResponse').focus();
  top.document.getElementById('modalResponse').select();
}

// This is replace confirm function it saves function callback and sets up dialog with yes/no buttons
function confirmModal(callback, text, height) {
  initiateModal (callback, text);
  top.document.getElementById('yesModalBut').style.display = 'inline';
  top.document.getElementById('noModalBut').style.display = 'inline';
  top.document.getElementById('yesModalBut').focus();
}

function modalKeypress(e) {
  if ((e.keyCode==10) || (e.keyCode==13)) modalClick(1);
  if (e.keyCode==27) modalClick(0);
}

function modalClick(response) {
  try {
    top.document.getElementById('modalIframeFrame').style.display = 'none';
  } catch (e) {};
  top.document.getElementById('modalFrame').style.display = 'none';
  top.document.getElementById('modalDiv').style.display = 'none';
  if (top.document.getElementById('modalResponse').style.display == 'block') {
    top.modalCallback(response ? (document.getElementById('modalResponse').value) : null);
  } else {
    top.modalCallback(response ? true : false);
  }
}


