// javascript function for easydb


function setFocus(el) {
   alert(el);
   if (window.oldFocus) {
      removeGraphicalFocus(window.oldFocus);
      window.oldFocus = null;
   }
   addGraphicalFocus(el);
}

function addGraphicalFocus(el) {
   el.style.backgroundColor = '#d0d0d0';
   window.oldFocus = el;
}

function removeGraphicalFocus(el) {
   el.style.backgroundColor = '';
}

function setEditlinkOnClick(div_id) {
   $(div_id).setAttribute('onclick', "setFocus(this);");
}

var faktura_calculators = new Array();
var values_by_gcell_id;


function faktura_update() {
   values_by_gcell_id = new Array();
   if (faktura_calculators.length == 0) return;

   for (var j=0; j < 2; j++) {    
     for (var i=0; i < faktura_calculators.length; i++) {  
        faktura_calculators[ i ].calculator_func();
     }
   }
//   setTimeout('faktura_update();', 1000);
}

function faktura_register_calculator(gcell_id, span_id, inside_editlinks, precision, update_element, calculator_code) {
    
   var f = " \
var myspan = $('" + span_id +"'); \
if (myspan) { \
  var myfunc = function() { "+ calculator_code+" }; \
  var myvar = myfunc();   \
  if ("+precision+" >= 0) { \
     myvar = IntegerDecimalFormatted(myvar / Math.pow(10, "+precision+"), "+precision+"); \
     add_value_by_gcell_id( "+gcell_id+", myvar * Math.pow(10, "+precision+"),"+inside_editlinks+" ); \
     $('" + span_id +"').setAttribute('value', myvar * Math.pow(10, "+precision+"));\
  } else { \
     add_value_by_gcell_id( "+gcell_id+", myvar,"+inside_editlinks+" ); \
     $('" + span_id +"').setAttribute('value', myvar);\
\
  }  \
  $('" + span_id +"').innerHTML = myvar;  \
  if ('" + update_element +"') { \
      var myel = document.getElementsByName('" + update_element +"')[0];\
      if (myel) { \
          myel.value = myvar; \
      }\
  } \
}\
";
  
   eval ("var func = function() { "+ f +" };");

   var obj = {
      gcell_id : gcell_id,
      span_id : span_id,
      calculator_func : func
   }
   
   faktura_calculators.push(obj);
}



function add_value_by_gcell_id(id, value, inside_editlinks) {
   if (inside_editlinks) {
       if (typeof values_by_gcell_id[ id ] == 'undefined') {
          values_by_gcell_id[ id ] = new Array();
       }
       values_by_gcell_id[ id ].push(value);
   } else {
       values_by_gcell_id[ id ] = value;
   }
}

function IntegerDecimalFormatted(amount, precision)
{
       if (amount.replace) amount = amount.replace(/,/g, ".");

       var appendString = '';

       if (precision > 0) {
           appendString = appendString + '.';
       }
        
       for (var j=0; j<precision; j++) {
           appendString = appendString + '0';
       }

       var i = parseFloat(amount);
	if(isNaN(i)) { i = 0; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + ( 0.5 / Math.pow(10, precision))) * Math.pow(10, precision));
	i = i / ( Math.pow(10, precision) );

	s = new String(i);
	if(s.indexOf('.') < 0) { s += appendString; }

        while (s.length - s.indexOf('.') - 1  < precision) {
           s = s + '0';
        };

	s = minus + s;

	return s;
}

function updateThesaurusPath(el) {
  // this is used by DIREKTLINK.driver.php
  updateInnerHTML(el,'thesaurus',el.options[ el.selectedIndex ].getAttribute('path'));
}


function updateInnerHTML(el, name, innerHTML) {
  // inside the parentNode, look for an element named "name"
  // and update the innerHTML to "innerHTML"

  var els = find_elements_by_id(name, ["DIV"], "name", el.parentNode);

  if (els.length > 1) {
     alert("updateInnerHTML: "+els.length+" DIVs found with name='"+name);
  }
  if (els.length > 0) {
      if (el.options[ el.selectedIndex ].value.length == 0 && els[0].oldInner) {
         els[0].innerHTML = els[0].oldInner;
      } else {
         if (!els[0].oldInner) {
           els[0].oldInner = els[0].innerHTML;
         }
         els[0].innerHTML = innerHTML;
      }
  }

}

function checkIntegerDecimal(el, precision) {
  el.value = IntegerDecimalFormatted(el.value, precision);
}

function getScrollY ( ) {
	if ( window.pageYOffset )
		return window.pageYOffset ;
	if ( document.body.scrollTop )
		return document.body.scrollTop ;
	if ( document.documentElement.scrollTop )
		return document.documentElement.scrollTop ;
    return 0 ;
}

function getScrollX ( ) {
	if ( window.pageXOffset )
		return window.pageXOffset ;
	if ( document.body.scrollLeft )
		return document.body.scrollLeft ;
	if ( document.documentElement.scrollLeft )
		return document.documentElement.scrollLeft ;
    return 0 ;
}

function cursorWithinArea2 ( x, y, b ) {
    if (!b) {
        alert('cursorWithinArea: '+id+' not found.');
    }
    if ( ! b ) 
        return ; 
        if ( x < ( getLeft(b) ) || y < ( getTop(b) ) ) 
        return 0 ; 
        if ( x >= (getLeft(b)+b.offsetWidth+1) || y >= (getTop(b)+b.offsetHeight+1) ) 
          return 0 ; 
             return 1 ; 
            }


function cursorWithinArea ( x, y, id ) {
    var b = document.getElementById(id) ;  
    if (!b) {
        alert('cursorWithinArea: '+id+' not found.');
    }
    if ( ! b ) 
        return ; 
        if ( x < ( getLeft(b) ) || y < ( getTop(b) ) ) 
        return 0 ; 
        if ( x >= (getLeft(b)+b.offsetWidth+1) || y >= (getTop(b)+b.offsetHeight+1) ) 
          return 0 ; 
             return 1 ; 
            }

            function cursorWithinAreaTolerance ( x, y, id, tolerance ) {
                var b = document.getElementById(id) ;  
                if (!b) {
                    alert('cursorWithinAreaTolerance: '+id+' not found.');
                    return ; 
                }
                if ( x < ( getLeft(b) - tolerance ) || y < ( getTop(b) - tolerance ) ) 
                    return 0 ; 
                if ( x >= (getLeft(b)+b.offsetWidth+1 + tolerance ) || y >= (getTop(b)+b.offsetHeight+1 + tolerance ) ) 
                    return 0 ; 
                return 1 ; 
            }

            function integer ( a ) {
                return parseInt(String(a)) ; 
            }









function getTop(el) {
  var y=0;
  if (el.offsetParent) {
     y = getTop(el.offsetParent);
  }
  if (el.offsetTop) {
    y = y+el.offsetTop;
  }
  return y;
}


function getWidth(el) {
   return el.offsetWidth;
}

function getHeight(el) {
   return el.offsetHeight;
}


function getLeft(el) {
  var x=0;

  if (el.offsetParent) {
     x = getLeft(el.offsetParent);
  }
  if (el.offsetLeft) {
    x = x+el.offsetLeft;
  }
  return x;
}



function findWindow(startwindow, target) {
  // recursively find window
  if (startwindow.name == target) {
     return startwindow;
  }
  // do we have frames?
  if (startwindow.frames && startwindow.frames.length > 0) {
     for (var i=0; i<startwindow.frames.length; i++) {
         var found = findWindow(startwindow.frames[i], target);
         if (found) {  
            return found;
         }
     }
  }
  return;
}

function cancelBubble(event) {
  if (typeof event.stopPropagation == 'function') { 
     event.stopPropagation();
  } else {
     event.cancelBubble = true;
  }
}

function markDiv(div, color) {
  // this function marks a div, by setting its background
  var cdiv = $(div);
  if (typeof cdiv.oldBg == 'undefined') {
     cdiv.oldBg = cdiv.style.backgroundColor;
  } 
  cdiv.style.backgroundColor = color;
}

function unmarkDiv(div) {
  var cdiv = $(div);
  cdiv.style.backgroundColor=cdiv.oldBg;
}



function sum(arr) {
   return add(arr);
}

function add(arr) {

   if (typeof arr=="undefined") {
      return;
   }
   var sum = 0;
   for (var i=0; i<arr.length; i++) {
        sum += arr[i];
   }
   return sum;
}

function last(arr) {
   if (typeof arr == 'undefined') {
     return null;
   }
   if (arr.length > 0) {
      return arr[arr.length-1];
   }
   return null;
}

// for ajax callbacks
function errFunc(t) {
   alert('Error ' + t.status + ' -- ' + t.statusText);
}

function handlerFunc(t) {
   eval(t.responseText);
}

function setField(name, value) {
   // set value of the element with the atttribute field_name
   var els = find_elements_by_id(name,['INPUT','SELECT'], 'field_name');
   els[0].value=value;
}


function concatValuesFromForm(fo) {
   if (!fo || !fo.elements) { 
      return "";
   }
   var all = new Array();
   for (var i=0; i<fo.elements.length; i++) {
        var name = fo.elements[i].getAttribute("field_name");
        if (name) {
            all.push(encodeURIComponent(name)+"[]="+encodeURIComponent(fo.elements[i].value));
        }
   }
   if (all.length > 0) {
      return "&"+all.join("&");
   } 
   return "";
}


var elementsUnderSurveillance = new Array();

function addElementToSurveillance(el, functionToGetValue) {
   if (!el) {
     alert("addElementToSurveillance: missing element!");
     return;
   }

   var myfunc = function() {
       var turned_on = false;
       var default_div = null;

       for (var i=0; i<so.choices.length; i++) {
           if (so.choices[i].case_default) {
              default_div = so.choices[i].enable_div;
           }

           if (so.functionToGetValue(el) == so.choices[i].value) {
              so.choices[i].enable_div.style.display='block';
              turned_on = true;
           } else {
              so.choices[i].enable_div.style.display='none';
           }
       }
       if (!turned_on && default_div) {
          default_div.style.display='block';
       }
   };

   var so = { element: el, 
              functionToGetValue: functionToGetValue,
              checkSurveillanceStatus: myfunc,    
              choices: new Array() 
            };

   if (so.functionToGetValue(el) == null) {
      alert("addElementToSurveillance: cannot get value\n from gcell, make sure you select the column");
      return;
   }

   if (!el.oldonchange) {
      el.oldonchange =  el.onchange;
   }

   el.onchange = function() {
       if (el.oldonchange) {
          el.oldonchange();
       }
       so.checkSurveillanceStatus();
   }    
   
   el.underSurveillance = true;

   elementsUnderSurveillance.push(so);
}


function addSurveillanceChoice(choice, enable_div, case_default) {


     // adds a choice to the last
     if (!elementsUnderSurveillance.length) {
        alert("addSurveillanceChoice called without surveilled element");
        return;
     }
     var so = elementsUnderSurveillance[elementsUnderSurveillance.length-1];

     so.choices.push( 
         { value: choice, 
           case_default: case_default,
           enable_div: enable_div });


     so.checkSurveillanceStatus();
}


function find_elements_by_id(id, tagNames, attributeName, start) {
   // runs through the dom tree, to find elements where the attribute "attributeName"
   // equals "id"
   if (!start) {
     start = document;
   }

   var elements = new Array();
   for (var j=0; j < tagNames.length; j++) {
      var allInputs = start.getElementsByTagName(tagNames[j]);
      for (var i=0; i < allInputs.length; i++) {  
         if (allInputs[i].getAttribute(attributeName) == id) {
             var s = allInputs[i];
             elements.push(s);
         }            
      }
   }
   return elements;
}

function setFocusOnOtherToggleLink ( element, id ) {
    both = find_elements_by_id(id,'a','iAmToggleLink');
    if ( both.length != 2 ) 
        return ;
    if ( both[0] != element) { 
        if ( both[0].style.display = 'none' ) 
            both[0].style.display = 'block ' ; 
        both[0].focus();

    }
    else { 
        if ( both[1].style.display = 'none' ) 
            both[1].style.display = 'block ' ; 
        both[1].focus();
    }
}


// this callback is used by  elements inside the form which require autosave 
function edit_autosave() {  
   if (typeof edit_autosave_form != "undefined") { 
      return submit_autosave(edit_autosave_form);
   }
   return false;
}

function submit_autosave(id_of_form) {
   var fo = $(id_of_form);
   fo.target = 'edit_useme_iframe';
   submit_current_form(fo, 'autosave','Y');
   fo.target = '';
   return true;
}


function get_current_form(el) {
    // climbs up the domtree and stops at a form
    if (el.tagName == 'FORM') {
        return el;
    } 
    if (el.parentNode) {  
        return get_current_form(el.parentNode);
    }
    alert("get_current_form: no form for "+el+" found.");
}


function submit_current_form(el, field_name, value) {
        // el: element which received the click
        // field_name: form field which is set to value (legacy code)
        // value
    var fo = get_current_form(el);
    if (fo) {
        if (field_name) {
            if (!fo.elements[field_name]) {
               alert("Missing "+field_name+" in FORM. Make sure you have a hidden element.");
               return false;
            }
            fo.elements[field_name].value = value;
        }
        if (fo.onsubmit) {
            if (fo.onsubmit() == false) {
                return false;
            }
        }
        fo.submit();
        return false;
    }
}


function value_of_select(name_of_select) {
   var el = document.getElementsByName(name_of_select)[0];
   if (el) {
      var value = el.options[el.selectedIndex].getAttribute('bare_value');
      if (el.precision) {
         return value * Math.pow(10, el.precision);
      }
      return value;
   }   
}

function direktlink(id,field) {
   // gets an attribute from a gcell element
   var gcells = find_elements_by_id(id, ["SELECT"], "gcell_id");
   if (gcells.length == 0) { 
        return alert("gcell with id:"+id+" not found, or is no SELECT.");
   }
   return gcells[0].options[gcells[0].selectedIndex].getAttribute("db__"+field);
}

function gcell_element(id) {
   var gcells = find_elements_by_id(id, ["INPUT","SELECT","SPAN"], "gcell_id");
   if (gcells.length > 0) {
      return gcells[0];
   }
   return null;
}

function gcell(id, prefix) {
   var gcells = find_elements_by_id(id, ["INPUT","SELECT","SPAN"], "gcell_id");

   var values = new Array();
   var ret = -1;

   for (var i=0; i<gcells.length; i++) {
      if (prefix) {
         if ( gcells[i].getAttribute("prefix") == prefix ) {
            ret = i;    
         }
      } else {
         if (gcells[i].getAttribute("prefix")) { 
             ret = "list";
         }
      }
      if (!gcells[i].getAttribute("prefix") && gcells.length == 1) { 
         ret = 0;
      }

      if (gcells[i].precision) {
         values.push( gcells[i].value * Math.pow(10, gcells[i].precision) );
      } else { 
         if (gcells[i].tagName == "INPUT" && gcells[i].type == "checkbox") {
            if (gcells[i].checked) {
               values.push( "t" );
            } else {
               values.push( "f" );
            }
         } else {
            if (gcells[i].tagName == "SPAN") {
               values.push(Math.ceil(gcells[i].getAttribute("value")));              
            } else {
               //  values.push(Math.ceil(gcells[i].value));
               values.push(gcells[i].value);
            }
         }
       }
   }
   // alert("id:"+id+"prefix:"+prefix+" gcell count:"+gcells.length+":="+values.join(","));
   if (ret == "list") {
      return values;
   }

   if (prefix && ret == -1) {
      // prefix not found
      return null;
   }

// henk

   if (ret > -1) {
      return values[ret];
   }

   if (ret == -1 && values.length > 0) { 
      if (values.length > 1) alert("gcell: too many values found!");
      return values[0];
   }
//   alert("gcells: "+gcells.length+" gcell: "+id+" prefix:"+prefix+" not found!");
}

function value_by_name(name_of_element) {
   var el = document.getElementsByName(name_of_element)[0];
   if (el) {
      if (el.precision) {
         return el.value * Math.pow(10, el.precision);
      }

      return el.value;
   } 
   return false;
}

function value_by_id(id_of_element) {
   var el = $(id_of_element);
   if (el) {
      return el.value;
   } 
   return false;
}

function abs ( x ) {
    if ( x < 0 ) 
        return -x ; 
    return x ; 
}

function getLastDIVChild ( e ) {
    var c = e.lastChild ; 
    while ( c ) {
        if ( c.nodeName == 'DIV' && ( c.id.substr(0,5) != 'debug' ) ) {
            return c ; 
        }
        c = c.previousSibling ; 
    }
    return null ; 
}

function removeInvisibleDivs(el, idStartsWith) {
  // this function walks through the dom tree an kills all invisible divs
  // we use this before submitting forms!

  var removeDivs = new Array();
  var allDivs = el.getElementsByTagName('DIV');
  for (var i=0; i < allDivs.length; i++) {  
      if (
        (!idStartsWith || allDivs[i].id.indexOf(idStartsWith) == 0)   
        && allDivs[i].style.display=='none') {
         removeDivs.push(allDivs[i].id);
      }
  }

  for (var i=0; i<removeDivs.length; i++) {  
      var el = $(removeDivs[i]);
      if (el) el.parentNode.removeChild(el);
  }
}

currentTabs = new Array();

tabsCallbacksDeactivate = new Array();
tabsCallbacksActivate = new Array();

function getTabHintsUrl() {
    var hints = '';
    for (tab_id in currentTabs) {
        if (typeof currentTabs[tab_id] == 'function') {
          // prototype 
          continue;
        }
        hints = hints + tab_id+','+currentTabs[tab_id]+';';
    }
    if (document.getElementsByName('tabHint').length) {
       document.getElementsByName('tabHint')[0].value = hints;
    }
    return hints;
}

function activate(tabs_id, tab_id) {
   if (typeof currentTabs[tabs_id] == 'undefined') {
      currentTabs[tabs_id] = 0;
   } 
   tab_off(get_tab(tabs_id, currentTabs[tabs_id]));
   tab_on(get_tab(tabs_id, tab_id));

   tabDeactivated(tabs_id, currentTabs[tabs_id]);
   currentTabs[tabs_id] = tab_id;
   tabActivated(tabs_id, tab_id);
}

function tabActivated(tabs_id, tab_id) {
   if (typeof processReloadUrl=='function') {
      processReloadUrl();
   }
   if (tabsCallbacksActivate[tabs_id+':'+tab_id]) {
      tabsCallbacksActivate[tabs_id+':'+tab_id]();
   }
}

function tabDeactivated(tabs_id, tab_id) {
   if (typeof processReloadUrl=='function') {
      processReloadUrl();
   }
   if (tabsCallbacksDeactivate[tabs_id+':'+tab_id]) {
      tabsCallbacksDeactivate[tabs_id+':'+tab_id]();
   }
}

function tab_off(arr) {
   arr.head.style.display='none';
   arr.head_off.style.display='block';
   if (arr.body) {
       arr.body.style.display='none';
   }
}

function tab_on(arr) {
   arr.head.style.display='block';
   arr.head_off.style.display='none';
   if (arr.body) {
       arr.body.style.display='block';  
   }
}

function get_el(id) {
   el = document.getElementById(id);
   if (!el) {
      // alert(id+' not found!');
   }
   return el;
}

function get_tab(tabs_id, tab_id) {
   arr = new Array();

   arr.head = get_el('tabhead_'+tabs_id+'_'+tab_id);

   if (!arr.head) {
      alert('tabhead_'+tabs_id+'_'+tab_id+' not found!');
      return;
   }
   arr.head_off = get_el('tabhead_off_'+tabs_id+'_'+tab_id);
   arr.body = get_el('tabbody_'+tabs_id+'_'+tab_id);
   return arr;
}



function bubbleHref() {
   document.write('<div id=mememe></div>');
   var el = document.getElementById('mememe');
   var mylink = el;

   while (mylink.previousSibling && mylink.tagName != 'A') {
       mylink = mylink.previousSibling;
   }

   var modify_el = el;
   while (modify_el.parentNode) {
      modify_el = modify_el.parentNode;
      if (modify_el.getAttribute('receive_bubble_href')) {
         modify_el.extra_onclick = function () { 
             var use_win;
             if (mylink.target) {
                 use_win = findWindow(top, mylink.target);
             } else {
                 use_win = window;
             }
             use_win.document.location.href = mylink.href; 
         };
         break;
      }
   }
   el.parentNode.removeChild(el);
}

var oldValues = new Array();
var valuesChanged = 0;



function applyNewValues() {
   // applies all changes and changes the color back to unmarked

   for (var name in oldValues) {  // prototype fixed
     if (typeof oldValues[name] == 'function') {
         continue;
     }
     if (document.getElementsByName(name).length > 0) {
         oldValues[name] = document.getElementsByName(name)[0].value;
         checkValue(name);
     }
   }
}

function setOldValue(name, value) {
   if (typeof value == 'string') {
       value = value.replace(/\n|\r/g,"");
   }
   oldValues[name] = value;
   checkValue(name);
}

function resetValue(name) {
     var el=document.getElementsByName(name)[0];
     if (el.value != oldValues[name]) { 
         el.cacheValue = el.value;
         el.value=oldValues[name]; 
     } else {
         if (el.cacheValue) {
             el.value = el.cacheValue;
             el.cacheValue = null;
         }
     }
     checkValue(name);
}

function checkValue(name) {

     var els = document.getElementsByName(name);

     if (els.length == 0) {
         return;
     }

     var el=els[0];

     if (typeof oldValues[name] == 'undefined') {
        return;
     }

     if (el.type == 'checkbox') {
         checkEl(el, el.checked != oldValues[name]);   
     } else {
         var value = el.value;
         if (typeof value == 'string') {
            value = value.replace(/\n|\r/g,"");
         }
         var changed = value != oldValues[name];
         checkEl(el,changed);
     }
}

var checkColor='#c0c0c0';
var checkErrColor='red';
var confirmText='confirm?';

function setConfirmText(c) {
    confirmText = c;
}

function confirmChanges() {
     if (valuesChanged != 0) {
         return confirm(confirmText);
     }
     return true;
}

function setCheckColors(color, err_color) {
    checkColor = color;
    checkErrColor = err_color;    
}

function checkEl(el, check) {
     var col; 
         // alert('check:'+check+':'+el.name+':'+el.type+':'+el.value+':'+oldValues[name]);
     if (check) {
         if (!el.alreadyChanged) {
             valuesChanged++;
         }
         el.alreadyChanged=1;
         el.style.backgroundColor=checkColor;
     } else { 
         if (el.alreadyChanged) {
             valuesChanged--;
         }
         el.alreadyChanged=0;
         el.style.backgroundColor=''; 
     }
}

function markValue(name) {
     var col; 
     var el=document.getElementsByName(name)[0]; 
     el.alreadyChanged=1;
     valuesChanged++;
     el.style.backgroundColor=checkErrColor;
}


function extendHref(el) {
   if (!el.origHref) {
     el.origHref=this.href;
   } else {
     el.href=this.origHref;
   }

   for (var e in document.execPHPselects) { // prototyp fixed
      if (typeof document.execPHPselects[e] == "function") {
          continue;
      }

      var k = document.execPHPselects[e];
      var v = document.getElementsByName(k[0])[0];
      if (v) {
         var use_value = v.options[v.selectedIndex].value;
         // var use_value = v.origValue;
         el.href = el.href+"&gcell_values[]="+encodeURIComponent(k[1]+":"+use_value);
      } else {
         alert("CALLBACK_exec_php:\'"+k[0]+"\' not found");
      }
   }
}


//g_mouseDevice.registerListener( null );

var window_width;
var window_height;

function get_window_sizes() {
  if (typeof window.innerWidth!='undefined') {
     window_width = window.innerWidth;
     window_height = window.innerHeight;
  } else {
     if (document.documentElement && 
       typeof document.documentElement.clientWidth!='undefined' && 
       document.documentElement.clientWidth!=0) {
    window_width = document.documentElement.clientWidth;
    window_height = document.documentElement.clientHeight;
   } else {
      if (document.body && 
          typeof document.body.clientWidth!='undefined') {
          window_width = document.body.clientWidth;
          window_height = document.body.clientHeight;
      }
   }
 }
}

get_window_sizes(); 


function addCodeToHandler(handler_name, code) {
    var oldhandler = "";
    eval (" \
var oldhandler=null;\
\
if (typeof "+handler_name+" != 'undefined' && "+handler_name+" != null) {\
   oldhandler = ''+"+handler_name+";\
}\
");
    if (oldhandler) {
        code = oldhandler.substr(0, oldhandler.lastIndexOf("}")-1) + code + "}";
        eval( handler_name+" = "+code );
    } else {
        eval( handler_name+" = function() { "+code+" } ");
    }
}


function clearAllFormElements ( a ) {
    if ( ! a.getElementsByTagName ) return ; 
         var inputs = a.getElementsByTagName('input');
         for ( var k = 0 ; k < inputs.length ; k ++ ) { 
             if ( inputs[k].type == 'text' ) {
                 inputs[k].value = '' ; 
             } else if ( inputs[k].type == 'checkbox' ) {
                 inputs[k].checked = false ; 
             } else if ( inputs[k].type == 'hidden' && inputs[k].name.match(/^TL_/) ) {
                 resetElement(inputs[k].name.substring(3));
             }
         }
         var selects = a.getElementsByTagName('select');
         for ( var k = 0 ; k < selects.length ; k ++ ) {
             selects[k].selectedIndex = 0;
             for ( var kk = 0 ; kk < selects[k].options.length ; kk++ ) {
                   if (selects[k].options[kk].defaultSelected) {
                        selects[k].selectedIndex = kk;
                   };
             }
         }
}


function hideDivDisplay(id, clear_form) {
   div = document.getElementById(id);
   if (clear_form) {
      clearAllFormElements(div);
   }
   div.style.display='none';
   eval('top.divstatus_'+id+'=0;');
}

function showDivDisplay(id) {
   div = document.getElementById(id);
   div.style.display='block';
   eval('top.divstatus_'+id+'=1;');
}


var resizeTimeout = 0;

function setTimeoutForReload() {
   if (resizeTimeout) {
     clearTimeout(resizeTimeout);
   }
   resizeTimeout = setTimeout('reloadWindow()', 500);
}

function reloadWindow() {
  // reloads the window, firefox cannot reload the window inside the onresize handler
   document.location.reload();
}

function isWindow(object) {
  if (typeof object.name == 'string') {
      // ie & firefox, window
      return true;
  }
  return false;
}

function ezOpenWindow(handle) {
  if (typeof top.openWindows == 'undefined') {
      top.openWindows = new Array();
  }
  top.openWindows.push(handle);
  return handle;
}


function getChildElementByAttributeValue ( attribute, value, e ) {
    for ( var i = 0 ; i < e.childNodes.length ; i++ ) {
        if ( e.childNodes[i].getAttribute(attribute) == value ) {
            return e.childNodes[i];
        }
        else {
            var retVal = getChildElementByAttributeValue( attribute, value, e.childNodes[i] );
            if ( retVal != null ) 
                return retVal ; 
        }
    }
    return null ; 
}

function toggleDivDisplay(id, clear_form) {

   div = document.getElementById(id);

   if (!div) {
      alert('div '+id+' not found.');
      return;
   }
   if (div.style.display!='none') {
      hideDivDisplay(id, clear_form);
   } else {
      showDivDisplay(id);
  //    var toggleCounterPart = getChildElementByAttributeValue ( 'iAmToggleLink', id, div );
  //    if ( toggleCounterPart != null ) {
  //        toggleCounterPart.focus();
  //    }
   }
   
}

function hideDiv(id, clear_form) {
   div = document.getElementById(id);
   if (clear_form) {
     clearAllFormElements(div);
   }
   div.style.visibility='hidden';
}

function showDiv(id) {
   div = document.getElementById(id);
   div.style.visibility='visible';
}

function getChildElementByAttributeValue ( attribute, value, e ) {
    for ( var i = 0 ; i < e.childNodes.length ; i++ ) {
        if ( e.childNodes[i].getAttribute(attribute) == value ) {
            return e.childNodes[i];
        }
        else {
            var retVal = getChildElementByAttributeValue( attribute, value, e.childNodes[i] );
            if ( retVal != null ) 
                return retVal ; 
        }
    }
    return null ; 
}


function toggleDiv(id, clear_form) {
   div = document.getElementById(id);

   if (!div) {
      alert('div '+id+' not found.');
      return;
   }
   if (div.style.visibility!='hidden') {
      hideDiv(id, clear_form);
   } else {
      showDiv(id);
    //  var toggleCounterPart = getChildElementByAttributeValue ( 'iAmToggleLink', id, div );
    //  if ( toggleCounterPart != null ) {
    //      toggleCounterPart.focus();
    //  }
   }
   
}

function getRightMostChild ( e ) {
    while ( e.lastChild != null ) 
        e = e.lastChild ; 
    return e ; 
}

function copyContent_lookForBrotherCell ( cellID, currentNode ) {
    while ( currentNode ) {
        if ( currentNode.previousSibling ) {
            if ( currentNode.previousSibling.getAttribute && currentNode.previousSibling.getAttribute('gcell_id') == cellID ) 
                return currentNode.previousSibling ; 
            currentNode = getRightMostChild(currentNode.previousSibling) ; 
        }
        else if ( currentNode.parentNode && currentNode.parentNode.previousSibling ) {
            if ( currentNode.parentNode.previousSibling.getAttribute && currentNode.parentNode.previousSibling.getAttribute('gcell_id') == cellID ) 
                return currentNode.parentNode.previousSibling ; 
//            currentNode = currentNode.parentNode.previousSibling ; 
            currentNode = getRightMostChild(currentNode.parentNode.previousSibling) ; 
        }
        else if ( currentNode.parentNode ) {
            if ( currentNode.parentNode.getAttribute && currentNode.parentNode.getAttribute('gcell_id') == cellID ) 
                return currentNode.parentNode ; 
            currentNode = currentNode.parentNode ; 
        }
        else {
            return null ; 
        }
    }
}

function copyContent ( e ) {
    cellID = e.getAttribute('gcell_id');
    if ( ! cellID ) 
        return ; 

    //brotherNode = copyContent_lookForBrotherCell(cellID,e);
    inputs = document.getElementsByTagName('input') ; 
    for ( i = 0 ; i < inputs.length ; i++ ) {
        if ( inputs[i] == e ) 
            break ; 
    }

    brotherNode = null; 
    for ( j = i - 1 ; j >= 0 ; j-- ) {
        if ( inputs[j].getAttribute && inputs[j].getAttribute('gcell_id') == cellID ) {
            brotherNode = inputs[j] ; 
            break ; 
        } 

    }

    if ( ! brotherNode ) 
        return ; 
    if ( brotherNode.value ) 
        if ( brotherNode.value.length > e.value.length ) 
            e.value = brotherNode.value ; 
}

// KALENDER --------------------------------------------------------------------- START 

var g_calendars = new Object(); 

var g_activeCalendar = null ; 

function removeCalendar ( calendarID ) {
    if ( g_calendars[calendarID] ) {
        g_calendars[calendarID].closeCalendar();
        if ( $(g_calendars[calendarID].mainDivID) ) {
            e = $(g_calendars[calendarID].mainDivID) ; 
            e.parentNode.removeChild(e);
        }
        if ( g_activeCalendar == g_calendars[calendarID] ) 
            g_activeCalendar = null ; 
    }

}

function g_calendarCheckTargetValue ( calendarID ) {
    if ( g_calendars[calendarID].active == false ) 
        return ; 

    cal = g_calendars[calendarID] ; 

    newDate = parseDate ( cal.target.value, cal.formatStr ) ; 
    if ( newDate ) {
        if ( newDate.getMonth()    != cal.selectedMonth || 
             newDate.getDate()     != cal.selectedDay   ||
             newDate.getFullYear() != cal.selectedYear ) {
             cal.updateSelectedDay(newDate.getDate(),newDate.getMonth(),newDate.getFullYear()); 
        }
    }
    
    window.setTimeout('g_calendarCheckTargetValue("'+calendarID+'");',1000);
}

function Calendar( calendarID, target, formatStr, initSelectedDay) {
    this.now = new Date() ;
    this.dummy = new Date() ;
    this.dummy2 = new Date() ;
    this.dummy.setDate(1);
    this.days = ["Mo","Di","Mi","Do","Fr","Sa","So"];
    this.months = ["Januar","Februar","M&auml;rz","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"]; 
    this.daysPerMonth     = [31,28,31,30,31,30,31,31,30,31,30,31] ;     
    this.daysBeforeMonth  = [0,31,59,90,120,151,181,212,243,273,304,334] ;     
    this.focusMonth  = this.now.getMonth()     ; 
    this.focusYear   = this.now.getFullYear()  ;    
    this.target = target ; 
    this.id = calendarID ; 
    this.formatStr = formatStr ; 
    this.active = true ; 
    g_calendars[calendarID] = this ;     

	g_mouseDevice.registerListener( this );
    this.mouseRegistered = true ; 

    if ( initSelectedDay != null ) {
        this.selectedDay   = initSelectedDay.getDate()     ; 
        this.selectedMonth = initSelectedDay.getMonth()    ; 
        this.selectedYear  = initSelectedDay.getFullYear() ;
        this.focusMonth  = this.selectedMonth ; 
        this.focusYear   = this.selectedYear  ; 
    }
    else {
        this.selectedDay   = null ; 
        this.selectedMonth = null ; 
        this.selectedYear  = null ;
    }

    this.startUpdating = function ( ) {
        window.setTimeout('g_calendarCheckTargetValue("'+this.id+'");',1000);
    };

	this.onMouseDown = function(e) {

        mX = g_mouseDevice.getMousePosX() ; 
        mY = g_mouseDevice.getMousePosY() ; 
        if ( cursorWithinArea2(mX,mY,this.target) ) {
            return ; 
        }

        if ( cursorWithinArea(mX,mY,this.mainDivID) ) 
            return ; 

        this.closeCalendar();
        if ( $(this.mainDivID) ) {
            e = $(g_activeCalendar.mainDivID) ; 
            e.parentNode.removeChild(e);
        }

        if ( g_activeCalendar == this ) 
            g_activeCalendar = null ; 

        this.target.blur(); 

        return ; 
    };

	this.onMouseUp = function(e) {
    };

	this.onMouseMove = function(e) {
    };

    this.updateDayDiv = function ( ) {
        this.mainDiv.removeChild(this.dayDiv);  
        this.dummy.setMonth(this.focusMonth);
        this.dummy.setFullYear (this.focusYear) ;
        this.dayDiv = this.createDayDiv(this.dummy) ; 
        /*
        e = this.mainDiv.getElementsByTagName('A'); 
        for ( i = 0 ; i < e.length ; i ++ ) {
            if ( e[i].id == 'closeButton' ) {
                this.mainDiv.insertBefore(this.dayDiv,e[i].parentNode);                                              
                return ; 
            }
        }
        */
        this.mainDiv.appendChild(this.dayDiv);                                              
    };

    this.updateSelectedDay = function ( day, month, year ) {
        this.selectedDay   = day   ; 
        this.selectedMonth = month ; 
        this.selectedYear  = year  ; 
        this.focusYear     = year  ; 
        this.focusMonth    = month ; 
        this.updateDayDiv();
    };

    this.selectDay = function ( day, month, fullYear ) {
        if ( this.selectedDay != null ) {            
            e = document.getElementById(this.id+'_td_'+this.selectedDay+'_'+this.selectedMonth+'_'+this.selectedYear) ; 
            if ( e ) {
                if ( this.selectedDay == this.now.getDate() && this.selectedMonth == this.now.getMonth() && this.selectedYear == this.now.getFullYear() ) {
                    e.className = 'jsCalendarTodayTD' ;                 
                }
                else if (this.selectedMonth != this.focusMonth ) {
                    e.className = 'jsCalendarOtherMonthTD' ;              
                }
                else {
                    e.className = 'jsCalendarTD' ;              
                }
            }
        }
        this.selectedDay   = day ; 
        this.selectedMonth = month ; 
        this.selectedYear  = fullYear ; 
        document.getElementById(this.id+'_td_'+day+'_'+month+'_'+fullYear).className = 'jsCalendarSelectedTD' ;         

//        this.target.value=fullYear+'-'+this.printNumber(month+1)+'-'+this.printNumber(day);
        this.target.value= printDate(this.formatStr, fullYear,month+1,day) ;

        // Close calendar 
        this.closeCalendar();
        if ( $(this.mainDivID) ) {
            e = $(g_activeCalendar.mainDivID) ; 
            e.parentNode.removeChild(e);
        }

        if ( g_activeCalendar == this ) 
            g_activeCalendar = null ; 
    };

    this.getDaysBeforeMonth = function ( month, year ) {
        if ( month > 1 ) {
            if ( ( year % 4 == 0 ) && ( ( year % 100 != 0 ) || ( year % 400 == 0 )) ) {
                return this.daysBeforeMonth[month] + 1 ; 
            }
        }
        return this.daysBeforeMonth[month] ; 
    };

    this.getDaysPerMonth = function ( month, year ) {
        if ( month == 1 ) {
            if ( ( year % 4 == 0 ) && ( ( year % 100 != 0 ) || ( year % 400 == 0 )) ) {
                return 29 ; 
            }           
        }
        return this.daysPerMonth[month];
    };  
    
    this.getPrevMonth = function ( month, year ) {
        if ( month == 0 ) 
            return 11 ; 
        return month-1 ;    
    }
    
    this.getPrevMonthYear = function ( month, year ) {
        if ( month == 0 ) 
            return year-1 ; 
        return year;    
    }
    
    this.getNextMonth = function ( month, year ) {
        if ( month == 11 ) 
            return 0 ; 
        return month+1 ;    
    }
    
    this.getNextMonthYear = function ( month, year ) {
        if ( month == 11 ) 
            return year+1 ; 
        return year;    
    }
    
    this.checkDayForMonthLength = function ( day, month, year ) {
        if ( day > this.getDaysPerMonth(month,year) ) 
            return this.getDaysPerMonth(month,year) ; 
        return day; 
    };
    
    this.getWeekNumber = function ( fullYearP, monthP, dayP) {
        temp = new Date();
        this.dummy2.setFullYear(fullYearP);
        this.dummy2.setDate(4);
        this.dummy2.setMonth(0);
        fourthJanuaryWeekDay = (this.dummy2.getDay()+6)%7 ; 
        firstMondayOffset = 4 - fourthJanuaryWeekDay ; 

        weekNumber = ( (this.getDaysBeforeMonth(monthP,fullYearP)+dayP)-firstMondayOffset ) / 7  + 1 ; 
        weekNumber = Math.floor(weekNumber) ; 

        if ( weekNumber == 53 ) {
            this.dummy2.setFullYear(fullYearP);
            this.dummy2.setDate(dayP);
            this.dummy2.setMonth(11);
            weekDay = (this.dummy2.getDay()+6)%7 ; 

            if ( dayP == 31 && weekDay < 3 ) 
                return 1 ; 
            if ( dayP == 30 && weekDay < 2 ) 
                return 1 ; 
            if ( dayP == 29 && weekDay < 1 ) 
                return 1 ; 
        }

        return weekNumber ; 
    };
    
    this.setFocusMonth = function ( a ) {
        if ( a == -1 ) {            
            if ( this.focusMonth == 0 ) {
                this.focusYear-- ; 
                this.focusMonth = 11 ;
            }               
            else {              
                this.focusMonth-- ;
            }                       
        }
        else {
            if ( this.focusMonth == 11 ) {
                this.focusYear++ ;
                this.focusMonth = 0 ; 
            }               
            else {              
                this.focusMonth++ ; 
            }           
        }
        this.updateDayDiv();
    };
    
    this.setFocusYear = function ( a ) {
        if ( a == -1 ) {                        
            this.focusYear-- ; 

        }
        else {          
            this.focusYear++;
        }
        this.updateDayDiv();
    };
    
    this.createDayDiv = function ( datee ) {
        var daysDiv = document.createElement('div'); // Days Div 
        
        var innerHTML = "<table class='jsCalendarHeadTable'><tr>";
        innerHTML = innerHTML + "<td><div class='jsCalendarButtonMinus' onclick='g_calendars[\""+this.id+"\"].setFocusYear(-1);'>-</div></td><td class='jsCalendarYearNameTD'>"+datee.getFullYear()+"</td><td><div class='jsCalendarButtonPlus' onclick='g_calendars[\""+this.id+"\"].setFocusYear(1);'>+</div></td>" ;            
        innerHTML = innerHTML + '</tr>' ;                   
        
        innerHTML = innerHTML + "<tr>";
        innerHTML = innerHTML + "<td><div class='jsCalendarButtonMinus' onclick='g_calendars[\""+this.id+"\"].setFocusMonth(-1);'>-</div></td><td class='jsCalendarMonthNameTD'>"+this.months[datee.getMonth()]+"</td><td><div class='jsCalendarButtonPlus' onclick='g_calendars[\""+this.id+"\"].setFocusMonth(1);'>+</div></td>" ;           
        innerHTML = innerHTML + '</tr></table>' ;                   
        
        innerHTML = innerHTML + "<table class='jsCalendarDaysTable'><tr>";
        
        var startDay   = ( datee.getDay() + 6 ) % 7 ;
        var currentDay = datee.getDate() ; 
        
        while ( currentDay > 1 ) {
            currentDay-- ; 
            startDay = ( startDay + 6 ) % 7 ;           
        }                   
       
        innerHTML = innerHTML + '<td></td>';
        for ( var i = 0 ; i < 7 ; i++ ) {
            innerHTML = innerHTML + '<td class="jsCalendarDayName">' + this.days[i] + '</td>' ; 
            //startDay = ( startDay + 8 ) % 7 ; 
        }       
                
        innerHTML = innerHTML + '</tr><tr>' ;   
//        innerHTML = innerHTML + '</tr><tr>';   

        
//      tdCount = 0 ; 
//      for ( var i = 0 ; i < startDay ; i++ ) {        
//          innerHTML = innerHTML + "<td width='14%' id='"+this.id+"_td_"+(i+1)+"' onclick=\"g_calendars['"+this.id+"'].setFocusDay("+(i+1)+");\" class='jsCalendarFocusTD'>" + (i+1) + '</td>' ;                                   
//          tdCount++; 
//      }

        dayIndex = -startDay ; 
        weekCounter = 0 ; 
        weekDay = 0 ; 
        weekMonth = 0 ; 
        weekYear = 0 ; 

        totalDays = startDay + this.getDaysPerMonth(datee.getMonth(),datee.getFullYear()) ; 

        if ( totalDays > 35 ) {
            dayCount = 35 + 7 ; 
        }
        else {
            dayCount = 35 ; 
        }
 
        for ( var i = 0 ; i < dayCount ; i++ ) {

        
            if ( dayIndex < 0 ) {
                month = this.getPrevMonth(datee.getMonth());
                year  = this.getPrevMonthYear(datee.getMonth(),datee.getFullYear());              
                day   = this.getDaysPerMonth(month,year)+dayIndex+1;
            }
            else if ( dayIndex + 1 > this.getDaysPerMonth(datee.getMonth(), datee.getFullYear()) ) {
                month = this.getNextMonth(datee.getMonth());
                year  = this.getNextMonthYear(datee.getMonth(),datee.getFullYear());              
                day   = dayIndex - this.getDaysPerMonth(datee.getMonth(), datee.getFullYear()) + 1 ;          
            }
            else {
                month = datee.getMonth()    ; 
                year  = datee.getFullYear() ; 
                day   = dayIndex + 1 ; 
            }       
                        
            if ( day == this.selectedDay && month == this.selectedMonth && year == this.selectedYear ) {
                className = 'jsCalendarSelectedTD' ; 
            }
            else if ( day == this.now.getDate() && month == this.now.getMonth() && year == this.now.getFullYear() ) {
                className = 'jsCalendarTodayTD' ;           
            }
            else {          
                if ( month != datee.getMonth() ) {
                    className = 'jsCalendarOtherMonthTD' ; 
                }
                else {
                    className = 'jsCalendarTD' ;            
                }
            }

            if ( i % 7 == 0 ) {
                weekTDID = this.id + '_weekDay_' + weekCounter ; 
                weekNR = this.getWeekNumber(year,month,day) 
                innerHTML = innerHTML + '<script type="text/javascript">document.getElementById("'+weekTDID+'").innerHTML="'+weekNR+'";;</script>'
            }
           
            if ( i == 0 ) {
//                innerHTML = innerHTML + '<td>' + this.getWeekNumber(year,month,day) +'</td>';  
//                innerHTML = innerHTML + '<td>' + day + '</td>';  
                  innerHTML = innerHTML + '<td class="jsCalendarWeekTD" id='+ this.id + '_weekDay_' + weekCounter +'></td>';  
            }

            dayID = this.id + '_td_' + day + '_' + month + '_' + year ; 
            //setSelectedDayCode = "selectDay('"+day+"','"+month+"','"+year+"')";
            setSelectedDayCode = "selectDay("+day+","+month+","+year+")";
        
            innerHTML = innerHTML + "<td id='"+dayID+"' onclick=\"g_calendars['"+this.id+"']."+setSelectedDayCode+";\" class='"+className+"'>" + day + '</td>' ;                        

            if ( (i+1) % 7 == 0 ) {
                weekCounter++ ; 
                if ( weekCounter < 5 || ( weekCounter == 5 && dayCount > 35 )) {
//                    innerHTML = innerHTML + '</tr><tr><td>' + this.getWeekNumber(weekYear,weekMonth,weekDay) + '</td>' ; 
                    innerHTML = innerHTML + '</tr><tr><td class="jsCalendarWeekTD" id='+ this.id + '_weekDay_' + weekCounter +'></td>';  
                }
                else {
                    innerHTML = innerHTML + '</tr><tr><td></td>' ; 
                }
//                innerHTML = innerHTML + '</tr><tr>' ;                       
            }
            dayIndex++ ; 
            /*if ( i == 34 ) {
                if ( month == datee.getMonth() && year == datee.getYear() && day < this.getDaysPerMonth(datee.getMonth(), datee.getFullYear()) ) {
                    i = i - 7  ;
                }
//                dayIndex + 1 > this.getDaysPerMonth(datee.getMonth(), datee.getFullYear()) 
            }
            */
        }

        /*
        for ( var i = 0 ; i < this.getDaysPerMonth(date.getMonth(),this.focus.getFullYear()) ; i++ ) {
            if ( (i+1) ==date.getDate() ) {
                innerHTML = innerHTML + "<td width='14%' id='"+this.id+"_td_"+(i+1)+"' onclick=\"g_calendars['"+this.id+"'].setFocusDay("+(i+1)+");\" class='jsCalendarFocusTD'>" + (i+1) + '</td>' ;                       
            }
            else {
                innerHTML = innerHTML + "<td width='14%' id='"+this.id+"_td_"+(i+1)+"' onclick=\"g_calendars['"+this.id+"'].setFocusDay("+(i+1)+");\" class='jsCalendarTD'>" + (i+1) + '</td>' ;                        
            }
            if ( (i+1) % 7 == 0 ) {
                innerHTML = innerHTML + '</tr><tr>' ;                       
            }
        }
        */      
        
        innerHTML = innerHTML + '</tr></table>' ;           
        daysDiv.innerHTML = innerHTML ;
        return daysDiv ; 
    };

    this.closeCalendar = function ( ) {
        if (  this.mouseRegistered == true ) {
            g_mouseDevice.deregisterListener(this);
            this.mouseRegistered = false ; 
        }
        this.target.setAttribute('calendar_visible',0);
        g_calendars[this.id].active = false ; 
    };
    
}

function printNumber ( n ) {
    if ( n < 10 && n >=0 ) 
        return '0' + n ; 
    return n ;     
}    

// returns null if format string is invalid. Otherwise array with three elements is returned. 
function createDateMapping ( formatStr ) {
    dateMapping = new Array() ; 
    dateMapping[0] = '' ; 
    dateMapping[1] = '' ; 
    dateMapping[2] = '' ; 

    formatStr  = formatStr.replace(/ /g,'');
    valueIndex = 0 ; 

    for ( i = 0 ; i < formatStr.length && valueIndex < 3 ; i ++ ) {
        if ( i + 1 >= formatStr.length ) { // We're still inside the loop ! -> Invalid string ! 
            return null ; 
        }

        if ( formatStr.charAt(i) == '%' ) {
            switch ( formatStr.charAt(i+1) ) {
                case 'd' : 
                case 'D' :
                    dateMapping[valueIndex] = 'day' ; 
                    break ; 
                case 'm' : 
                case 'M' :
                    dateMapping[valueIndex] = 'month' ; 
                    break ; 
                case 'y' : 
                case 'Y' :
                    dateMapping[valueIndex] = 'year' ; 
                    break ; 
                default : // Invalid character after % in date format string  
                    return null ; 
            }
            valueIndex++ ; 
        }
    }
    return dateMapping ; 
}

// formatStr is like '%d.%m.%y' or ' %Y / %d / %m' 
function printDate ( formatStr, year , month, day ) {
    retStr = formatStr.replace(/ /g,'');    
    retStr = retStr.replace(/%[dD]/,day).replace(/%[mM]/,month).replace(/%[Yy]/,year) ;
    return retStr ; 
}

// str contains the date to parse (like '06-10-1980' or '1980/06/10')
// formatStr contains the format description (like '%m-%d-%y' oder '%Y/%d/%M)
// returns null if the str does not match the format. returns an Date object when parsing was successfull. 
function parseDate ( str, formatStr )  {
    dateMapping = createDateMapping(formatStr);
    if ( dateMapping == null ) { 
        return null ; 
    }

    dateValues = new Object() ; 
    dateValues['day']   = 0 ; 
    dateValues['month'] = 0 ; 
    dateValues['year']  = 0 ; 

    exprCode = formatStr.replace(/ /g,'');
    exprCode = exprCode.replace(/\//g,'\/');
    exprCode = exprCode.replace(/\./g,'\.');
    exprCode = exprCode.replace(/%[dD]/,'(\\d{1,2})').replace(/%[mM]/,'(\\d{1,2})').replace(/%[Yy]/,'(\\d{4})') ;
    str = str.replace(/ /g,'');
    expression = new RegExp(exprCode); 
    expression.exec(str);

    if ( ! ( RegExp.$1 && RegExp.$2 && RegExp.$3 ) ) { // Some value is missing...        
        return null ; 
    }

    dateValues[ dateMapping[0] ] = RegExp.$1 ; 
    dateValues[ dateMapping[1] ] = RegExp.$2 ; 
    dateValues[ dateMapping[2] ] = RegExp.$3 ; 

    if ( dateValues['day'] > 31 ) 
        return null ; 
    if ( dateValues['month'] > 11 ) 
        return null ; 

    var returnObj = new Date() ; 
    returnObj.setFullYear( dateValues['year'] ) ; 
    returnObj.setMonth( ( dateValues['month'] % 12 ) - 1 ) ; 
    returnObj.setDate( dateValues['day'] ) ; 

    return returnObj ; 
}

// formatStr is the system specific format description like '%d.%m.%y' or '  %Y / %m / %d '. Spaces are ignored. 
function showCalendar ( target, calendarID, formatStr ) {

    if ( target.getAttribute('calendar_visible') == 1 ) 
        return ; 

    if ( g_activeCalendar != null ) {
        g_activeCalendar.closeCalendar();
        if ($(g_activeCalendar.mainDivID) ) {
            e = $(g_activeCalendar.mainDivID) ; 
            e.parentNode.removeChild(e);
        }
        g_activeCalendar = null ; 
    }

    preSelectedDate = parseDate (target.value, formatStr) ; 
//    if ( preSelectedDate ) 
//        alert ( preSelectedDate.getDate() + '.' + (preSelectedDate.getMonth()+1) + '.' + preSelectedDate.getFullYear() ) ;  

    var calendar = new Calendar(calendarID,target,formatStr,preSelectedDate);

    target.setAttribute('calendar_visible',1);
    
    var newDiv = document.createElement('div'); // Main Calendar Div 
    newDiv.id = calendarID + '_parent' ; 
    newDiv.className = 'jsCalendar' ; 
    newDiv.style.position = 'absolute' ; 
    //newDiv.style.left = getLeft(target) + target.offsetWidth ; 
    //newDiv.style.top  = getTop(target) ; 

    document.getElementsByTagName('body')[0].appendChild(newDiv);                   
//    target.parentNode.appendChild(newDiv);                   
    newDiv.style.left = getLeft(target) + getScrollY() + target.offsetWidth + 'px' ; 
    newDiv.style.top  = getTop(target) + getScrollX() + 'px' ; 
    
    var close = document.createElement('div');
    close.className = 'jsCalendarHeadDiv'
    close.innerHTML = "<a id='closeButton' class='jsCalendarCloseButton' onclick='g_calendars[\""+calendarID+"\"].closeCalendar(); e = document.getElementById(\""+newDiv.id+"\"); e.parentNode.removeChild(e);'>x</a>"; 
    calendar.mainDiv = newDiv ;     
    calendar.mainDivID = newDiv.id ; 

    if ( preSelectedDate ) {
        calendar.dayDiv  = calendar.createDayDiv(preSelectedDate) ; 
    }
    else {
        calendar.dayDiv  = calendar.createDayDiv(calendar.now) ; 
    }

    newDiv.appendChild(close);      
    newDiv.appendChild(calendar.dayDiv);        

    g_activeCalendar = calendar ; 
    calendar.startUpdating();
}
   
// KALENDER --------------------------------------------------------------------- 



