/***************************************************************************
*   ed.wiki 2.0
*   (C) 2005 Daniel Wrana
*   http://www.wissen.selbstlernarchitekturen.info
*   Distributed under the terms of the GNU General Public License v2
****************************************************************************/

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

// reject browsers

function warnEdit() {
  var browser = navigator.userAgent.toLowerCase();
  if (browser.indexOf("opera") != -1) {
    alertWindow("Leider kann der Opera-Browser die Seiten zwar anzeigen, aber nicht "
        + "bearbeiten. Sie können zwar auch eine aktuelle Version des "
        + "Internet-Explorer benutzen. Wir empfehlen Ihnen jedoch den Browser "
        + "Firefox \nhttp://www.mozilla.org/firefox");
    return false;
  }
  if (browser.indexOf("khtml") != -1) {
    alertWindow("Leider können KHTML-Browser wie Konqueror oder Safari "
        + "die Seiten zwar anzeigen, aber nicht im WYSIWYG-Modus bearbeiten.\n"
        + "Dies geht mit IE ab 5.5., Mozilla ab 1.3, Netscape ab 7.1 "
        + "und Firefox ab 6.0. Wir empfehlen Ihnen den Browser Firefox \n"
        + "http://www.mozilla.org/firefox");
    return false;
  }
  if (browser.indexOf("gecko") != -1) {
    if (navigator.productSub < 20030210) {
      alertWindow("Sie brauchen den Mozilla ab 1.3 oder Firefox ab 0.6 oder "
          + "Netscape ab 7.0, um die Seiten zu bearbeiten.\n "
          + "Ihr Browser ist leider veraltet. Bitte machen Sie ein Update.\n"
          + "Wir empfehlen Ihnen den Browser Firefox \n"
          + "http://www.mozilla.org/firefox");
      return false;
    }
  }
  if ((browser.indexOf("msie 5.0") || browser.indexOf("msie 5.1"))!=-1) {
      alertWindow("Sie brauchen den IE mindestens in der Version 5.5 oder einen "
          + "aktuellen Mozilla, Firebird oder Netscape-Browser, "
          + "um die Seiten zu bearbeiten.\n"
          + "Ihr Browser ist leider veraltet. Bitte machen Sie ein Update.\n"
          + "Wir empfehlen Ihnen den Browser Firefox \n"
          + "http://www.mozilla.org/firefox");
      return false;
  }
  return true;
};


// base functions

function addEvent (el, evname, func) {
  if (el.addEventListener) el.addEventListener(evname, func, true);
  else                     el.attachEvent("on" + evname, func);
}

function removeEvent (el, evname, func) {
  if (el.removeEventListener) el.removeEventListener(evname, func, true);
  else                        el.detachEvent("on" + evname, func);
}

function stopEvent (event) {
  if (event.preventDefault) {
    event.preventDefault();
  } else {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
}

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) {
  removeClass(el, className);
  el.className += " " + className;
}

function urlEncode (plaintext) {
  if (typeof(plaintext) == "undefinded") return false;
  // The Javascript escape and unescape functions do not correspond
  // with what browsers actually do...
  var SAFECHARS = "0123456789" + // Numeric
                  "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
                  "abcdefghijklmnopqrstuvwxyz" +
                  "-_.!~*'()"; // RFC2396 Mark characters
  var HEX = "0123456789ABCDEF";

  var encoded = "";
  for (var i = 0; i < plaintext.length; i++ ) {
    var ch = plaintext.charAt(i);
      if (ch == " ") {
        encoded += "+";     // x-www-urlencoded, rather than %20
      } else if (SAFECHARS.indexOf(ch) != -1) {
        encoded += ch;
      } else {
        var charCode = ch.charCodeAt(0);
        if (charCode > 255) {
          alertWindow( "Der Buchstabe '" + ch  + "' konnte nicht erkannt werden. Er ist durch ein Leerzeichen ersetzt worden." );
          encoded += "+";
        } else {
          encoded += "%";
          encoded += HEX.charAt((charCode >> 4) & 0xF);
          encoded += HEX.charAt(charCode & 0xF);
        }
      }
  } // for
  return encoded;
};

// window functions

function getTranslation(text) {
  translationAjax = new ajax();
  translationAjax.successCallback = translationPopup;
  translationAjax.failureCallback = errorPopup;
  translationAjax.request('translation.php',
                          'text=' + text
                        + '&language=' + language
                        + '&langContext='  + langContext);
}

function translationPopup() {
    ajaxHtml = windowAjax.getTextResponse();
    var window = document.createElement("div");
    window.innerHTML = ajaxHtml;
}

function alertWindow (text) {
  alert(text);
  return;
}

function alertBox (title, text, height) {
  var id = 'alert';
  clearWinID(id);
  openPopupWindow('window_alert.php', 'title=' + title + '&text=' + text + '&iconSet=' + iconSet
                + '&height=' + height + '&id=' + id);
}

function helpWindow(content, top, left, width, height) {
  var id = 'help' + urlEncode(content);
  clearWinID(id);
  openPopupWindow('window_content.php', 'ajaxAction=help&content='+content+'&top='+top
                       +'&left='+left+'&width='+width+'&height='+height+'&id='+id);
}

function loginWindow() {
  var id = 'login';
  clearWinID(id);
  openPopupWindow('window_content.php', 'ajaxAction=login&id='+id);
}

function openFile(file, path) {
  var id = 'openfile' + file;
  location.href = 'create_files.php?file=' + file + '&path=' + path;
/*  clearWinID(id);
  openPopupWindow('window_content.php', 'ajaxAction=openFile&file='+file+'&path='+path+'&id='+id);*/
}

function clearWinID(id) {
  winNode = document.getElementById(id + "_main");
  iframeNode = document.getElementById(id + "_iframe");
  if (winNode) winNode.parentNode.removeChild(winNode);
  if (iframeNode) iframeNode.parentNode.removeChild(iframeNode);
}

windowTopIndex = 1000;

function openPopupWindow (url, post) {
  windowTopIndex = windowTopIndex + 2;
  windowAjax = new ajax();
  windowAjax.successCallback = writePopup;
  windowAjax.failureCallback = errorPopup;
  windowAjax.request(url, post + '&zindex=' + windowTopIndex);
}

function writePopup() {
  ajaxHtml = windowAjax.getTextResponse();
  var window = document.createElement("div");
  window.innerHTML = getHtml(ajaxHtml);
  document.getElementsByTagName('body')[0].appendChild(window);
  setJavascript(ajaxHtml);
}

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

function setJavascript (ajaxHtml) {
  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];
  document.getElementsByTagName('head')[0].appendChild(javoScript);
}

function errorPopup() {
  alert('The website the system is calling is not available. Please contact your administator.');
}

function authLogin(crypt) {
    user = document.getElementById('loginuser').value;
    pass = document.getElementById('pass').value;
    if (crypt && crypt=="md5") pass = MD5(pass);
    loginAjax = new ajax();
    loginAjax.successCallback = responseLoginPopup;
    loginAjax.failureCallback = errorPopup;
    loginAjax.request('index.php', 'ajaxAction=loginAuth' + '&user=' + urlEncode(user) + '&pass=' + urlEncode(pass));
}

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

function getFileType(filetype) {
  location.href = pathBase + "create_images.php?filetype=" + filetype;
}

function wikiLink(wikiPageName) {
  location.href = pathBase + "wiki.php?wiki=" + wikiPageName;
}

/* formular functions */

function leaveField (el) {
  removeClass(el, 'sfHover');
}

function hoverField (el) {
  addClass(el, 'sfHover');
}

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

function leaveFieldFile (id) {
  nameField = document.getElementById(id);
  buttonField = document.getElementById(id + 'Button');
  fileField = document.getElementById(id + 'File');
  nameField.value = fileField.value;
  removeClass(nameField, 'sfHover');
  removeClass(buttonField, 'sfHover');
}

function hoverFieldFile (id) {
  nameField = document.getElementById(id);
  buttonField = document.getElementById(id + 'Button');
  fileField = document.getElementById(id + 'File');
  nameField.value = fileField.value;
  addClass(nameField, 'sfHover');
  addClass(buttonField, 'sfHover');
}

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

function formChange (formName, el) {
  if (ajaxAction[formName] == "") return;
  callFormAjax(el, 'standard', ajaxRequestURL[formName], ajaxRequestBase[formName]);
}

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

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

function callFormAjax (el, mode, url, basedata) {
  formAjax = new ajax();
  if (mode=='boolean') {
    formAjax.successCallback = processResponseBoolean;
  } else if (mode=='radio') {
    formAjax.successCallback = processResponseRadio;
  } else {
    formAjax.successCallback = processResponse;
  }
  formAjax.failureCallback = showError;
  ajaxEle = el;
  if (mode=='radio') {
    field = ajaxEle.name;
  } else {
    field = ajaxEle.name.match(/\[(.*)\]$/);
    field = field[1];
  }
  if (field[1]=='passKlar') {
    var passKlar = document.getElementById('passKlar').value;
    var storeValue = (passKlar=='') ? '' : MD5(passKlar);
    var sendField = 'pass';
  } else if (mode=='boolean') {
    var sendField = field;
    var storeValue = (ajaxEle.value=='TRUE' ? 'FALSE' : 'TRUE');
  } else if (mode=='radio') {
    var sendField = field;
    var storeValue = ajaxEle.id.split("_")[1];
  } else {
    var storeValue = ajaxEle.value;
    ajaxEle.value = 'Updating...';
    var sendField = field;
  }
  data = basedata + '&field=' + sendField + '&storeValue=' + storeValue;
  formAjax.request(url, data);
}

function processResponseRadio() {
  toggleRadio(ajaxEle);
}

function processResponse() {
  result = formAjax.getSimpleResponse();
  if (field[1]!='passKlar') {
    ajaxEle.value = (result || result == "") ? result : storeValue;
  }
}

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 showError(formAjax) {
  errorPopup();
  ajaxEle.value = storeValue;
}

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

function doSubmitForm (obj, formularName, crypt) {
  var submit = true;
  if (window.XMLHttpRequest) {
    selects = document.getElementsByTagName('select');
    for(var i = 0; i < selects.length; i++) {
      if (selects[i].value=='pleaseselect') {
        alert('Bitte waehlen Sie in den Auswahlfeldern eine Angabe aus');
        submit = false;
        break;
      }
    }
  }
  email = document.getElementById('valuesemail');
  if (email != null && email.value == '') {
    alert('Bitte geben Sie eine Emailadresse an');
    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 = '';
      }
    }
    var value = (typeof(obj.val) == 'undefined') ? obj.value : obj.val;
    document.getElementById('submitAction').value = value;
    document.getElementById(formularName).submit();
  }
}

/* grid - functions */
function gridBooleanChange(el) {
  ele = el;
  alert(ajaxEle.data);
}

function gridAction(el, action, id, value1) {
  if (action == "download") {
    openFile(id, value1);
  } else if (action == "select") {
    selectEntry(id);
  }
}

function confirmQuestion (question, link) {
   result = confirm(question);
   if (result) document.location = link;
}

function confirmDelete (target, text) {
   result = confirm(text);
   if (result) location.href = target;
}

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

function literatur (shorty) {
    lit = window.open(pathBase + "literatur.php?shorty=" + shorty,
                            "Literaturfenster",
                            "width=400, height=100, left=30, top=30, dependent=yes, "
                            + "menubar=no");
    lit.focus();
}

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

function printVersion (target, page) {
   page = page.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,"");
   page = page.replace(/\?/g,"");
   page = page.replace(/\!/g,"");
   page = 'print' + page.replace(/\s/, '');
   print = window.open(target, page, 'top=20,left=20,width=900,height=600,'
                                    +'menubar=yes, scrollbars=yes');
   print.focus();
}

function confirmDeleteFile(confirmMsg) {
  return (confirm(confirmMsg)) ? true : false;
}

