/**
* Sammeldatei für nachträglich nötig gewordene Funktionen
* Derzeitiger Inhalt:
* - Kontrollfunktion für Formularfelder
* - (veränderte!) Anleihen aus dhtml.js
* - Korrekturfunktion für Höhe d. rechten Spalte
* - onLoad-Funktion "doOnPageReady()"
*/
var EA, undefined, tmpObj, tmpStr, tmpArr;

var ENV = {
  app : new Object()
}

var MPOT = {
  Cache : {
    LastCss : null
  },
  documentStarted : false,
  documentInitialized : false,
  onDocStart : new Array(),
  onBeforeInit : new Array(),
  onInitDone : new Array()
}

function noop() {;}

function notUndef(obj) {
  return typeof obj != "undefined";
}

MPOT.solveOptions = function(str) {
  var q, k, erg, arr, ar2;
  erg = new Object();
  if(typeof str == "string") {
    arr = str.split(",");
    for(q=0; q<qrr.length; q++) {
      ar2 = arr[q].split("=");
      k = ar2[0].trim();
      if(k) {
        if(k.charAt(0)=="!" || k.charAt(0)=="-" || k.charAt(0)=="+") {
          k = k.slice(1);
          if(k.length) {
            if(k.charAt(0)=="+") erg[k] = "true";
            else erg[k] = "false";
          }
        }
        erg[k] = ar2.slice(1).join("=");
        if(erg[k].toLowerCase()=="true") erg[k] = true;
        if(erg[k].toLowerCase()=="false") erg[k] = false;
      }
    }
  }
  return erg;
}

if(!document.getElementById && document.all){
  document.getElementById = function(id){
    return document.all[id];
  }
}

// Browsererkennung ...

EA = ENV.app;

EA.ie4 = document.all ? true : false;
EA.nn4 = document.layers ? true : false;

EA.w3c = (document.getElementById && document.documentElement) ? true : false;
EA.w3cL2 = (EA.w3c && document.createRange && document.addEventListener) ? true : false;

EA.gecko  = navigator.product ? navigator.product.search("Gecko") >= 0 : false;
EA.gecko14comp = (EA.w3cL2 && notUndef(document.designMode) && document.execCommand) ? true : false;
EA.gecko14 = EA.gecko && EA.gecko14comp;

// AppleWebKit:
EA.safari = navigator.userAgent.indexOf("AppleWebKit") >= 0;
EA.safariNative = navigator.userAgent.indexOf("Safari") >= 0;

// KHTML-Engines:
EA.konqNative = navigator.appName == "Konqueror";
EA.konq = EA.konqNative || EA.safari;
EA.khtml = !EA.gecko && (navigator.product ? navigator.product.search("khtml") >= 0 : EA.konq);
// 12.12.2008 Thomas Matysik: Google Chrome Erkennung hinzugefügt:
EA.chrome = navigator.userAgent.indexOf("Chrome") >= 0;

EA.opera = navigator.userAgent.indexOf("Opera") >= 0;

// Gecko-Engines:
EA.moz = !EA.konq && !EA.opera && EA.w3c && EA.gecko; // auch Netsc. 6+ und Epiphany
EA.moz14 = EA.moz && EA.gecko14; // auch Netsc. 7.1 +
EA.kecko = EA.konq && EA.gecko14; // Stand Okt. 04: in Planung -> korrekt?
EA.ffx = EA.gecko14 && navigator.userAgent.indexOf("Firefox") >= 0; // dann auch EA.moz!

if(EA.gecko || EA.khtml || EA.opera) EA.ie4 = false;
else if (EA.ie4) EA.w3c = false;

EA.msie = EA.ie4;

EA.verNum = 0;
EA.revNum = -1;

EA.ie5=false; EA.ie5mac=false; EA.ie52mac=false; // Korrektur im OS-Block
EA.ie55=false; EA.ie6=false; EA.sim_msie=false;
if (EA.ie4) {
  if (document.getElementById) EA.ie5 = true;
  tmpStr = navigator.userAgent || navigator.appVersion;
  tmpArr = tmpStr.match(/\; *MSIE *([\d\.]+) *\;/);
  if (tmpArr.length>1) EA.verNum = parseFloat(tmpArr[1]);
  else EA.verNum = EA.ie5 ? 5.0 : 4.0;
  if(EA.verNum>5.499) EA.ie55 = true;
  if(EA.verNum>5.999) {
    EA.ie6 = true;
    if(document.addEventListener) {
      EA.ie4=EA.ie5=false;
      EA.w3c=EA.w3cL2=true;
    }
  }
}else{
  EA.sim_msie = navigator.appName.indexOf("Internet Explorer") >= 0;
  tmpArr = navigator.userAgent.match(/[ \;]+rv: ?([\d\.]*)/i);
  // EA.revNum
  if(tmpArr && tmpArr[1]) EA.revNum = parseFloat(tmpArr[1].replace(/(\.\d*)\./g,"$1"));
  if(tmpArr && tmpArr[1] && !EA.ffx) EA.verNum = EA.revNum;
  else {
    tmpStr = EA.konqNative?"Konqueror":(EA.safariNative?"Safari":(EA.safari?"AppleWebKit":(EA.ffx?"Firefox":(EA.opera?"Opera":"DUMMY"))));
    tmpRXp = new RegExp(tmpStr+"[\\ \\/]?([\\d\\.]+)","i");
    tmpArr = navigator.userAgent.match(tmpRXp);
    if(tmpArr && tmpArr[1]) {
      EA.verNum = parseFloat(tmpArr[1]);
      if(EA.safari && EA.verNum>45) {
        EA.revNum = EA.verNum;
        switch (Math.floor((EA.verNum-1)/100)) {
          case 0: EA.verNum = EA.verNum>=85 ? 1.0 : 0.8; break;
          case 1: case 2: EA.verNum = EA.verNum<125 ? 1.1 : 1.2; break;
          case 3: EA.verNum = 1.3; break;
          default: EA.verNum = (Math.floor((EA.verNum)/10)-21)/10; // grobe Schaetzung Feb 2006 (aktuell: Safari/417.8) [BNY]
        }
      }
    }
  }
  if(!EA.verNum) EA.verNum = parseFloat(navigator.appVersion);
}

EA.engineType = EA.gecko?"gecko":(EA.msie?"msie":(EA.khtml?"khtml":(EA.opera?"opera":(EA.w3c?"w3c":(EA.nn4?"nn4":"unknown")))));

String.prototype.trim = function() {
  return this.replace(/^\s*/,"").replace(/\s*$/,"");
}

function testFormOnSubmit(form,MfStr,umlOK) {
  // MF steht für Mandatory-Fields-Objekt
  // Beispiel:
  //   MfStr = 'email:Im Feld XY muss eine Mailadresse stehen!:@email|name:Geben Sie einen Namen ein|...'
  // -> Empfehlung: Meldungstext = escape(Meldungstext);
  var arr, arr2, str, flg, RX, erg=true, ergTotal=true, MF, qq, k, outStr="";
  arr = MfStr.split("|");
  MF = new Object();
  for(qq=0; qq<arr.length; qq++){
    arr2 = arr[qq].split(":");
    MF[arr2[0].trim()] = arr2.slice(1).join(':');
  }
  for(k in MF){
    if(typeof form[k]!='undefined'){
      arr = MF[k].split(':');
      if(!arr[1]) arr[1] = "@@string";

      if(form[k].type && (form[k].type=="text"||form[k].type=="textarea")){
        switch(arr[1]){
          case "@@string": RX = /\S+/; break;
          case "@@confirm": RX = /^\s*(JA|J|NEIN|N|YES|Y|NO|N|OUI|O|NON|SI|S)\s*$/i; break;
          case "@@ok": RX = /^\s(JA|J|OK|YES|Y|OUI|O|SI|S)\s$/i; break;
          case "@@email":
            RX = /^[\w\.\-äöüßáéíóúàèìòùâêîôû]+@\w([\w\-äöüßáéíóúàèìòùâêîôû]+\.)+\w{2,5}$/i;
            break;
          case "@@integer": RX = /^[\-\+]?\d+$/; break;
          case "@@number": RX = /^[\-\+]?\d+(\.\d+([Ee][\-\+]?\d+)?)?$/; break;
          case "@@plz": RX = /^\d{5}$/; break;
          case "@@adr": RX = /^\S{2,} .*\d{1,4}\w?$|^(q.{0,7} )?\w\d{1,2}[\,\ ]{0,3}[\d\-]{0,5}$/i; break;
          case "@@zahl": RX = /^[\-\+]?\d+(\,\d+([Ee][\-\+]?\d+)?)?$/; break;
          case "@@menge": RX = /^\d{1,8}$/; break;
          case "@@telefon": RX = /^(\S{1,3}[ \-]{1,3})?[\d\+\-\(\)\[\]\/\ ]*\d{3,}[\d\-\/\ ]*$/; break;
          default:
            str = arr.slice(1).join(':').replace(/^\s*|\s*$/g,"");
            if(str.search(/^\/.+\/[gim]{0,3}$/)!=-1) {
              flg = str.replace(/^\/.+\/([gim]{0,3})$/,"$1");
              str = str.replace(/^\//,"").replace(/\/[gim]{0,3}$/,"");
            } else flg = "i";
            RX = new RegExp(str,flg);
        }
        erg = form[k].value.search(RX)!=-1;
      }

      if(form[k].type && form[k].type=="Checkbox") erg = form[k].checked;

      if(!erg){ // wenn Ergebnis negativ ...
        ergTotal = false;
        outStr += unescape(arr[0]).replace(/\r\n|\n|\r/g,"\\n").replace(/"/g,"''")+"\\n";
      }
    }
  }
  if(!ergTotal){ // wenn Ergebnis negativ ...
    setTimeout('alert("'+outStr+'");',1);
  }
  return ergTotal;
}

function canScroll(win) {
  if(!win) win = window;
  if(win.scrollbars && (typeof win.scrollbars.visible != 'undefined'))
    return win.scrollbars.visible;
  // bezieht sich auf seitlichen Scrollbar ...
  if(document.body) {
    if(typeof document.body.scroll == "string" && document.body.scroll.length)
      return (("yes,auto").indexOf(win.document.body.scroll) > -1);
    if(document.body.offsetWidth && document.body.clientWidth)
      return (Math.abs(win.document.body.offsetWidth - win.document.body.clientWidth) > 6);
    if(win.innerWidth && document.body.clientWidth)
      return (Math.abs(win.innerWidth - win.document.body.clientWidth) > 6);
  }
  return true; // : im "Zweifelsfall"
}

function getWindowWidth(win) {
  var doc;
  if(!win) win = window;
  doc = win.document;
  if (doc.documentElement && doc.documentElement.clientWidth) return doc.documentElement.clientWidth;
  if (win.innerWidth) {
    if(canScroll(win))
      return (bodyClientSize() && doc.body.clientWidth!=win.innerWidth) ?
        doc.body.clientWidth : win.innerWidth-16;
    return win.innerWidth;
  }
  if (doc.body.clientWidth) return doc.body.clientWidth;
  if (doc.body.offsetWidth)
    return doc.body.offsetWidth - (win.canScroll()?16:0);
  return -1; // = nicht gefunden
}

function getSize(node) {
  if(typeof node == "string") node = document.getElementById(node);
  if(node) {
    if (document.layers) {
      if(node.clip) return [ node.clip.width , node.clip.height ];
      if(node.width) return [ node.width , node.height ];
      return [0,0];
    }
    else return [ parseInt(node.offsetWidth.toString()) , parseInt(node.offsetHeight.toString()) ];
  } else return [0,0];
}

function setSize(node,w,h) {
  if(typeof node == "string") node = document.getElementById(node);
  if(node) {
    if(typeof w == "number") {
      if(document.layers) node.clip.width = w;
      else node.style.width = w.toString()+"px";}
    if(typeof h == "number") {
      if(document.layers) node.clip.height = h;
      else node.style.height = h.toString()+"px";}
  }
}

function getPos(node){
  var vati,x=0,y=0;
  if(typeof node == "string") node = document.getElementById(node);
  if(node){
    if(document.layers) {
      if(typeof node.pageX == 'number') return [ node.pageX , node.pageY , node.zIndex ];
      if(typeof node.x == 'number') return [ node.x , node.y , 0 ];
      return [0,0,0];
    }
    else {
      vati = node;
      while (vati) {
        x += vati.offsetLeft; y += vati.offsetTop;
        vati = vati.offsetParent;
      }
      return [ x, y, (node.style && node.style.zIndex) ? node.style.zIndex : 0 ];
    }
  } else return [0,0,0];
}

function setPos(node,X,Y,Z) {
  if(typeof node == "string") node = document.getElementById(node);
  if (typeof X == "number") node.style.left = X.toString()+"px";
  if (typeof Y == "number") node.style.top = Y.toString()+"px";
  if (typeof Z == "number") node.style.zIndex = Z;
}

findLastCss = function () {
  var C = MPOT.Cache, doc, arr, win = window;
  if(!C.LastCss){
   doc = win.document;
   arr = doc.styleSheets || doc.styleSheet;
   if(arr && arr.length) C.LastCss = arr[arr.length-1];
  }
}

function addCssRule(sel,rule) {
  var C = MPOT.Cache, CSS;
  findLastCss();
  CSS = C.LastCss;
  if(CSS) {
    if (CSS.addRule) CSS.addRule(sel,rule);
    else CSS.insertRule(sel+"{"+rule+"}",CSS.cssRules.length);
  }
}

function openPopup(type,url) {
   var breit, hoch, X0, Y0, str, Korrektur=25;
   switch(type) {
     case "100px":
       breit = hoch = 100; X0 = Y0 = 10;
       break;
     case "full":
       breit = screen.availWidth-10; hoch = screen.availHeight-Korrektur;
       X0 = Math.round((screen.availWidth-breit)/2)-10; if (X0<0) X0=0;
       Y0 = Math.round((screen.availHeight-hoch-Korrektur)/2)-15; if (Y0<0) Y0=0;
       break;
     default:
       breit = 400; hoch = 300;
       X0 = Math.round((screen.availWidth-breit)/2)-10; if (X0<0) X0=0;
       Y0 = Math.round((screen.availHeight-hoch-Korrektur)/2)-15; if (Y0<0) Y0=0;
   }
   str = "menubar=no,location=no,directories=no,resizable=yes,scrollbars=yes,toolbar=no,status=yes,";
   str += 'width='+breit+',height='+hoch+',';
   if (document.layers) str += 'screenX='+X0+',screenY='+Y0+',';
   else str += 'left='+X0+',top='+Y0;
   return window.open(url,"YellowMarkerPopup",str,false);
}

MPOT.getSelectedText = function (win) {
  var W = window || win, D, S = null;
  D = W.document;
  if (typeof W.getSelection == 'function') {
    S = W.getSelection();
    if (S && S.toString) return S.toString();
  }
  else if (typeof D.selection != "undefined") {
    S = D.selection;
    if (S && S.createRange) return S.createRange().text || '';
  }
  return '';
}

MPOT.evalWithSelectionText = function (str, inWin) {
  // Als zweites Argument kann ein Bezugsfenster uebergeben werden
  var arr, txt, win = self, host;
  if (inWin && inWin.setTimeout && win.eval) win = inWin;
  host = win.location.protocol+'//'+win.location.host+'/';
  txt = MPOT.getSelectedText (win);
  if (typeof str == 'string') {
    txt = txt.replace(/\s+/g, ' ').replace(/("|')/g, '\\$1');
    // %SEL% wird durch den Selektionstext ersetzt
    // %QSELQ% wird durch den Selektionstext in Anfuehrungszeichen ersetzt ...
    win.eval(str.replace(/%SEL%/g, txt).replace(/%QSELQ%/g, '"'+txt+'"')
      .replace(/%HOST%/g, host).replace(/%SELQUERY%/g, encodeURIComponent(txt)));
  }
}

function doOnPageReady(){
  var node, y, y1, y2, h1, h2, dy, hSoll, get;
  if(get = document.getElementById){
    node = get("LinkeSpalte");
    y1 = getPos(node)[1]+getSize(node)[1];
    node = get("MittlereSpalte");
    y2 = getPos(node)[1]+getSize(node)[1];
    node = get("RechteSpalte");
    hSoll = Math.max(y1,y2) - getPos(node)[1];
    if(hSoll > getSize(node)[1]) node.style.height = hSoll+"px";
  }
}

MPOT.startDocument = function(options) {
  var qq, OPT = MPOT.solveOptions(options);
  if(!MPOT.documentStarted) {
    MPOT.documentStarted = true;
    for(qq=0; qq<MPOT.onDocStart.length; qq++) MPOT.onDocStart[qq]();
  }
}

MPOT.init = function(options) {
  var qq, OPT = MPOT.solveOptions(options);
  if(!MPOT.documentInitialized) {
    if(!MPOT.documentStarted) MPOT.startDocument();
    MPOT.documentInitialized = true;
    for(qq=0; qq<MPOT.onBeforeInit.length; qq++) MPOT.onBeforeInit[qq]();
    // hier ggf. spaetere Initialisierungsfunktionen einfuegen ...
    for(qq=0; qq<MPOT.onInitDone.length; qq++) MPOT.onInitDone[qq]();
  }
}

if(typeof initConfig == "undefined") window.initConfig = MPOT.init;

/**
* Nachfolgend Sondermodul "Textcounter/-längenbegrenzer" für Stadt MH ...
*/


function InputLengthGuard(node) { // Laengenwaechter-Klasse
  var arr, str, osub, CLA = InputLengthGuard, form = node.form, _fn;
  var i = CLA.inst.length;
  var my = CLA.inst[i] = this;
  arr = node.className.match(/\bLenMinMax_(\d+)_(\d+)_?(\w+)?\-?(\S+)?\b/i);
  this.node = node;
  this.form = form;
  this.cnum = i;
  this.min = parseInt(arr[1]);
  this.max = parseInt(arr[2]);
  if(this.max<1) this.max = 1E+10;
  this.mode = arr[3] || "0";
  this.dispName = arr[4] || null;
  this.disp = null;
  if(this.dispName && document.getElementById) this.disp = document.getElementById(this.dispName);
  this.lastContent = node.value.toString();

  this.loopID = setInterval("InputLengthGuard.inst["+i+"].checkMaxAndCount();", 50);

  // nachfolgend wird der Mindestlaengencheck fuer d. einzeln. Felder an d. Formularsubmit gehaengt
  osub = form.onsubmit;
  _fn = form.onsubmit = function(EVT) {
    var OK = my.checkMin(), args = null, osubRtn = true;
    if(typeof arguments != "undefined") args = arguments;
    else if(_fn.arguments) args = _fn.arguments
    if(typeof osub == "function") osubRtn = osub.apply(form, args);
    return OK && ( typeof osubRtn != "undefined" ? osubRtn : true ); // ERST TESTEN
  }
  // else form.onsubmit = my.checkMin;

}

InputLengthGuard.inst = new Array(); // Sammler für die Instanzen

InputLengthGuard.prototype.checkMaxAndCount = function() {
  var node = this.node, dsp = this.disp, str, num;
  var len = node.value.length;
  if(dsp && typeof dsp.innerHTML != "undefined") {
    switch(this.mode.toLowerCase()) {
      case "max":
          str = (this.max - len).toString();
          if(this.max < 1E+9 && dsp.innerHTML != str) dsp.innerHTML = str;
        break;
      case "min":
          num = this.min - len;
          if(num<0) num = 0;
          str = num.toString();
          if(dsp.innerHTML != str) dsp.innerHTML = str;
        break;
      default:
        str = len.toString();
        if(dsp.innerHTML != str) dsp.innerHTML = str;
    }
  }
  if(len > this.max) {
    node.value = this.lastContent;
  }
  this.lastContent = node.value.toString();
}

InputLengthGuard.prototype.checkMin = function() {
  var node = this.node, title="", arr, i, id;
  id = node.id;
  if(!id) id = "";
  if(node.value.length < this.min) {
    if(document.getElementsByTagName) {
      arr = document.getElementsByTagName('label');
      for(i=0; i<arr.length; i++) if(arr[i].htmlFor && arr[i].htmlFor==id) {
        title = '"'+arr[i].innerHTML.replace(/\x3C[^\x3C\x3E]*\x3E/g,' ')+'"';
        break;
      }
    }
    if(title=='' && node.title) title = '"'+node.title+'"';
    if(title=='') title = node.id ? '"'+node.id+'"' : '[ohne Titel]';
    setTimeout("alert('Eingabefeld "+title+" enthält zu wenige Zeichen!');", 10);
    return false;
  } else {
    return true;
  }
}

function startInputLengthGuard() {
  var I, i, G, str="";
  I = new Array();

  I = document.getElementsByTagName('input');
  for(i=0; i<I.length; i++) {
    if(I[i].type.indexOf('text') == 0 &&
       I[i].className.search(/\bLenMinMax_\d+_\d+/i) != -1) G = new InputLengthGuard(I[i]);
  }
  I = document.getElementsByTagName('textarea');
  for(i=0; i<I.length; i++) {
    if(I[i].className.search(/\bLenMinMax_\d+_\d+/i) != -1) G = new InputLengthGuard(I[i]);
  }

}

MPOT.onBeforeInit[MPOT.onBeforeInit.length] = startInputLengthGuard;

function showBmTitle(BmName) {
    BmDiv = document.getElementById('bookmark_service');
    switch (BmName) {
        case 'delicious':
            BmDiv.innerHTML = "Del.icio.us";
        break;
        case 'google':
            BmDiv.innerHTML = "Google";
        break;
        case 'misterwong':
            BmDiv.innerHTML = "Mister Wong";
        break;
        default:
            object_test(BmName);
        break;
    }
}

function hideBmTitle() {
    document.getElementById('bookmark_service').innerHTML = "";
}



