var ns = (document.layers) ? true : false;
var ie  = (document.all) ? true : false;
var ns6 = (document.getElementById && !document.all) ? true : false;

var datepickerDefaultOpts = 
  {
  // the jquery datepicker has a rather special date format syntax.
  // see "http://docs.jquery.com/UI/Datepicker/formatDate"
  // for example the date format "dd.mm.yy" corresponds to the standard java dateformat "dd.MM.yyyy"
  dateFormat: 'dd.mm.yy',
  yearRange: '1900:2099',
  changeMonth: true,
  changeYear: true,
  firstDay: 1,
  monthNames:['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
  monthNamesShort: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
  dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
  dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
  dayNamesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
  };

function clickIE()
  {
  if (ie)
    {
    (message);
    return false;
    }
  }

function clickNS(ev)
  {
  if (ns||(document.getElementById&&!ie))
   	{
		if (ev.which==2||ev.which==3)
			{
			(message);
			return false;
			}
   	}
  }

function ignore()
  {
  return false;
  }

function ignoreOk()
  {
  return true;
  }

/*
if (ns)
	{
	document.captureEvents(Event.MOUSEDOWN);
	document.onmousedown=clickNS;
	}
else
	{
	document.onmouseup=clickNS;
	document.oncontextmenu=clickIE;
	}
document.oncontextmenu = ignore;
*/

//------------------------------------------------------------------------------------
function isNumeric (text)
	{
	if (text.length == 0)
		return false;
	var ziffern="0123456789";
	for (var i=0; i < text.length; i++)
		{
		var c = text.charAt(i);
		if (ziffern.indexOf(c) == -1)
			return false;
		}
	return true;
	}

/*-------------------------------------------------------------------------------------
 * replaces the content of the element with id which with the text
 */
function replaceText (which, text)
	{
	if (ie)
	  {
	  var el = document.getElementById(which);
  	if ( el == null || el == "undefined" )
  	  return;
  	el.innerHTML = text;
	  }
	else if (ns6)
		{
		var over = document.getElementById([which]);
  	if ( over == null || over == "undefined" )
  	  return;
		var range = document.createRange();
		range.setStartBefore(over);
		var frag = range.createContextualFragment (text);
		while (over.hasChildNodes())
			{
			over.removeChild(over.lastChild);
			}
		over.appendChild (frag);
		}
	else
	  {
		document[which].document.write(text);
		document[which].document.close();
		}
	}

/*-------------------------------------------------------------------------------------
 * omits spaces on beginning and end of the text
 */
function trim(text)
  {
  while (text.length>0 && text.charAt(0)==' ')
    text = text.substring(1,text.length);
  while (text.length>0 && text.charAt(text.length-1)==' ')
    text = text.substring(0,text.length-1);
  return text;
  }

/*-------------------------------------------------------------------------------------
 * obtain the content of an element with the id which
 */
function getContentById (which)
	{
	if (ie)
    {
	  var el = document.getElementById(which);
  	if ( el == null || el == "undefined" )
  	  return "";
	  return el.innerText;
	  }
	else if (ns6)
		{
		var el = document.getElementById([which]);
  	if ( el == null || el == "undefined" )
  	  return "";
		return el.firstChild.nodeValue;
		}
	else
	  {
		return document[which].document;
		}
	}

//----------------------------------------------------------------------------------
function z2 (num)
	{
  var txt = "00" + num;
  return txt.substr (txt.length - 2, 2);
  }

//----------------------------------------------------------------------------------
function z4 (num)
	{
  var txt = "0000" + num;
  return txt.substr (txt.length - 4, 4);
  }

//----------------------------------------------------------------------------------
function addYear (myDate)
  {
  var originalMonth = myDate.getMonth ();
  myDate.setFullYear (myDate.getFullYear () + 1) ;
  if (myDate.getMonth () > originalMonth)
    myDate.setDate (0);
  }

function toDate (text)
	{
  var date = toDateObject (text);
  if (date == null)
    return "";
  else
    {
    var dd = date.getDate();
    var mm = date.getMonth() + 1;
    var yy = date.getFullYear();
    return "" + z2(dd) + "." + z2(mm) + "." + z4(yy);
    }
  }

function toDateObject (text)
  {
  if (text.length < 1)
		return null;

	var dd = 0;
	var mm = 0;
	var syy = "";
	var yy = 0;

	var da = text.split(".");
	if (da.length == 1)
	  {
	  var c = text.substr(0,1);
	  if (c == "+" || c == "-")
	    {
	    var diff = parseInt (text.substr(1), 10);
	    if (isNaN(diff))
	      diff = 0;
	    if (c == "-")
	      diff = - diff;
	    var date = new Date();
	    date.setTime (date.getTime() + diff * 24*60*60*1000);
	    return date;
	    }
	  if (text.length >= 6)
	    {
	    text = text.substr(0,2) + "." + text.substr(2,2) + "." + text.substr(4);
	    da = text.split(".");
	    }
	  else if (text.length > 4)
	    {
	    text = text.substr(0,2) + "." + text.substr(2);
	    da = text.split(".");
	    }
	  else if (text.length == 4)
	    {
	    text = "01.01." + text;
	    da = text.split(".");
	    }
	  }
	if (da.length < 2 || da.length > 3)
	  return null;

  dd = parseInt (da[0], 10);
 	mm = parseInt (da[1], 10);
 	if (da.length == 3)
	  {
	  syy = da[2];
  	yy = parseInt (syy, 10);
  	if (syy.length == 2)
  	  {
  	  syy = '20' + syy;
  	  yy = parseInt (syy, 10);
  	  if (yy - (new Date()).getFullYear() > 20)
  	    yy -= 100;
  	  }
    else if (isNaN(yy))
      yy = (new Date()).getFullYear();
	  }
  else
	  {
    yy = (new Date()).getFullYear();
	  }

	if (isNaN(dd) || isNaN(mm) || isNaN(yy))
		return null;
	if (dd < 1 || dd > 31 || mm < 1 || mm > 12 || yy < 1900)
	  return null;
	if (dd > 30 && (mm == 4 || mm == 6 || mm == 9 || mm == 11))
	  return null;
	if (mm == 2 && (dd > 29 || dd == 29 && !isLeap(yy)))
	  return null;

  return new Date (yy, mm - 1, dd);
	}

//----------------------------------------------------------------------------------
function toTime (text)
	{
	if (text.length < 1)
		return "";

	var hh = 0;
	var mm = 0;
	var ss = -1;

	var da = text.split(":");
	if (da.length == 1)
	  {
	  if (text.length == 4)
	    {
	    text = text.substr(0,2) + ":" + text.substr(2,2);
	    da = text.split(":");
	    }
	  else if (text.length == 3)
	    {
	    text = "0" + text.substr(0,1) + ":" + text.substr(1);
	    da = text.split(":");
	    }
	  else if (text.length <= 2)
	    {
	    text = text + ":00";
	    da = text.split(":");
	    }
	  }
	if (da.length == 3)
   	ss = parseInt (da[2], 10);
	else if (da.length != 2)
	  return "";

  hh = parseInt (da[0], 10);
 	mm = parseInt (da[1], 10);

	if (isNaN(hh) || isNaN(mm))
		return "";
	if (hh < 0 || hh > 23 || mm < 0 || mm > 59)
	  return "";
	return "" + z2(hh) + ":" + z2(mm) + ((!isNaN(ss)  &&  ss >= 0) ? (":" + z2(ss)) : "");
	}

//-------------------------------------------------------------------------------------
function isLeap (year)
	{
	if (year % 4 != 0)
	  return false;
	if (year % 100 != 0)
	  return true;
	if (year % 400 == 0)
	  return true;
	return false;
	}

//-------------------------------------------------------------------------------------
function OnlyNumber ()
	{
	if (event.keyCode < 45 || event.keyCode > 57)
		event.returnValue = false;
	}

//-------------------------------------------------------------------------------------
function init_form ()
	{
	if (typeof on_init != "undefined")
	  on_init();
	if (document.forms.length > 0)
	  {
    var frm = getEhypForm();
		for (var i = 0; i < frm.elements.length; i ++)
		  {
		  var el = frm.elements[i];
		  if (el.type != "hidden" && !el.disabled && el.style.display != "none")
		    {
		    el.focus();
		    break;
		  	}
		  }
		}
	if (typeof on_focus_init != "undefined")
	  on_focus_init();
	}

//-------------------------------------------------------------------------------------

var lastFocusElement;
var lastFocusElementFailed = false;

function fc (name, pattern, validator)
  {
  lastFocusElementFailed = false;
  var fld = firstInput (name);
  unmarkError (fld);
  if (pattern != "")
    reformat (fld, pattern);
  if (validator && typeof triggerValidation != "undefined")
    triggerValidation (fld, validator);
  }

function fieldFocus (name)
  {
  var fld = firstInput (name);
  if (lastFocusElementFailed)
    lastFocusElement.focus ();
  else
    lastFocusElement = fld;
  }

function setCheck (el, name)
  {
  var hid = firstInput (name);
  hid.value = (el.checked) ? "on" : "off";
  }

function reformat (fld, frmt)
  {
  var val = fld.value;
  if (val == "")
    return;
  /*
   * In Date validation we do not erase an erroneous input, but
   * leave it unchanged to alert the user later on.
   */
  if (frmt.substr(0,1) == "^")
    reformatSpecial (fld, val, frmt);
  else if (frmt != "")
    {
    var f = new Formatter (frmt);
    fld.value = f.format (f.parse (val));
    }
  }


function reformatSpecial (fld, val, frmt)
  {
  if (frmt.substr(0,2) == "^H")
  	{
  	var tmpTime = toTime(val);
  	if (tmpTime != "")
  		fld.value = tmpTime;
  	else
  	  alert( "Bitte geben Sie die Uhrzeit in der Form HH:MM ein." );
  	}
  else if (frmt.substr(0,2) == "^d")
  	{
  	var sepPos = frmt.indexOf (" H"); //separates date and time
  	if (sepPos != -1)
  	  {
  	  var frmtDate = frmt.substr (0, sepPos);
  	  var frmtTime = "^d" + frmt.substr (sepPos+1,frmt.length);
  	  sepPos = val.indexOf (" ");
  	  if (sepPos == -1)
  	    {
  	    alert( "Bitte geben Sie Datum und Uhrzeit in der Form " + frmt.substr (2, 99) + " ein." );
  	    return;
  	    }
  	  var valDate = val.substr (0, sepPos);
  	  var valTime = val.substr (sepPos+1,val.length);
      fld.value = valDate;
      reformat (fld, frmtDate);
      valDate = fld.value;
      if (valDate != "")
        {
        fld.value = valTime;
        reformat (fld, frmtTime);
        valTime = fld.value;
        if (valTime != "")
          fld.value = valDate + " " + valTime;
        else
          fld.value = "";
        }
      return;
  	  }

    var sfrm = frmt.substring(2, frmt.length);
    if (sfrm == "HH:mm"  ||  sfrm == "HH:mm:ss")
    	{
	  	var tmpTime = toTime(val);
	  	if (tmpTime != "")
	  		fld.value = tmpTime;
	  	else
	  	  alert( "Bitte geben Sie die Uhrzeit in der Form HH:MM ein." );
    	}
    else if (sfrm == "MM.yyyy")
    	{
    	var tmpDate = toDate("01." + val);
    	if (tmpDate != "")
    		fld.value = tmpDate.substring(3, tmpDate.length);
    	else
    		{
    		fld.value = repairDate (fld, "01." + val);
    		}
    	}
  	else
  		{
  		var tmpDate = toDate (val);
    	if (tmpDate != "")
    		fld.value = tmpDate;
    	else
    		{
    		fld.value = repairDate (fld, val);
    		}
    	}
  	}
  else if (frmt.substr(0,2) =="^R")
    {
    if(window.RegExp)
      {
      var regexp = new RegExp(frmt.substring(2, frmt.length), "g");
      var a = regexp.exec(val);
      if(a && a != "undefined")
        fld.value=a[0];
      else
        fld.value="";
      }
    }
  else if (frmt.substr(0,5) =="^blzf")
  	{
  	// BLZ formatter
		val = val.split(" ").join("");
  	if (window.RegExp)
  		{
  		// Browser knows regular expressions
	  	var regexp = new RegExp(frmt.substring(5, frmt.length), "g");
			while (val.length < 8)
				val = "0" + val;
			var a = regexp.exec(val);
	  	if (a && a != "undefined")
	  		{
				if (a.length > 8)
					a = a.substring (0,8);
				fld.value=a[0];
				}
	  	else
	  		fld.value="";
	  	}
		}
  else if (frmt.substr(0,4) =="^blz")
  	{
  	// BLZ formatter
		val = val.split(" ").join("");
  	if (window.RegExp)
  		{
  		// Browser knows regular expressions
	  	var regexp = new RegExp(frmt.substring(4, frmt.length), "g");
			var a = regexp.exec(val);
			if (a && a != "undefined")
	  		{
				if (a.length > 8)
					a = a.substring (0,8);
				fld.value=a[0];
				}
			else
	  		fld.value="";
	  	}
	  else
	  	{
	  	// browser doesn't know regular expressions
			while (val.length < 8)
				val = "0" + val;
			if (isNaN(val))
				fld.value="";
			else
				fld.value=val;
	  	}
  	}
  else if (frmt =="^phone")
  	fld.value = normalizePhoneNo (val);
  else if (frmt.substr(0,2) =="^z")
  	{
	  // zip formatter
  	if(window.RegExp)
  		{
  		// Browser knows regular expressions
	  	var regexp = new RegExp(frmt.substring(2, frmt.length), "g");
			while (val.length < 5)
				val += "0";
			var a = regexp.exec(val);
	  	if(a && a != "undefined")
	  		fld.value=a[0];
	  	else
	  		fld.value="";
	  	}
	  else
	  	{
	  	// browser doesn't know regular expressions
			while (val.length < 5)
				val += "0";
			if (isNaN(val))
				fld.value="";
			else
				fld.value=val;
	  	}
  	}
  else if (frmt.substr(0,3) =="^fn")
  	{
	  fld.value = goodFirstname (val);
  	}
  else if (frmt.substr(0,3) =="^ln")
  	{
	  fld.value = goodLastname (val);
  	}
  }

function normalizePhoneNo (number)
  {
  number = number.replace(/^\+\+49/,"");
  number = number.replace(/^\+49/,"");
  number = number.replace(/^0049/,"");
  number = number.replace(/^00/,"+");
  number = number.replace(/^\+\+/,"+");
  number = number.replace(/^\ /,"");
  number = number.replace(/^\(\0\)/,"0");
  number = number.replace(/^\ /,"");
  number = number.replace(/^\(([0-9]+)\)/,"$1");
  if (number.indexOf("0") != 0 && number.indexOf("+") != 0)
  	number = "0" + number;
  return number;
  }
  
	
/*-------------------------------------------------------------------------------------
 * Validates the named fields content according to a regular expression
 * specified in frmt (with prefix ^r)
 * returns false if validation fails!
*/
function validateToRegexp(name, frmt)
	{
	var el = firstInput(name);
	var val = el.value;
	if(window.RegExp && val != "" && frmt.substring(0,2) == "^r")
		{
		// Browser knows regular expressions - if not: do nothing
  	var regexp = new RegExp(frmt.substring(2, frmt.length), "g");
		var a = regexp.exec(val);
  	if(a && a != "undefined")
  		{
  		el.value=a[0];
  		return true;
  		}
  	else
 			return false;
  	}
  	return true;
	}

/*-------------------------------------------------------------------------------------
 * Validates the named fields content according to a regular expression
 * specified in frmt (with prefix ^r)
 * generating an email specific errormessage
 * returns false if validation succeeds, meaning the focus has not been changed!
*/
function validateEmail (name, frmt)
  {
  if (!validateToRegexp (name, frmt))
    {
    var el = firstInput (name);
    markError (el, false, "email");
    if (!useErrorLines (el))
      alert (getGlobalErrorText ("email"));
    return true;
    }
  return false;
  }

/*-------------------------------------------------------------------------------------
 * Validates the named fields content according to a regular expression
 * specified in frmt (with prefix ^r)
 * generating an unspecific errormessage
 * returns false if validation succeeds, meaning the focus has not been changed!
*/
function validateRegexp (name, frmt)
	{
	if (!validateToRegexp (name,frmt))
		{
		alert("Die Eingabe entspricht nicht dem erforderlichen Format. Bitte korrigieren Sie.");
		return markError (firstInput (name), false);
    }
	return false;
	}

/*-------------------------------------------------------------------------------------
 * Checks the fill status of a input field
 * if not filled the field is marked red and if the focus has not been set before
 * (as determined by the hasFocus variable)
 * returns false if validation succeeds, meaning the focus has not been changed!
*/
function validateFilledField (name, hasFocus)
	{
	return validateFilledElement (inputField (name), hasFocus);
	}

function validateFilledElement (el, hasFocus)
	{
  if (el != null && isEmptyField (el))
    {
    if (getElementType (el) != "radio")
      hasFocus = markError (firstField (el), hasFocus, "filled");
    }
  return hasFocus;
  }

//-------------------------------------------------------------------------------------
function repairDate(fld, val)
	{
  alert ("Das eingegebene Datum '" + val + "' konnte nicht erkannt werden. Bitte geben Sie ein gültiges Datum ein.");
  lastFocusElementFailed = true;
  return "";

	var name = "cal_" + fld.name;
	var el = null;
	if (document.getElementById)
    el = document.getElementById(name);
	else
	 	el = document[name];
  if (!el)  //no repair
    return "";
  if (!confirm ("Das eingegebene Datum '" + val + "' konnte nicht erkannt werden. Möchten Sie einen Kalender zur Auswahl des Datums verwenden?"))
    return "";
  el.onclick();
  return fld.value; //will be filled later on by click handler (i.e. calendar control)
	}

//-------------------------------------------------------------------------------------
function isArray(obj)
	{
	if (typeof obj != "undefined" && obj != null)
		return (typeof(obj.length)!="undefined" && typeof(obj.type)=="undefined");
	else
		return false;
	}

//-------------------------------------------------------------------------------------
function blockDisplay()
	{
  return (window.netscape) ? "table-row" : "block";
	}

function styleDisplay(on)
	{
	if (on)
	  return (window.netscape) ? "table-row" : "block";
	return "none";
	}

/*-------------------------------------------------------------------------------------
 * sets the visibility of the element with the id name according to the boolean on flag
 * if the element is a TR and it is displayed in the IE then all child-TDs visibility
 * is set too
 */
function setVisibility(name, on)
	{
	var el = null;
	if (document.getElementById)
    el = document.getElementById(name);
  else
  	el = document[name];
  if (typeof el == "undefined" || el == null)
    return false;
  return makeBlockVisible (el, on);
	}
	
function makeBlockVisible (el, on)
	{
	if (on)
    el.style.display = (window.netscape) ? "table-row" : "block";
  else
    el.style.display = "none";
	if (ie && el.tagName == "TR")
		{
		var cells = el.cells;
		for (var  i = 0; el.cells[i]; i++)
			{
			if (on)
			  el.cells[i].style.display = (window.netscape) ? "table-row" : "block";
			else
			  el.cells[i].style.display = "none";
			}
		}
	return true;
	}

function setSpanVisibility(name, on)
	{
  var el = document.getElementById(name);
  if (!el)
    return false;
  makeSpanVisible (el, on);
  el = document.getElementById("l_" + name);
  if (el)
	  el.style.display = on ? "inline" : "none";
	el = document.getElementById("helpspan_" + name);
  if (el)
	  el.style.display = on ? "inline" : "none";
	return true;
	}
	
function makeSpanVisible (el, on)
  {
  el.style.display = on ? "inline" : "none";
  for (var i = 0; i < el.childNodes.length; i ++)
    {
    var sub = el.childNodes[i];
    if (sub.tagName == "SELECT")
	  	sub.style.display = on ? "inline" : "none";
    }
	return true;
	}

/*-------------------------------------------------------------------------------------
 * sets the visibility of the element with the id name according to the boolean on flag
 * if the element is a TR and it is displayed in the IE then all child-TDs visibility
 * is set too
 */
function enableElementById(name, on)
	{
		if (document.getElementById)
	    el = document.getElementById(name);
	  else
	  	el = document[name];
	  if (el == null || typeof el == "undefined")
	    return false;
    el.disabled = !on;
		return true;
	}

/*-------------------------------------------------------------------------------------
 * sets the visibility of the inline element with the id name according to the boolean on flag
 * is set too
 */
function setVisibilityInline(name, on)
	{
		if (document.getElementById)
	    el = document.getElementById(name);
	  else
	  	el = document[name];
	  if (typeof el == "undefined" || el == null)
	    return false;
		if (on)
	    el.style.display = "inline";
	  else
	    el.style.display = "none";
		return true;
	}

//-------------------------------------------------------------------------------------
function setCondBoolean (section, name, onval)
  {
	var on = getCondValue (name, onval);
	showConditional (section, on);
	return on;
  }

//-------------------------------------------------------------------------------------
function buttonClick (name)
	{
	var el = document.getElementById (name);
	if (el == null || el.type != "button" || el.value == "Bitte warten")
		return false;
	el.disabled = true;
	el.origValue = el.value;
	el.value = "Bitte warten";
	return true;
	}

//-------------------------------------------------------------------------------------
function enableButton(name)
	{
	var el = document.getElementById(name);
	if (el == null || el.type != "button" || el.value != "Bitte warten")
		return false;
	el.disabled = false;
	el.value = el.origValue;
	return true;
	}

//-------------------------------------------------------------------------------------
function hasField (name)
  {
  var el = firstInput (name);
  if (typeof el != "undefined" && el != null)
    return true;
  return false;
  }

//-------------------------------------------------------------------------------------
function getFieldType (name)
  {
  return getElementType (inputField (name));
  }

function getElementType (el)
  {
  el = firstField (el);
  if (!el || typeof el == "undefined")
    return null;
  return el.type;
  }

//-------------------------------------------------------------------------------------
function getFieldValue (name)
  {
  return getElementValue (inputField (name));
  }

function getElementValue (el)
  {
  if (!el || typeof el == "undefined")
    return null;
  var elType = getElementType (el);
  if (elType == "radio")
    return getRadioButtonValue (el);
  el = firstField (el);
  if (elType == "select-one")
	  return el.value;
	return el.value;
  }

function getSelectDisplayValue (el)
  {
  if (el == null || typeof el == "undefined")
    return null;
  return el.options[el.selectedIndex].text;
  }

//-------------------------------------------------------------------------------------
function getRadioButtonValue (radioElement)
  {
  if (typeof radioElement.length == "undefined")
    return radioElement.value;
  for (var i = 0; i < radioElement.length; i++)
    {
    if (radioElement[i].checked)
      return radioElement[i].value;
    }
  return null;
  }

//-------------------------------------------------------------------------------------
function getCondValue (name, onval)
  {
  var myval = getFieldValue (name);
  if (myval == null)
  	return false;
	if (onval)
		return (myval == onval);
	return (myval != null && myval != "" && myval != "0" && myval != 0)
  }

/*-------------------------------------------------------------------------------------
 * show section if element with the name is not zero
*/
function setCondNonZero(section, name)
  {
 	var el = inputField (name);
 	if (typeof el != "undefined" && el != null)
 		{
 		var val = 0;
 		if(!isNaN(el.value))
 			val = parseFloat(el.value)
 		var on = el.value != 0;
		showConditional (section, on);
		return on;
		}
	return false;
  }

/*-------------------------------------------------------------------------------------
 * set field display according to the on parameter
*/
function displayField (fieldname, on)
  {
 	var f = inputField (fieldname);
  if (f == null || typeof f == "undefined")
    return;
  var display = on ? "inline" : "none";
  if (isArray(f))
    {
    f[0].style.display = display;
    f[1].style.display = display;
  	}
  else
		f.style.display = display;
  }


/*-------------------------------------------------------------------------------------
 * deletes the content of the named field
 * if it exists and the boolean flag 'on' is set to false (meaning the field is not
 * displayed)
 * if there is an array of fields with this name, only the first element is emptied,
 * assuming, this is a periodical amount input field with the value being the first element.
*/
function condDeleteFieldValue (name, on)
	{
	if(on)
		return;
	var el = inputField(name);
	if (typeof el != "undefined" && el != null)
		{
		el = firstField (el);
		if (el)
			el.value = "";
		}
	}

/*-------------------------------------------------------------------------------------
 * This is the duplicateTabLine adapted to use by netscape and only by netscape.
 * Moved here from antrag\capital.vm
 */
function duplicateTabLineNS (topic, vcs, before, prefix, e)
  {
  duplicateTabLineNS_2 (topic, vcs, before, prefix, e, null);
  }

function duplicateTabLineNS_2 (topic, vcs, before, prefix, e, dontReplaceVcsAfter)
  {
	var vc = parseInt(vcs.substring(1,vcs.length-1));
	var value = e.target.value;
	e.target.value = "";

  var tr = document.getElementById(topic + "Row" + vc);
  var trc = tr.cloneNode(true);
  trc.id = topic + "Row" + (vc+1);
	if (before)
		{
  	var tbefore = document.getElementById(before);
		tr.parentNode.insertBefore (trc, tbefore);
		}
	else
		{
		tr.parentNode.appendChild (trc);
		}
  var oldVc = "[" + vc + "]";
  var newVc = "[" + (vc+1) + "]";
	var seqId = document.getElementById(topic + "Seq" + oldVc);
	if (seqId != null)
		{
		var idNodes = document.getElementsByName(seqId.name);
		if (idNodes.length == 1)
			{
			var seqClone = seqId.cloneNode(true);
			seqClone.setAttribute("id", topic + "Seq" + newVc);
			seqClone.name = seqClone.name.split(oldVc).join (newVc);
			seqId.parentNode.appendChild(seqClone);
			}
		}
	var tds = trc.getElementsByTagName("TD");
  for (var i = 0; i < tds.length; i ++)
    {
    var td = tds[i];
    if (typeof td.innerHTML != "undefined" && td.innerHTML != "undefined")
      {
    	td.innerHTML = td.innerHTML.split(oldVc).join (newVc);
      if (dontReplaceVcsAfter != null)
        td.innerHTML = td.innerHTML.split(dontReplaceVcsAfter + newVc).join (dontReplaceVcsAfter + oldVc);
    	}
		}
  if (prefix)
    {
    oldVc = prefix + vc;
    newVc = prefix + (vc+1);
    for (var i = 0; i < tds.length; i ++)
      {
      var td = tds[i];
	    if (typeof td.innerHTML != "undefined" && td.innerHTML != "undefined")
				td.innerHTML = td.innerHTML.split(oldVc).join (newVc);
	  	}
    }
  e.target.onchange = ignoreOk;
	e.target.value = value;
  }

/*-------------------------------------------------------------------------------------
 * duplicates a table line - purely for ie, only to be used for backoffice functionality
 *
 * sample definition of addPreSuffixes = {"noDefaultVcReplace":true,"noReplaceOnChange":true, "containsCond":"XX",
 *    "psList":[{"prefix":"p1", "suffix":"s1"},
 *              {"prefix":"p2", "suffix":"s2"}]};
*/
function duplicateTabLine (topic, vcs, before, prefix, addPreSuffixes)
  {
  duplicateTabLine_2 (topic, vcs, before, prefix, null, addPreSuffixes);
  }

function duplicateTabLine_2 (topic, vcs, before, prefix, dontReplaceVcsAfter, addPreSuffixes)
  {
	var vc = parseInt(vcs.substring(1,vcs.length-1));
  var value = event.srcElement.value;
  event.srcElement.value = "";
  var tr = document.getElementById(topic + "Row" + vc);
  var trc = tr.cloneNode(true);
  trc.id = topic + "Row" + (vc+1);
	if (before)
		{
  	var tbefore = document.getElementById(before);
		tr.parentNode.insertBefore (trc, tbefore);
		}
	else
		tr.parentNode.appendChild (trc);
  var oldVc = "[" + vc + "]";
  var newVc = "[" + (vc+1) + "]";
  for (var i = 0; i < trc.childNodes.length; i ++)
    {
    var td = trc.childNodes(i);
    if (!addPreSuffixes || !addPreSuffixes.noDefaultVcReplace)
    {
      td.innerHTML = td.innerHTML.split(oldVc).join (newVc);
    }    
    if (addPreSuffixes && (!addPreSuffixes.containsCond || td.innerHTML.indexOf(addPreSuffixes.containsCond) >= 0))
      {
      for (var addpsIdx = 0; addpsIdx < addPreSuffixes.psList.length; addpsIdx++)
        {
        var oldReplStr = addPreSuffixes.psList[addpsIdx].prefix + vc + addPreSuffixes.psList[addpsIdx].suffix;
        var newReplStr = addPreSuffixes.psList[addpsIdx].prefix + (vc+1) + addPreSuffixes.psList[addpsIdx].suffix;
        td.innerHTML = td.innerHTML.split(oldReplStr).join (newReplStr);
        }
      }
    if (dontReplaceVcsAfter != null)
      td.innerHTML = td.innerHTML.split(dontReplaceVcsAfter + newVc).join (dontReplaceVcsAfter + oldVc);
		}
  if (prefix)
    {
    oldVc = prefix + vc;
    newVc = prefix + (vc+1);
    for (var i = 0; i < trc.childNodes.length; i ++)
      {
      var td = trc.childNodes(i);
      td.innerHTML = td.innerHTML.split(oldVc).join (newVc);
  		}
    }
  if (!addPreSuffixes || !addPreSuffixes.noReplaceOnChange)
    event.srcElement.onchange = ignoreOk;
  event.srcElement.value = value;
	//alert ("new tab " + tab.outerHTML);
  }

/*-------------------------------------------------------------------------------------
 * checks an form field for emptyness
 */
function isEmptyField (el)
	{
  var elType = getElementType (el);
  if (elType == "radio")
    {
    var value = getRadioButtonValue (el);
    return (value == null || value == "");
    }
  el = firstField (el);
  if (elType.substring(0,1) == "s")
    return (el.selectedIndex == 0 && (el.value == "" || el.value=="Bitte wählen")) ||
            el.selectedIndex < 0;
  else if (elType.substring(0,1) == "c")
  	return (!el.checked);
	else
  	return (getElementValue (el) == "");
	}


/*-------------------------------------------------------------------------------------
 * returns the input field of given name or an array, if multiply defined
 */
function inputField (name)
  {
  var retVal = null;
  if (name.indexOf(":") != -1)
    {
    var a = name.split(':');
    retVal = document.forms[a[0]].elements[a[1]];
    }
  else
    {
    for (var i = 0; i < document.forms.length && !retVal; i ++)
      {
      var el = document.forms[i].elements[name];
      if (el)
        retVal = el;
      }
    }
  if (!retVal && (typeof lookupInputFieldExt != "undefined" ) && lookupInputFieldExt != null && lookupInputFieldExt)
    retVal = document.getElementById(name);
  return retVal;
  }

/*-------------------------------------------------------------------------------------
 * returns the input field of given name. If multiply defined, return first matching
 */
function firstInput (name)
  {
  return firstField (inputField (name));
  }

function firstField (el)
  {
  if (isArray (el))
    el = el[0];
  return el;
  }

var stdFloatFormatter = null;

function makeStdFloatFormatter ()
  {
	if (stdFloatFormatter == null)
	  stdFloatFormatter = new Formatter("\#.\#\#\#,00");
	}

function getStdFloatFormatter ()
  {
  makeStdFloatFormatter ();
  return stdFloatFormatter;
  }

/*-------------------------------------------------------------------------------------
 * returns the amount of a periodical value casted to a given period
 */
function getPeriodicalAmount (name, targetPeriod)
  {
	var el = inputField (name);
	if (isArray(el))
		{
		period = el[1].value;
		el = el[0];
		}
	else
		period = null;
	val = el.value;
	if (val == null || val == "")
		return null;
	val = getStdFloatValue (val);
	if (period != null)
		val = recalcPeriodical (val,period, targetPeriod);
	return val;
	}

/*-------------------------------------------------------------------------------------
 * returns the period of a periodical amount
 */
function getPeriod (name)
  {
	var el = inputField (name);
	if (isArray(el))
		return el[1].value;
	return null;
	}

/*-------------------------------------------------------------------------------------
 * returns the monthly amount of a periodical value, replacing 0 for null
 */
function getMonthlyAmount (name)
  {
	var el = inputField (name);
	if (typeof el == "undefined" || el == null)
	  return 0;
	if (isArray(el))
		{
		period = el[1].value;
		el = el[0];
		}
	else
		period = null;
	val = el.value;
	if (val == null || val == "")
		return 0;
	val = getStdFloatValue (val);
	if (period != null)
		val = recalcPeriodical (val,period, "pm");
	return val;
	}

/*-------------------------------------------------------------------------------------
 * returns the float value of a numeric field
 */
function getFloatValue (name)
  {
	var el = firstInput (name);
	if (el == null || el == "undefined")
	  return 0;
  return getElementFloatValue (el);
  }

function getElementFloatValue (el)
  {
  var val = el.value;
	if (val == null || val == "")
		return null;
  return getStdFloatValue (val);
  }

function getStdFloatValue (val)
  {
  makeStdFloatFormatter ();
  return stdFloatFormatter.parseFloat (val);
  }

/*-------------------------------------------------------------------------------------
 * set a field to empty
 */
function makeEmpty (name)
  {
	var el = firstInput (name);
	if ( el == null || el == "undefined" )
	  return;
	el.value = "";;
	}

/*-------------------------------------------------------------------------------------
 * returns the float value of a numeric field, replacing empty fields by 0
 */
function getFloatNumeric (name)
  {
  var val = getFloatValue (name);
  if (val == null)
    return 0;
  return val;
  }


/*-------------------------------------------------------------------------------------
 * returns the float value of a span field, replacing empty fields by 0
 */
function getSpanValue (name)
  {
  var fld = document.getElementById(name);
  if (typeof fld == "undefined" || fld == null)
    return 0;
	var val = fld.innerHTML;
	if (val == null || val == "")
		return 0;
	val = getStdFloatValue (val);
  if (val == null)
    return 0;
  return val;
  }


/*-------------------------------------------------------------------------------------
 * recalcs a periodical value from source period
 * to target period
 */
function recalcPeriodical (val, pSource, pTarget)
	{
	var tfactor = getPeriodicalFactor(pTarget);
	var sfactor = getPeriodicalFactor(pSource);
	return val / sfactor * tfactor;
	}

/*-------------------------------------------------------------------------------------
 * obtains the numeric factor for a given period
 * pa = 12
 * ph = 6
 * pq = 3
 * pm = 1
 */
function getPeriodicalFactor(p)
	{
		if (p=="pa")
		  return 12;
		else if (p=="pm")
		  return 1;
		else if (p=="pq")
		  return 3;
		else if (p=="ph")
		  return 6;
		return 0;
	}


/*-------------------------------------------------------------------------------------
 * maximize a window
 */
function maximizeWindow (win)
  {
  win.moveTo(0,0);
  if (document.all)
    win.resizeTo(screen.availWidth,screen.availHeight);
  else if (document.layers||document.getElementById)
    {
    if (win.outerHeight < screen.availHeight || win.outerWidth < screen.availWidth)
      {
      win.outerHeight = screen.availHeight;
      win.outerWidth = screen.availWidth;
      }
    }
  }

/*-------------------------------------------------------------------------------------
 * prefix-function: determines wheter "text" startsWith "prefix"
 */
function startsWith (text, prefix)
  {
  if (prefix == null)
    return true;
  if (text == null)
    return false;
  return (text.length >= prefix.length) && (text.substring(0, prefix.length) == prefix);
  }

/*-------------------------------------------------------------------------------------
 * simple Popup Window
 */
function simplePopupWindow (name, w, h, url, doCenter, scrollbars)
	{
	if (scrollbars)
	  scrollbars = "yes";
	else
	  scrollbars = "auto";
  var x = -1;
  var y = -1;
  if (doCenter)
    {
    x = (screen.width / 2) - (w / 2);
    y = (screen.height / 2) - (h / 2) - 50;
    }
  var options = "toolbar=no,menubar=no,locationbar=no,scrollbars="+scrollbars+",resizable=yes,status=yes";
  return popupWindow (name, x, y, w, h, false, options, url );
  }
 
/*-------------------------------------------------------------------------------------
 * invokes a popup window
 * name = Name of window
 * url = URL to invoke
 * returns window handle
 */
function popupWindow (name, x, y, width, height, maximize, options, url)
	{
  var w = window.open (url, name, options + ",width=" + width + ",height=" + height);
  if (w && w != "undefined")
    {
    if (maximize)
      maximizeWindow(w);
    else if (document.all)
      moveOnScreen (w, width, height);
    if (x != -1 && y != -1)
    	w.moveTo( x, y );
    w.focus();
    }
  return w;
  }

  

/*-------------------------------------------------------------------------------------
 * for active-passive-grey field pairs.
 * disables the field called otherName
 * and fills it with the value calculated from the baseName fields value and
 * the name fields value using the calc formula.
 * In calc the baseName value has to be called base and the name value has to
 * be called val.
 */
function changeState(name, otherName, baseName, calc, pattern)
 	{
	var f = new Formatter(pattern);
 	var field = firstInput (name);
 	var otherField = firstInput (otherName);
 	var baseField = firstInput (baseName);
 	// empty - so enable both
	if(field.value == "")
		{
		field.className="app";
		otherField.value="";
		otherField.className="app";
		}
	else
	  {
		field.className="app";
		otherField.className="disabled";
		var val = f.parseFloat(field.value);
		var base = 0;
		if(!baseField || baseField == "undefined")
			base = f.parseFloat(getContentById(baseName));
		else
			base = f.parseFloat(baseField.value);
		otherField.value=f.format(String(eval(calc)));
 		}
	}

/*-------------------------------------------------------------------------------------
 * this function is called by onKeyPress and onChange events of textareas.
 * it grows the field to accepts all the text without scrolling
 */

function growArea(name)
  {
  var el = firstInput (name);
  if (el.clientHeight < el.scrollHeight)
	  {
	  if (el.scrollHeight > 80)
	  	{
	  	var pel = el.parentNode;
	  	if (el.clientWidth < pel.clientWidth - 6)
	  		el.style.width = pel.clientWidth - 6;
	  	}
	  el.style.height = el.scrollHeight + 10;
		}
  }

/*-------------------------------------------------------------------------------------
 * Submits the 0th form of the documents forms collection on pressing the enter button
 * Should be called in the onKeyPress event of either a specific form element or the body
 */
function submitOnEnter(e)
	{
	var keycode;
	if (window.event)
		{
		// ie
		keycode = window.event.keyCode;
		}
	else if (e)
		{
		// netscape
		keycode = e.which;
		}
	else
		{
		// something else. ignore it.
		return true;
		}

	if (keycode == 13)
	   {
	   getEhypForm().submit();
	   return false;
	   }
	else
	   return true;
	}


/* ******************************************************************
 * In the case of conditional fields this function has to be called
 * in the body tags onKeyDown event. Thus the Cursor is set correctly
 * and the netscape crash upon setting the focus on a removed field
 * is avoided.
 */
function filterTab(e)
	{
	var keycode;
	var el;
	if (window.event)
		{
		//return true;
		// ie
		keycode = window.event.keyCode;
		el = window.event.srcElement;
		}
	else if (e)
		{
		// netscape
		keycode = e.which;
		el = e.target;
		}
	else
		{
		// something else. ignore it.
		return true;
		}
	if (keycode == 9)
		{
		if (el.onchange && el.onchange != 'undefined')
			el.onchange();
		return true;
		}
	}

/*
 * sets the focus on the element and scrolls the page so the element
 * aligns with the top.
 */
function setFocus(el, hasFocus)
	{
	if (!hasFocus)
		{
    window.scrollTo (0, el.offsetTop - 1);
	  el.focus();
		}

	return true;
	}

/*
 * check whether an input control doesn't have too many charcters.
 * If it does, shorten the text accordingly.
 * This function should be called onKeyDown and onKeyUp.
 */
function textMax (limit)
	{
  var el = event.srcElement;
	if (el.value.length > limit)
		el.value = el.value.substring(0, limit);
  }


/*
 * return the absolute screen pos of an element
 */
function getAbsolutePos (el)
  {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent)
	  {
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	  }
	return r;
  }


/*
 * move the window so that it is Visible on the screen
 */
function moveOnScreen (w, dx, dy)
  {
  try
    {
    //alert ("left " + w.screenLeft + " + width " + dx + " = " + (w.screenLeft + dx) + ", limit " + w.screen.width);
    if (w.screenLeft + dx > w.screen.availWidth)
      {
      var maxOffset = -1 * w.screenLeft + 5;
      var offset = w.screen.availWidth - (w.screenLeft + dx) - 10;
      w.moveBy (Math.max (offset, maxOffset), 0);
      }
    //alert ("top " + w.screenTop + " + height " + dy + " = " + (w.screenTop + dy) + ", limit " + w.screen.height);
    if (w.screenTop + dy > w.screen.availHeight)
      {
      var maxOffset = -1 * w.screenTop + 23;
      var offset = w.screen.availHeight - (w.screenTop + dy) - 10;
      w.moveBy (0, Math.max (offset, maxOffset));
      }
    }
  catch (e)
    {
    }
  }

/*
 * refresh the opener window by calling its refreshFunc or submitting its refresh form
 */
function refreshOpener(closemyself)
  {
  if (window.opener != null)
    {
    var func = findRefreshFunc (window.opener);
    if (func != null)
      func();
    else
      {
      var form = findForm (window.opener, "refresh");
      if (form != null)
        form.submit();
      }
    }
  if (closemyself)
    {
    if (ie)
      window.open('','_self','');
    window.close();
    }
  }

function findRefreshFunc (win)
  {
  if (typeof win.refreshFunc != "undefined")
    return win.refreshFunc;
  for (var i = 0; i < win.frames.length; i++)
    {
    var f = findRefreshFunc (win.frames[i]);
    if (f != null)
      return f;
    }
  return null;
  }

function findForm (win, name)
  {
  var f = win.document.forms[name];
  if (f != null && f != "undefined")
    return f;
  for (var i = 0; i < win.frames.length; i++)
    {
    f = findForm (win.frames[i], name);
    if (f != null)
      return f;
    }
  return null;
  }

function getEhypForm()
  {
  if (document.forms.length <= 1)
    return document.forms[0];
  if ((typeof myEhypForm != "undefined") && myEhypForm)
    return document.forms[myEhypForm];
  if (document.forms["ehyp"])
    return document.forms["ehyp"];
  if (document.forms["appform"])
    return document.forms["appform"];
  return document.forms[0];
  }

function getFormAsUrl(frm)
  {
  var url = frm.action;
  var connect = "?";
  if (url.indexOf("?") != -1)
    connect = "&";
  for (var i = 0; i < frm.elements.length; i ++)
    {
    var el = frm.elements[i];
    if (el.type == "button")
      continue;
    if (el.type == "checkbox"  &&  !el.checked)
      continue;
    url += connect;
    connect = "&";
    url += el.name;
    url += "=";
    var val = getElementValue (el);
    if (val)
      {
      //Vorsicht: zerschiesst die Umlaute - lieber lassen
      //url += encodeURIComponent (val);
      url += val;
      }
    }
  return url;
  }

function submitAsUrl()
  {  
  document.location.href = getFormAsUrl(getEhypForm());
  }

function setRadioButton (name, value)
  {
	var el = inputField(name);
  setRadioButtonElem (el, value);
  }

function setRadioButtonElem (el, value)
  {
	if (isArray(el))
	  {
	  for (var i = 0; i < el.length; i++)
    	if (el[i].value == value)
    		{
    		el[i].checked = true;
    		break;
    		}
    }
	else if (el.value == value)
		el.checked = true;
  }

function setCheckboxValue (name, on)
  {
  var cbElem = firstInput ("cb_" + name);
  cbElem.checked = on;
  setCheck (cbElem, name);
  }

function setFieldValue (name, value)
  {
  var el = firstInput (name);
  setElementValue (el, value);
  }

function setElementValue (el, value)
  {
  if (!el)
    return;
	if (el.type == "radio")
		{
		setRadioButtonElem (el, value);
		return;
		}
	else if (el.type == "select-one")
	  {
    for (var j = 0; j < el.options.length; j ++)
      {
      var option = el.options[j];
      if (option.value == value)
        {
        option.selected = true;
        break;
        }
      }
	  }
	else
  	el.value = value;
  }


function append (base, delimiter, appendix)
  {
  if (!base || base.length == 0)
    return appendix;
  if (!appendix || appendix.length == 0)
    return base;
  return base + (!delimiter ? "" : delimiter) + appendix;
  }

function contains(array, value)
  {
  for (var i=0; i<array.length; i++)
    if (array[i] == value)
      return true;
  return false;
  }

function isInPopup ()
  {
	if ((window.opener))
	  return true;
	if (parent != window && parent.frames.length > 0)
	  return true;
  return false;
  }

function goodFirstname (text)
  {
  return goodName (text, true);
  }

function goodLastname (text)
  {
  return goodName (text, false);
  }

function goodName (text, eachword)
  {
  if (!text || text == "")
    return text;
  if (text != text.toLowerCase())
    return text;
  var words = text.split(" ");
  for (var i = 0; i < words.length; i++)
    if (eachword || i == words.length-1)
      {
      var word = words[i];
      var names = word.split("-");
      for (var j = 0; j < names.length; j++)
        names[j] = capFirst(names[j]);
      words[i] = names.join("-");
      }
  text = words.join(" ");
  return text;
  }

function capFirst (text)
  {
  return text.substring(0, 1).toUpperCase() + text.substr(1);
  }

var noEncodeChars = " -_.*!'()öäüÖÄÜß";
function urlEncodeFormData (url)
  {
  var result = "";
  var start = 0;
  var end = 0;
  for (var i = 0; i < url.length; ++i)
    {
    var ch = url.charAt (i);
    if ('0' <= ch && ch <= '9' || 'A' <= ch && ch <= 'Z' || 'a' <= ch && ch <= 'z' || noEncodeChars.indexOf (ch) >= 0)
      ++end;
    else
      {
      if (start != end)
        result += url.slice (start, end);
      start = end = i + 1;
      result += encodeUTF8 (url.charCodeAt (i));
    	}
    }
  if (start != end)
    result += url.slice (start, end);
  return result.replace (/ /, "+");
  }

var doEncodeChars = "\n\r\a\t";
function urlEncodeSpecialChars (url)
  {
  var result = "";
  var start = 0;
  var end = 0;
  for (var i = 0; i < url.length; ++i)
    {
    var ch = url.charAt (i);
    if (doEncodeChars.indexOf (ch) >= 0)
      {
      if (start != end)
        result += url.slice (start, end);
      start = end = i + 1;
      result += encodeUTF8 (url.charCodeAt (i));
    	}
    else
    	end++;
    }
  if (start != end)
    result += url.slice (start, end);
  return result.replace (/ /, "+");
  }

var hexDigits = [48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70];
function encodeUTF8 (code)
  {
  if (code < 128)
    return String.fromCharCode (37, hexDigits[code >> 4], hexDigits[code & 0xF]);
  else if (code < 0x800)
    return String.fromCharCode (37, hexDigits[0xC | (code >> 10)], hexDigits[(code >> 6) & 0xF], 37, hexDigits[0x8 | ((code >> 4) & 0x3)], hexDigits[code & 0xF]);
  else if (code < 0x10000)
    return String.fromCharCode (37, 69, hexDigits[(code >> 12) & 0xF], 37, hexDigits[0x8 | ((code >> 10) & 0x3F)], hexDigits[(code >> 6) & 0xF], 37, hexDigits[0x8 | ((code >> 4) & 0x03)], hexDigits[code & 0x0F]);
  }

var matchText = "";
var lastKeyHit = null;

function typingMatch ()
	{
  return; // for now, it doesn't work because of IE bug
	if (!window.event)
	  return; // for netscape, who does it correctly by itself
  var evt = window.event;
  var c = evt.keyCode;
  //println ("key up " + lastKeyPressed);
  var k = makeChar (c);
  if (k == "")
    return;
  var ms = (new Date()).getTime();
  if (lastKeyHit < ms - 1100)
    matchText = "";
  lastKeyHit = ms;
  matchText += k;
  var s = evt.srcElement;
  for (var i = 0; i < s.options.length; i ++)
    if (s.options[i].text.toLowerCase().indexOf(matchText) == 0)
      {
      s.selectedIndex  = i;
      break;
      }
  evt.cancelBubble = true;
  evt.returnValue = false;
	}

function typingSearch ()
	{
  return; // for now, it doesn't work because of IE bug
	if (!window.event)
	  return; // for netscape, who does it correctly by itself
  var evt = window.event;
  var s = evt.srcElement;
  var c = evt.keyCode;
  var k = makeChar (c);
  if (k == "")
    return;
  var ms = (new Date()).getTime();
  if (lastKeyHit < ms - 1100)
    matchText = "";
  lastKeyHit = ms;
  matchText += k;
  for (var i = 0; i < s.options.length; i ++)
    if (s.options[i].text.toLowerCase().indexOf(matchText) != -1)
      {
      s.selectedIndex  = i;
      break;
      }
  evt.cancelBubble = true;
  evt.returnValue = false;
	}

function makeChar (c)
  {
  if (c >= 65 && c <= 90)
    return String.fromCharCode(c).toLowerCase();
  if (c >= 48 && c <= 57)
    return String.fromCharCode(c);
  switch (c)
    {
    case 222: return "ä";
    case 186: return "ü";
    case 192: return "ö";
    case 219: return "ß";
    case 190: return ".";
    case 188: return ",";
    case 189: return "-";
    case 55: return "/";
    case 32: return " ";
    }
  return "";
  }

function duplicateRow (e, substlist, userFunc, fallBackEl)
	{
	var el;
	if (fallBackEl)
	  el = fallBackEl;
	else
	  {
  	if (window.event)
  		el = window.event.srcElement;
  	else
  		el = e.target;
	  }
	var dup = new Duplicator();
	if (!dup.inTriggerLine (el))
		return null;
	dup.addSubst ("inc:[?]");
	if (substlist)
		{
		var sarr = substlist.split("|");
		for (var i = 0; i < sarr.length; i ++)
			dup.addSubst (sarr[i]);
		}
	if (userFunc)
		dup.addSubstFunc (userFunc);
	return dup.duplicate();
	}
	
var substFuncs;
function initSubstFuncs()
	{
	var s = new Object();
	s["inc"] = incSubstFunc;
	s["dec"] = decSubstFunc;
	s["setorg"] = setorgSubstFunc;
	s["setdup"] = setdupSubstFunc;
	s["innorg"] = innorgSubstFunc;
	s["inndup"] = inndupSubstFunc;
	s["outorg"] = outorgSubstFunc;
	s["outdup"] = outdupSubstFunc;
	s["incval"] = incvalSubstFunc;
	s["setval"] = setvalSubstFunc;
	s["cpyval"] = cpyvalSubstFunc;
	s["incatt"] = incattSubstFunc;
	s["setatt"] = setattSubstFunc;
	return s;
	}

function incSubstFunc (nr, orgTR, dupTR, pattern)
	{
	substChilds (dupTR, substPattern(pattern, nr), substPattern(pattern, nr+1));
	}
function decSubstFunc (nr, orgTR, dupTR, pattern)
	{
	substChilds (dupTR, substPattern(pattern, nr+1), substPattern(pattern, nr));
	}
function setorgSubstFunc (nr, orgTR, dupTR, pattern)
	{
	setSubstFunc (nr, orgTR, pattern);
	}
function setdupSubstFunc (nr, orgTR, dupTR, pattern)
	{
	setSubstFunc (nr+1, dupTR, pattern);
	}
function innorgSubstFunc (nr, orgTR, dupTR, pattern)
	{
	setIdHtmlFunc (nr, pattern, false);
	}
function inndupSubstFunc (nr, orgTR, dupTR, pattern)
	{
	setIdHtmlFunc (nr+1, pattern, false);
	}
function outorgSubstFunc (nr, orgTR, dupTR, pattern)
	{
	setIdHtmlFunc (nr, pattern, true);
	}
function outdupSubstFunc (nr, orgTR, dupTR, pattern)
	{
	setIdHtmlFunc (nr+1, pattern, true);
	}
function incvalSubstFunc (nr, orgTR, dupTR, pattern)
	{
	var el = firstInput(substPattern(pattern, nr+1));
	if (el)
		el.value = "" + (parseInt(el.value) + 1);
	}
function setvalSubstFunc (nr, orgTR, dupTR, pattern)
	{
	var arr = pattern.split("=");
	var pat = arr[0];
	var rep = "";
	if (arr.length > 1)
		rep = arr[1];
	var el = firstInput(substPattern(pat, nr+1));
	if (el)
		el.value = substPattern(rep, nr+1);
	}
function cpyvalSubstFunc (nr, orgTR, dupTR, pattern)
	{
	var el1 = firstInput(substPattern(pattern, nr));
	var el2 = firstInput(substPattern(pattern, nr+1));
	if (el1 && el2)
		el2.value = el1.value;
	}
function incattSubstFunc (nr, orgTR, dupTR, pattern)
	{
	var attname = substPattern(pattern, nr+1);
	var attval = dupTR.getAttribute (attname);
	if (attval)
		dupTR.setAttribute (attname, "" + (parseInt(attval) + 1));
	}
function setattSubstFunc (nr, orgTR, dupTR, pattern)
	{
	var arr = pattern.split("=");
	var attname = arr[0];
	var rep = "";
	if (arr.length > 1)
		rep = arr[1];
	dupTR.setAttribute (attname, substPattern(rep, nr+1));
	}

function setSubstFunc (nr, tr, pattern)
	{
	var arr = pattern.split("=");
	var src = arr[0];
	var rep = "";
	if (arr.length > 1)
		rep = arr[1];
	substChilds (tr, substPattern(src, nr), substPattern(rep, nr));
	}	

function setIdHtmlFunc (nr, pattern, outer)
	{
	var arr = pattern.split("=");
	var name = arr[0];
	var rep = "";
	if (arr.length > 1)
		rep = arr[1];
	var el;
	if (document.getElementById)
    el = document.getElementById(name);
  else
  	el = document[name];
	if (!el)
		return;
	if (outer)
		el.outerHTML = rep;
	else
		el.innerHTML = rep;
	}	

function substPattern (pattern, nr)
	{
	return pattern.split("?").join("" + nr);
	}
	
function substChilds (tr, src, rep)
	{
	var childs = tr.childNodes;
  for (var i = 0; i < childs.length; i ++)
    {
    var td = childs[i];
    if (td.tagName && td.innerHTML != undefined)
    	td.innerHTML = td.innerHTML.split(src).join (rep);
    }    
  for (var i = 0; i < tr.attributes.length; i ++)
    {
    if(tr.attributes[i].nodeValue && tr.attributes[i].name)
      tr.attributes[i].nodeValue = tr.attributes[i].nodeValue.split(src).join (rep);
    }
	}
	
function Duplicator()
	{
  this.field;
  this.nr;
  this.orgTR;
  this.dubTR;
  this.substFuncs = new Array();
  this.substFuncPars = new Array();
	if (!substFuncs)
		substFuncs = initSubstFuncs(); 
		 
  this.inTriggerLine = function (el)
  	{
  	this.field = el;
  	while (el && el.tagName && el.tagName != "FORM")
  		{
  		var att = el.getAttribute ("duplicate");
  		if (att)
  			{
  			this.nr = parseInt(att);
  			this.orgTR = el;
  			return this.nr != -1;
  			}
			el = el.parentNode;
			}
		return false;
		};
		
	this.addSubst = function (subst)
		{
		var arr = subst.split(":");
		if (arr.length == 1)
			this.addSubstFunc (substFuncs[arr[0]]);
		else
			this.addSubstFunc (substFuncs[arr[0]], arr[1]);
		};
		
	this.addSubstFunc = function (func, par)
		{
		this.substFuncs.push (func);
		if (par)
			this.substFuncPars.push (par);
		else
			this.substFuncPars.push ("");
		};
	
	this.duplicate = function ()
		{
		var fieldval = this.field.value;
		this.field.value = "";
		this.dupTR = this.orgTR.cloneNode(true);
		var tbefore = this.orgTR.nextSibling;
		if (tbefore)
			this.orgTR.parentNode.insertBefore (this.dupTR, tbefore);
		else
			this.orgTR.parentNode.appendChild (this.dupTR);
		this.field.value = fieldval;
		this.orgTR.setAttribute("duplicate", "-1");
		this.dupTR.setAttribute("duplicate", "" + (this.nr+1));
		for (var i = 0; i < this.substFuncs.length; i ++)
			this.substFuncs[i] (this.nr, this.orgTR, this.dupTR, this.substFuncPars[i]);
		return this.dupTR;
		}
	}
			
function getDuplicates (pattern)
	{
	var arr = new Array();
	for (var i = 1; i < 999; i ++)
		{
		el = firstInput (substPattern (pattern, i));
		if (el == null || el == "undefined")
		  return arr;
  	arr.push(el);
		}
	}

function getDuplicateSum (pattern)
	{
	var sum = 0;
	for (var i = 1; i < 999; i ++)
		{
		el = firstInput (substPattern (pattern, i));
		if (el == null || el == "undefined")
		  return sum;
  	sum += getElementFloatValue (el);
		}
	}
	
function getAjaxHighslide (clickedElem, highslideElemId, url)
  {
  var ajaxControlId = highslideElemId;
  var ajaxControl = new AjaxControl (ajaxControlId, url, "PLAIN", true, function () { showAjaxHighslide (clickedElem, highslideElemId) });
  ajaxControl.makeRequest ();
  }

function showAjaxHighslide (clickedElem, highslideElemId)
  {
  var ajaxControlId = highslideElemId;
  var ajaxData = getAjaxData (ajaxControlId);
  if (ajaxData != null)
    {
    var targetNode = document.getElementById ("highslideBody_" + highslideElemId);
    targetNode.innerHTML = ajaxData;
    hs.htmlExpand (clickedElem, { contentId: highslideElemId } )
    }
  }
  
function isVisible (el)
	{
	return (el.offsetWidth > 0 && el.offsetHeight > 0 && el.style.display != "none");
	}

var hasFieldChanges = false;

function registerFieldChange ()
  {
  hasFieldChanges = true;
  }

// --------------------------------------------------------------------------
// ajax scriptings
// --------------------------------------------------------------------------
var ajaxControls = new Array ();

function getAjaxData (_key)
  {
  return ajaxControls[_key].getAjaxData ();
  }

function AjaxControl (_key, _url, _mode, _isAsync, _readyHandler)
  {
  this.key = _key;
  this.url = _url;
  this.mode = _mode;
  this.isAsync = _isAsync;
  this.readyHandler = _readyHandler;

  this.httpControl = null;
  this.ajaxData = null;
  this.enabled = false;

  function makeRequest ()
    {
    if (!this.enabled)
      this.enable ();
    if (this.httpControl == null)
      this.httpControl = createHttpControl ();
    if (this.httpControl == null)
      return;
    this.ajaxData = null;
    if (this.readyHandler)
	    this.httpControl.onreadystatechange = this.readyHandler;
    this.httpControl.open ("GET", this.url, this.isAsync);
    this.httpControl.send (null);
    }
  this.makeRequest = makeRequest;

  function enable ()
    {
    ajaxControls[this.key] = this;
    }
  this.enable = enable;

  function getAjaxData ()
    {
    if (this.httpControl != null)
      this.processAjaxResult ();
    return this.ajaxData;
    }
  this.getAjaxData = getAjaxData;

  function createHttpControl ()
    {
    if (window.ActiveXObject)
      return new ActiveXObject ("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
      return new XMLHttpRequest ();
    return null;
    }
  this.createHttpControl = createHttpControl;

  function processAjaxResult ()
    {
    if (this.httpControl != null && this.httpControl.readyState == 4)
      {
      if (this.mode == "JSON")
        {
        if (this.httpControl.responseText != null && this.httpControl.responseText != "")
          this.ajaxData = eval ("(" + this.httpControl.responseText + ")");
        }
      else if (this.mode == "XML")
        {
        if (this.httpControl.responseXML != null && this.httpControl.responseXML.documentElement != null)
          this.ajaxData = this.httpControl.responseXML;
        }
      else if (this.mode == "PLAIN")
        {
        if (this.httpControl.responseText != null && this.httpControl.responseText != "")
          this.ajaxData = this.httpControl.responseText;
        }
      this.httpControl = null;
      }
    }
  this.processAjaxResult = processAjaxResult;
  }

// --------------------------------------------------------------------------
// form lib scriptings
// --------------------------------------------------------------------------
var useFormLib = false;
var useConditionals = false;
var useAutocheck = false;

// --------------------------------------------------------------------------
// general helper methods
// --------------------------------------------------------------------------
function getColSpan (el)
  {
  if (el == null || typeof (el) == "undefined")
    return 0;
  var tagName = el.nodeName;
  if (tagName != null && tagName.toUpperCase () == "TD")
    {
    var colspan = el.getAttribute ("colspan");
    if (colspan != null)
      {
      colspan = parseInt (colspan);
      if (colspan > 0)
        return colspan;
      }
    return 1;
    }
  else
    {
    var result = 0;
    for (var i = 0; i < el.childNodes.length; i++)
      result += getColSpan (el.childNodes[i]);
    return result;
    }
  }

function addAttribute (el, name, value)
  {
  var lineAttribute = document.createAttribute (name);
  lineAttribute.nodeValue = value;
  el.setAttributeNode (lineAttribute);
  }

function insertAfter (newNode, refNode)
  {
  if (refNode.nextSibling)
    refNode.parentNode.insertBefore (newNode, refNode.nextSibling);
  else
    refNode.parentNode.appendChild (newNode);
  }

function addAll (myArray, toAdd)
  {
  if (toAdd != null)
    {
    for (var i = 0; i < toAdd.length; i++)
      myArray.push (toAdd[i]);
    }
  }

function focusField (fieldName)
  {
  var el = firstInput (fieldName);
  if (el != null && !el.disabled && (!el.type || el.type != "hidden"))
    el.focus ();
  }

// --------------------------------------------------------------------------
// set handling for nonempty String elements by Strings with '|' separator
// --------------------------------------------------------------------------
function isEmptySet (set)
  {
  return set == null || set == "";
  }

function hasElement (set, element)
  {
  if (set == null)
    return false;
  return ("|" + set + "|").indexOf ("|" + element + "|") > -1;
  }

function getAsList (set)
  {
  if (set == null)
    return null;
  return set.split ("|");
  }

function joinElements (set1, set2)
  {
  if (isEmptySet (set1))
    return set2;
  if (isEmptySet (set2))
    return set1;
  var result = set1;
  var elementsList = getAsList (set2);
  for (var i = 0; i < elementsList.length; i++)
    {
    var element = elementsList[i];
    if (!hasElement (result, element))
      result += "|" + element;
    }
  return result;
  }

function removeElements (set1, set2)
  {
  if (isEmptySet (set1))
    return null;
  if (isEmptySet (set2))
    return set1;
  var result = null;
  var elementsList = getAsList (set1);
  for (var i = 0; i < elementsList.length; i++)
    {
    var element = elementsList[i];
    if (!hasElement (set2, element))
      {
      if (result == null)
        result = "";
      else
        result += "|";
      result += element;
      }
    }
  return result;
  }

function hasIntersectWithList (set, elementsList)
  {
  if (isEmptySet (set) || elementsList == null || elementsList.length == 0)
    return false;
  for (var i = 0; i < elementsList.length; i++)
    {
    if (hasElement (set, elementsList[i]))
      return true;
    }
  return false;
  }

function hasIntersect (set1, set2)
  {
  if (isEmptySet (set1))
    return false;
  return hasIntersectWithList (set2, getAsList (set1));
  }

// --------------------------------------------------------------------------
// appended rows of a field row
// --------------------------------------------------------------------------
function getAppendedRowType (row)
  {
  if (!row.attributes)
    return null;
  var result = row.getAttribute ("appendedRowType");
  return result == "" ? null : result;
  }

function isAppendedRow (row)
  {
  return getAppendedRowType (row) != null;
  }

function getAppendedRows (fieldRow, appendedRowType)
  {
  if (fieldRow == null || typeof (fieldRow) == "undefined")
    return null;
  var result = new Array ();
  var el = fieldRow;
  do
    {
    el = el.nextSibling;
    if (el == null || !isAppendedRow (el))
      break;
    if (appendedRowType == null || typeof appendedRowType == "undefined" || el.getAttribute ("appendedRowType") == appendedRowType)
      result.push (el);
    }
  while (true);
  return result;
  }

function getTotalRows (fieldRow)
  {
  var result = new Array ();
  result.push (fieldRow);
  addAll (result, getAppendedRows (fieldRow, null));
  return result;
  }

var appendedRowIdCounter = 1;

function createAppendedRow (fieldRow, appendedRowType, rowClassName)
  {
  var totalRows = getTotalRows (fieldRow);

  var tr = document.createElement ("tr");
  addAttribute (tr, "appendedRowType", appendedRowType);
  addAttribute (tr, "id", "appendedRow" + (appendedRowIdCounter++));
  if (fieldRow.getAttribute("conditions"))
    addAttribute (tr, "conditions", fieldRow.getAttribute("conditions"));
  if (rowClassName != null && typeof rowClassName != "undefined")
    tr.className = rowClassName;

  var td = document.createElement ("td");
  td.className = "crd_label";
  var textEl = document.createTextNode ("");
  td.appendChild (textEl);
  addAttribute (td, "colspan", getColSpan (fieldRow));

  tr.appendChild (td);
  insertAfter (tr, totalRows[totalRows.length - 1]);
  return tr;
  }

function setAppendedRowText (appendedRow, text)
  {
  for (var i = 0; i < appendedRow.childNodes.length; i++)
    {
    var child = appendedRow.childNodes[i];
    var tagName = child.nodeName;
    if (tagName != null && tagName.toUpperCase () == "TD")
      {
      child.innerHTML = text;
      return;
      }
    }
  }

function removeAppendedRow (appendedRow)
  {
  if (appendedRow != null)
    appendedRow.parentNode.removeChild (appendedRow);
  }

function removeAllAppendedRows (fieldRow, appendedRowType)
  {
  var appendedRows = getAppendedRows (fieldRow, appendedRowType);
  if (appendedRows != null)
    {
    for (var i = 0; i < appendedRows.length; i++)
      removeAppendedRow (appendedRows[i]);
    }
  }

// --------------------------------------------------------------------------
// error/validator class name methods
// --------------------------------------------------------------------------
function addClassPart (text, toAdd)
  {
  if (text == null || text == "")
    return toAdd;
  return text + " " + toAdd;
  }

function getPlainClassName (el)
  {
  var result = null;
  var className = el.className;
  if (className != null && className != "")
    {
    var parts = className.split (" ");
    for (var i = 0; i < parts.length; i++)
      {
      var part = parts[i];
      if (part.indexOf ("error") == -1 && part.indexOf ("validator") == -1)
        result = addClassPart (result, part);
      }
    }
  return result;
  }

function getErrorRowClassName (fieldRow)
  {
  var result = getPlainClassName (fieldRow);
  result = addClassPart (result, "error_msg");
  return result;
  }

function getValidatorRowClassName (fieldRow)
  {
  var result = getPlainClassName (fieldRow);
  result = addClassPart (result, "validatorMsg");
  return result;
  }

// --------------------------------------------------------------------------
// error rows of a field row
// --------------------------------------------------------------------------
function getErrorRows (fieldRow)
  {
  return getAppendedRows (fieldRow, "error");
  }

function getErrorRow (fieldRow, key)
  {
  var errorRows = getErrorRows (fieldRow)
  if (errorRows == null)
    return null;
  for (var i = 0; i < errorRows.length; i++)
    {
    var errorRow = errorRows[i];
    if (errorRow.getAttribute ("errorKey") == key)
      return errorRow;
    }
  return null;
  }

function createErrorRow (fieldRow, key)
  {
  var row = createAppendedRow (fieldRow, "error", getErrorRowClassName (fieldRow));
  addAttribute (row, "errorKey", key);
  return row;
  }

function makeErrorRow (fieldRow, key)
  {
  if (fieldRow == null || typeof (fieldRow) == "undefined")
    return null;
  var errorRow = getErrorRow (fieldRow, key);
  if (errorRow != null)
    return errorRow;
  return createErrorRow (fieldRow, key);
  }

function makeErrorText (fieldRow, key, errorText)
  {
  if (fieldRow == null || typeof (fieldRow) == "undefined")
    return null;
  var errorRow = makeErrorRow (fieldRow, key);
  setAppendedRowText (errorRow, errorText);
  }

function removeErrorText (fieldRow, key)
  {
  if (fieldRow == null || typeof (fieldRow) == "undefined")
    return null;
  removeAppendedRow (getErrorRow (fieldRow, key));
  }

function removeErrorTexts (fieldRow, keys)
  {
  var keyList = getAsList (keys);
  if (keyList != null)
    {
    for (var i = 0; i < keyList.length; i++)
      {
      var key = keyList[i];
      removeErrorText (fieldRow, key);
      }
    }
  }

function removeAllErrorTexts (fieldRow)
  {
  removeAllAppendedRows (fieldRow, "error");
  }

// --------------------------------------------------------------------------
// validator row of a field row
// --------------------------------------------------------------------------
function getValidatorRow (fieldRow)
  {
  var rows = getAppendedRows (fieldRow, "validator");
  if (rows == null)
    return null;
  return rows[0];
  }

function createValidatorRow (fieldRow)
  {
  return createAppendedRow (fieldRow, "validator", getValidatorRowClassName (fieldRow));
  }

function makeValidatorRow (fieldRow)
  {
  if (fieldRow == null || typeof (fieldRow) == "undefined")
    return null;
  var validatorRow = getValidatorRow (fieldRow);
  if (validatorRow != null)
    return validatorRow;
  return createValidatorRow (fieldRow);
  }

function makeValidatorText (fieldRow, validatorText)
  {
  if (fieldRow == null || typeof (fieldRow) == "undefined")
    return null;
  var validatorRow = makeValidatorRow (fieldRow);
  setAppendedRowText (validatorRow, validatorText);
  }

function removeValidatorText (fieldRow)
  {
  removeAppendedRow (getValidatorRow (fieldRow));
  }

// --------------------------------------------------------------------------
// error text methods
// --------------------------------------------------------------------------
function substituteContentText (text, parameters)
  {
  if (text == null || typeof text == "undefined")
    return null;
  var result = text;
  if (parameters != null && typeof parameters != "undefined")
    {
    for (var i = 0; i < parameters.length; i++)
      {
      var value = parameters[i];
      if (value == null)
        value = "";
      result = result.replace ("%" + i, value);
      }
    }
  return result;
  }

function pushParam (result, param)
  {
  if (typeof param != "undefined")
    result.push (param);
  }

function collectParameters (param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  var result = new Array ();
  pushParam (result, param0);
  pushParam (result, param1);
  pushParam (result, param2);
  pushParam (result, param3);
  pushParam (result, param4);
  pushParam (result, param5);
  pushParam (result, param6);
  pushParam (result, param7);
  pushParam (result, param8);
  pushParam (result, param9);
  return result;
  }

function getGlobalErrorText (errorKey)
  {
  if (errorKey == "filled" && validateFilledErrorRow)
    return "Bitte füllen Sie die markierten Felder aus.";
  if (errorKey == "email")
    return "Die von Ihnen eingegebene E-Mail-Adresse ist nicht gültig. Bitte korrigieren Sie.";
  return null;
  }

function getContentErrorText (errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  if (typeof getRawContentErrorText == "undefined")
    return null;
  var text = getRawContentErrorText (errorKey);
  if (text == null)
    return null;
  return substituteContentText (text, collectParameters (param0, param1, param2, param3, param4, param5, param6, param7, param8, param9));
  }

function getErrorText (errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  var result = getContentErrorText (errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  if (result == null)
    result = getGlobalErrorText (errorKey);
  return result;
  }

// --------------------------------------------------------------------------
// error registration
// --------------------------------------------------------------------------
var globalErrors = null;

function registerGlobalError (errorKey)
  {
  globalErrors = joinElements (globalErrors, errorKey);
  }

function deregisterGlobalErrors (errorKeys)
  {
  globalErrors = removeElements (globalErrors, errorKeys);
  }

function hasGlobalError (errorKeys)
  {
  return hasIntersect (globalErrors, errorKeys);
  }

function registerLocalError (errorKey, el)
  {
  var localErrors = el.getAttribute ("localErrors");
  localErrors = joinElements (localErrors, errorKey);
  el.setAttribute ("localErrors", localErrors);
  }

function deregisterLocalErrors (errorKeys, el)
  {
  if (isEmptySet (errorKeys))
    return;
  var localErrors = el.getAttribute ("localErrors");
  localErrors = removeElements (localErrors, errorKeys);
  if (localErrors == null)
    localErrors = "";
  el.setAttribute ("localErrors", localErrors);
  }

// --------------------------------------------------------------------------
// mark elements
// --------------------------------------------------------------------------
function getDelegationTarget (el, tagName)
  {
  if (el == null || typeof el == "undefined" || tagName == null || typeof tagName == "undefined")
    return null;
  while (el != null)
    {
    if (!el.attributes)
      return null;
    var myNodeName = el.nodeName;
    if (myNodeName != null && myNodeName.toUpperCase () == tagName.toUpperCase () && el.getAttribute ("errorDelegationTarget") == "true")
      break;
    el = el.parentNode;
    }
  return el;
  }

function getElementToMark (el)
  {
  if (el == null || typeof el == "undefined")
    return null;
  if (el.attributes)
    {
    var delegator = el.getAttribute ("delegateError");
    if (delegator != null && delegator != "")
      {
      var delegationTarget = getDelegationTarget (el, delegator);
      if (delegationTarget != null)
        return delegationTarget;
      }
    }
  return el;
  }

function markElementAsError (el, doit)
  {
  var elToMark = getElementToMark (el);
  if (elToMark != null)
    {
    var elClassName = getPlainClassName (elToMark);
    if (doit)
      elClassName = addClassPart (elClassName, "errorNeutralName");
    elToMark.className = elClassName;
    }
  }

// --------------------------------------------------------------------------
// global error elements
// --------------------------------------------------------------------------
function getErrorElements (root, errorKeysList)
  {
  var result = null;
  for (var i = 0; i < root.childNodes.length; i ++)
    {
    var child = root.childNodes[i];
    if (!child.attributes)
      continue;
    if (hasIntersectWithList (child.getAttribute ("errorKeys"), errorKeysList))
      {
      if (result == null)
        result = new Array ();
      result.push (child);
      }
    var subResult = getErrorElements (child, errorKeysList);
    if (subResult != null)
      {
      if (result == null)
        result = subResult;
      else
        addAll (result, subResult);
      }
    }
  return result;
  }

function getAllErrorElements (errorKeys)
  {
  if (isEmptySet (errorKeys))
    return null;
  var result = new Array ();
  var errorKeysList = errorKeys.split ("|");
  for (var i = 0; i < document.forms.length; i++)
    addAll (result, getErrorElements (document.forms[i], errorKeysList));
  return result;
  }

// --------------------------------------------------------------------------
// fire error events
// --------------------------------------------------------------------------
function shouldBeMarked (el)
  {
  if (el == null || typeof el == "undefined" || !el.attributes)
    return false;
  return !isEmptySet (el.getAttribute ("localErrors")) || hasIntersect (globalErrors, el.getAttribute ("errorKeys"));
  }

function isRowAppender (el)
  {
  var tagName = el.nodeName;
  return tagName != null && tagName.toUpperCase () == "TR" && el.getAttribute ("appendMessageRows") == "true";
  }

function fireGlobalErrorEvent (errorKey, text)
  {
  if (errorKey == null || errorKey == "" || typeof errorKey == "undefined")
    return;
  registerGlobalError (errorKey);
  var errorElements = getAllErrorElements (errorKey);
  for (var i = 0; i < errorElements.length; i++)
    {
    var errorElement = errorElements[i];
    markElementAsError (errorElement, true);
    if (isRowAppender (errorElement))
      {
      if (text != null && typeof text != "undefined")
        makeErrorText (errorElement, errorKey, text);
      }
    }
  return true;
  }

function fireGlobalError (errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  return fireGlobalErrorEvent (errorKey, getErrorText (errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9));
  }

function cleanGlobalErrors (errorKeys)
  {
  deregisterGlobalErrors (errorKeys);
  var errorElements = getAllErrorElements (errorKeys);
  for (var i = 0; i < errorElements.length; i++)
    {
    var errorElement = errorElements[i];
    if (!shouldBeMarked (errorElement))
      markElementAsError (errorElement, false);
    if (isRowAppender (errorElement))
      removeErrorTexts (errorElement, errorKeys);
    }
  }

function shouldReportLocalError (el, name)
  {
  if (!el.attributes)
    return false;
  return el.getAttribute ("name") == name || el.getAttribute ("reportLocalError") == "true";
  }

function fireLocalErrorEvent (errorKey, el, text)
  {
  if (errorKey == null || errorKey == "" || typeof errorKey == "undefined")
    return;
  if (el == null || typeof el == "undefined")
    return;
  var name = el.getAttribute ("name");
  errorKey = name + ":" + errorKey;
  do
    {
    if (shouldReportLocalError (el, name))
      {
      registerLocalError (errorKey, el);
      markElementAsError (el, true);
      if (isRowAppender (el) && text != null && typeof text != "undefined")
        {
        makeErrorText (el, errorKey, text);
        break;
        }
      }
    el = el.parentNode;
    }
  while (el != null);
  return true;
  }

function fireLocalError (errorKey, el, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  return fireLocalErrorEvent (errorKey, el, getErrorText (errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9));
  }

function cleanLocalErrors (errorKeys, el)
  {
  var name = el.getAttribute ("name");
  do
    {
    if (shouldReportLocalError (el, name))
      {
      deregisterLocalErrors (errorKeys, el);
      if (!shouldBeMarked (el))
        markElementAsError (el, false);
      if (isRowAppender (el))
        {
        removeErrorTexts (el, errorKeys);
        break;
        }
      }
    el = el.parentNode;
    }
  while (el != null);
  }

// --------------------------------------------------------------------------
// markError, fc and validation methods
// --------------------------------------------------------------------------
var validateFilledErrorRow = false;
var silentValidateFilled = true;

function useErrorLines (el)
  {
  if (el == null || typeof el == "undefined")
    return null;
  return el.getAttribute ("errorLines") == "true";
  }

function markFormElementError (el, hasFocus, errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  var key = "undefined";
  if (errorKey != null && errorKey != "undefined")
    key = errorKey;
  fireLocalError (key, el, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9);
  if (getElementType (el) != "hidden")
    setFocus (el, hasFocus);
  return true;
  }

function markRegularElementError (el, hasFocus, errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  var cn = el.className;
  if (!cn)
    cn = "";
  if (!el.getAttribute("regularClass"))
    el.setAttribute("regularClass", cn)
  el.className = "errorNeutralName";
  setFocus (el, hasFocus);
  if (errorKey && errorKey != "filled")
    {
    var alertText = getErrorText(errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9);
    if (alertText && alertText != "")
      alert(alertText);
    }
  return true;
  }

function markError (el, hasFocus, errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9)
  {
  if (useErrorLines (el))
    return markFormElementError (el, hasFocus, errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9);
  return markRegularElementError (el, hasFocus, errorKey, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9);
  }

function unmarkFormElementError (el)
  {
  var errorKeys = el.getAttribute ("errorKeys");
  if (errorKeys != null && errorKeys != "")
    cleanGlobalErrors (errorKeys);
  var localErrors = el.getAttribute ("localErrors")
  if (localErrors != null && localErrors != "")
    cleanLocalErrors (localErrors, el);
  }

function hasErrorClass (el)
  {
  if (el == null || typeof el == "undefined")
    return false;
  return (el.className.indexOf("error") == 0);
  }

function getRegularClass (el)
  {
  var rc = el.getAttribute ("regularClass");
  if (!rc)
    rc = "app";
  return rc;
  }

function unmarkRegularElementError (el)
  {
  if (hasErrorClass (el))
    el.className = getRegularClass (el);
  }

function unmarkError (el)
  {
  if (useErrorLines (el))
    unmarkFormElementError (el);
  unmarkRegularElementError (el);
  }

function markErrorField (fieldName, hasFocus)
  {
  return markError (firstInput (fieldName), hasFocus);
  }

function unmarkErrorField (fieldName)
  {
  unmarkError (firstInput (fieldName));
  }

function makeFirstErrorText (newText, text)
  {
  if (text != null && text != "")
    return text;
  return newText;
  }

function makeFilledErrorText (newTxt, text)
  {
  if (text == null || text == "")
    return newTxt;
  return "Bitte füllen Sie die markierten Felder aus.";
  }

function checkElementFilled (el, errText, text)
  {
  if (el != null && isEmptyField (el))
    {
    markError (el, text != null, "filled");
    text = makeFilledErrorText (errText, text);
    }
  return text;
  }

function checkFieldFilled (name, errText, text)
  {
  return checkElementFilled (inputField (name), errText, text);
  }

// --------------------------------------------------------------------------
// conditional handling
// --------------------------------------------------------------------------
var activeConditions = "|";
var allOptionFlags = "|";
var immediateConditionalRendering = true;
var fancyConditionalRendering = true;

function stopConditionalRendering ()
  {
  immediateConditionalRendering = false;
  }

function startConditionalRendering (fancy)
  {
  immediateConditionalRendering = true;
  fancyConditionalRendering = fancy;
  renderConditionals ();
  fancyConditionalRendering = true;
  }

function toggleConditional (key)
  {
  changeConditional (key, posOfConditional (key));
  }

function toggleOptional (key)
  {
  changeConditional (key, posOfConditional (key));
  }

function setConditional (key, on)
  {
  var pos = posOfConditional (key);
  if (on && pos != -1 || !on && pos == -1)
    return;
  changeConditional (key, pos);
  }

function changeConditional (key, pos)
  {
  if (pos == -1)
    activeConditions += key + "|";
  else
    activeConditions = activeConditions.substr(0, pos) + activeConditions.substr(pos+1+key.length);
  changeOptionalLink (key, pos == -1);
  if (immediateConditionalRendering)
    renderConditionals ();
  }

function changeOptionalLink (key, on)
  {
  var linkEl = document.getElementById ("togglelink" + key);
  if (linkEl != null)
    {
    if(on)
      linkEl.className = linkEl.className+' down';
    else
      linkEl.className = linkEl.className.replace(" down","");
    var settingFieldName = linkEl.getAttribute ("settingField");
    if (settingFieldName != null && settingFieldName != "")
      {
      var settingField = firstInput (settingFieldName);
      if (settingField)
        settingField.value = on ? "1" : "0";
      }
    }
  }

function hasConditional (key)
  {
  return posOfConditional(key) != -1;
  }

function couldHaveConditional (key)
  {
  return (allOptionFlags.indexOf("|" + key + "|") != -1);
  }

function posOfConditional (key)
  {
  return activeConditions.indexOf("|" + key + "|");
  }

function renderConditionals ()
  {
  if (typeof fancyWorkTodos == "undefined")
    fancyConditionalRendering = false;
  for (var i = 0; i < document.forms.length; i++)
    renderConditionalChilds (document.forms[i]);
  if (fancyConditionalRendering)
    startFancyTodo ();
  }

function renderConditionalChilds (root, immediate)
  {
  var foundVisible = false;
  for (var i = 0; i < root.childNodes.length; i ++)
    {
    var child = root.childNodes[i];
    if (child.tagName == undefined)
      continue;
    var conds = child.getAttribute ("conditions");
    var visible = true;
    if (conds)
      {
      visible = conditionalChildVisible (conds, child, immediate);
      if (visible)
        foundVisible = true;
      }
    if (visible && renderConditionalChilds (child, immediate))
      foundVisible = true;
    }
  return foundVisible;
  }

function conditionalChildVisible (conds, child, immediate)
  {
  var carr = conds.split('|');
  var visible = true;
  for (var i = 0; i < carr.length; i++)
    {
    if (carr[i] == "_hasVisibleChilds")
      visible = renderConditionalChilds (child, true);
    else
      visible = hasConditional (carr[i]);
    if (!visible)
      break;
    }
  if (fancyConditionalRendering && !immediate)
    addFancyTodo (child, visible, false);
  else
    makeVisible (child, visible);
  return visible;
  }

function makeVisible (el, on)
  {
  if (el.tagName == "SPAN")
    makeSpanVisible (el, on);
  else
    makeBlockVisible (el, on);
  }

function showConditional (key, on)
  {
  if (useConditionals)
    setConditional (key, on);
  else
    {
    for (var i = 1; i < 999; i ++)
      if (!setVisibility(key + i, on))
        return false;
    }
  }

function fireOnChange (name)
  {
  var field = firstInput (name);
  if (field.fireEvent)
    field.fireEvent ("onchange");
  else if (document.createEvent)
    {
    var evt = document.createEvent ("Events");
	  evt.initEvent ("change", null, null);
		field.dispatchEvent (evt);
    }
  }

function getStreetHouseNo (street)
  {
  if (street && street.length > 0)
    {     
    var matchRes = street.match(/(\d{1,4}\s*\w*)\s*(\W\s*\d{0,4}\s\w*)*$/);
    if (matchRes && matchRes.length > 0 && matchRes[0] != street)
      return matchRes[0];
    }
  return "";
  }

function getStreetOnly (street)
  {
  if (street && street.length > 0)
    {     
    var hn = getStreetHouseNo(street);
    if (hn && hn.length > 0 && street.lastIndexOf(hn) >= 0 && (street.length - street.lastIndexOf(hn)) == hn.length )
      {
      return street.substr(0, street.length-hn.length);
      }
    }
  return street;   
  }