// javascript function for easydb
function unregister_marker_window(table_id) {
    delete(top.marker_register[table_id]);
    if (top.js_links_update_window && 
		typeof top.js_links_update_window.js_links_update == 'function') {
        top.js_links_update_window.js_links_update();
    }
}

function register_marker_window(table_id, win) {
	top.marker_register[table_id] = win;
    if (top.js_links_update_window && 
		typeof top.js_links_update_window.js_links_update == 'function') {
		top.js_links_update_window.js_links_update();
	}
}

function marker_window_get(table_id) {
   return top.marker_register[table_id];
}

if (!top.marker_register) {
   top.marker_register = new Array();
}

top.register_marker_window = register_marker_window;
top.marker_window_get = marker_window_get;
top.unregister_marker_window = unregister_marker_window;

function get_marker_window(table_id) {
   if (!top.marker_register) {
      alert('marker_register not found. checkboxResultFuncs set in driver head for search?');
   }
   var mw = top.marker_register[table_id];

   var type='';
   if (mw) {
     type = typeof mw.marker_click_action;
   }

   if (type == 'function') {
      return mw;
   } else {
      return '';
   }
}

function get_top_doc() {
	return top.document;
	
	// XXX: the following code causes problems when easydb is launched from
	//		within another window (e.g. using <a target="_blank">) because
	//		window.opener.top.document is inaccessible in such case
	top_doc = top.document;
	if (!top_doc.link_action_type && window.opener) {
		top_doc = window.opener.top.document;
	}
	return top_doc;
}


function submitIdsLink(ids, eadb_frame) {
	// submits the form embedded by result.php for long id chains
	// used by ids_link in result.php

	var w = window;
	if (eadb_frame) {
		w = findWindow(top, eadb_frame);
	}
	if (!w) {
		alert("submitIdsLink: window/frame '"+eadb_frame+"' not found.");
	}
	var fo = w.$("ids_link");
	fo.elements['loadids'].value = ids.join(",");
	fo.submit();
}


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, prefix) {
    
   var f = " \
var myspan = $('" + span_id +"'); \
if (myspan) { \
  var myfunc = function(prefix) { "+ calculator_code+" }; \
  var myvar = myfunc('" + prefix +"'); \
  var dont_update = false; \
  if (myvar === false) { \
     dont_update = true; \
  }; \
  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 +"' && !dont_update) { \
      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 ;
}

/**
* Return the absolute vertical scroll offset for a certain Element.
* Also calculates the parent's offset caused by e.g. scrolling divs.
*/
function getAbsScrollY (el) {
    var scrollY = 0;//getScrollY();
    while (el != undefined) {
        if (el.scrollTop)
            scrollY += el.scrollTop;
        el = el.parentNode;
    }
    return scrollY;
}

/**
* Return the absolute horizontal scroll offset for a certain Element.
* Also calculates the parent's offset caused by e.g. scrolling divs.
*/
function getAbsScrollX (el) {
    var scrollX = 0;//getScrollX();
    while (el != undefined) {
        if (el.scrollLeft)
            scrollX += el.scrollLeft;
        el = el.parentNode;
    }
    return scrollX;
}

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 0;
   }
   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) {
    try {
        eval(t.responseText);
    } catch (e) { 
        t = e + "\ntried to eval:\n" + t.responseText;
        alert(t);
        //(console!=undefined) ? console.error(t) : alert(t);
    }
}

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');
   if (els.length == 0) {
      alert("setField: name:"+name+" value:"+value); 
   } else {
      els[0].value=value;
   }
}

function submitConcatForm(concatForm, arr) {
	var sfo = $('formForLongRequests');
	if (!sfo) {
		alert('formForLongRequests not found, make sure to use close_form in your edit mask');
		return;
	}

	// remove all children
	sfo.innerHTML = "";

	sfo.method = arr.method;
	sfo.action = arr.action;
	sfo.target = arr.target;

	$H(arr.elements).each(function(pair) {
		sfo.appendChild(new Element('INPUT',{type:'hidden', 
											 name: pair.key,
											 value: pair.value}));
	});

	if (concatForm && concatForm.elements) { 
		var all = new Array();
		for (var i=0; i<concatForm.elements.length; i++) {
			var name = concatForm.elements[i].getAttribute("field_name");
			if (name) {
				sfo.appendChild(new Element('INPUT',{type:'hidden', 
													 name:name+'[]', value:concatForm.elements[i].value}));
			}
		}
	}
	sfo.submit();
}

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 = [];

function addElementToSurveillance(id, attributeName, column) {

	var gcell = null;
	var gcells_tmp = find_elements_by_id(id,["SELECT","INPUT"],attributeName);
	if (!(gcells_tmp.length > 0)) {
		alert("gcell_value_for_CASE: "+attributeName+": "+id+", no gcells found"); 
		return null;
	} else {
		gcell = gcells_tmp[0];        
		for (var i=0; i<gcells_tmp.length; i++) {
			if (!gcells_tmp[i].underSurveillance) {
				gcell = gcells_tmp[i];        
			}
		}
	}
	var functionToGetValue;

    if (column) {
		functionToGetValue = function(el) { 
			return el.options[el.selectedIndex].getAttribute("db__"+this)
		}.bind(column);
    } else {
		if (typeof gcell.type != "undefined" && 
			gcell.type == "checkbox") {

			functionToGetValue = function(el) { 
				if (el.checked) {
					v = "true"
				} else {
					v = "false"
				}
				return v; 
			};
		} else {
			functionToGetValue = function(el) { 
				return el.value 
			}
		}
	}
	
	if (!gcell.underSurveillance) {
		// the surveillanceNumber is a number which is the 
		// same for the same elemnent in the DOM tree

		gcell.surveillanceNumber = elementsUnderSurveillance.length;
		gcell.underSurveillance = true;
		if (!gcell.oldonchange) {
			gcell.oldonchange =  gcell.onchange;
		}
		gcell.onchange = function() {
			checkSurveillanceStatus(gcell.surveillanceNumber);
			if (gcell.oldonchange) {
				gcell.oldonchange();
			}
		}    
	}

	var so = { 
		number: gcell.surveillanceNumber,
		element: gcell,
		functionToGetValue: functionToGetValue,
		choices: []
	};

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

     checkSurveillanceStatus(so.number);
}

function checkSurveillanceStatus(surveillanceNumber) {
	for (var j=0; j<elementsUnderSurveillance.length;j++) {
		var so = elementsUnderSurveillance[j];

		if (so.number === surveillanceNumber) {
			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;
				}
				
				// check if the div has been made invisible by removeInvisibleDivs and an autosave
				if (so.choices[i].enable_div._inner_html) {
					so.choices[i].enable_div.innerHTML = so.choices[i].enable_div._inner_html;
					so.choices[i].enable_div._inner_html = false;
				}

				var scripts = so.choices[i].value.extractScripts()
				var choice = so.functionToGetValue(so.element)
				var show = null

				if (scripts.length) {
					try {
						show = eval(scripts[0])
						if (typeof show == "undefined") {
							alert("In CASE GRIDs the JSCRIPT must eval to true or false. \nYou find the value of the choice stored in 'choice'")
							break
						}
					} catch (e) {
						alert(e)
						break
					}
				} else {
					if (choice == so.choices[i].value) {
						show = true
					} else {
						show = false
					}
					
				}
				
				if (show) {
					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';
			}
		}
	}
};

function find_elements(func, tagNames, attributeName, start) {
   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++) {  
          var v = allInputs[i].getAttribute(attributeName);
		  if (v === null) {
			  continue;
		  }
          if (func(v, allInputs[i])) {
             elements.push(allInputs[i]);
         }            
      }
   }
   return elements;
}

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

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, extra_javascript_code) {
   if (!extra_javascript_code) {
      extra_javascript_code = "Y";
   }

   var fo = $(id_of_form);
   fo.target = 'edit_useme_iframe';
   submit_current_form(fo, 'autosave', extra_javascript_code);
   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.resetDefaultText) fo.resetDefaultText();
        if (fo.onsubmit) {
            if (fo.onsubmit() == false) {
                return false;
            }
        }
        fo.submit();
        return false;
    }
}


function elementSetDefaultText(el, text, color) {
    // this sets a default text for an element
    el.defaultText = text;
    el.origColor = el.style.color;
    el.defaultTextColor = color;
    el.isDefaultText = false;
    el.setText = function(text) { this.value=text; this.isDefaultText=false; this.onblur() };
    el.checkTextColor = function() { if (this.isDefaultText) { this.style.color = this.defaultTextColor; } else { this.style.color=this.origColor } };

    if (el.onfocus && !el.onfocus_sdt) { 
         el.onfocus_sdt = el.onfocus; 
    }
    el.onfocus = function () { 
         if (this.isDefaultText) { 
              this.value=""; this.isDefaultText=false; 
         } 
         this.checkTextColor(); 
         if (el.onfocus_sdt) {
              el.onfocus_sdt()
         };
    }  
    el.onblur = function () {if (this.value.length==0) { this.value=this.defaultText; this.isDefaultText=true; } this.checkTextColor(); }
    el.onblur();

    if (el.form && !el.form.resetDefaultText) {
        el.form.resetDefaultText = function () {
          for (var i=0; i<this.elements.length; i++) {
                if (this.elements[i].isDefaultText) {
                    this.elements[i].value="";
                }
          } 
        }
    } 
}


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.replace(',','.') * 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") {
				if (gcells[i].getAttribute("precision")) {
					values.push( gcells[i].innerHTML.replace(',','.') * Math.pow(10, gcells[i].getAttribute("precision")) );
				} else {
					values.push(Math.round(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;
   }

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

  for (var i=0; i<removeDivs.length; i++) {  
      var el = removeDivs[i];
      // if (el) el.parentNode.removeChild(el);
      // instead of removing them from the dom tree, we just empty them end
      // store the html inside the div element, this is needed for the 
      // case grid to work properly after an autosave
      if (!el._inner_html) {
          el._inner_html = el.innerHTML;
          el.innerHTML = '';       
      }
  }
}

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);
	if (googlemaps.domEl) {
		googlemaps.createMap(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) {
         setOldValue(name, document.getElementsByName(name)[0].value);
     }
   }
}

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;
         if (el.isDefaultText) {
            changed = "" != oldValues[name];
         } else {
            changed = value != oldValues[name];
         }
         checkEl(el, changed);
     }
}

var checkColor='#c0c0c0';
var checkErrColor='#ff0000';
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) {
         // alert('check:'+check+':'+el.name+':'+el.type+':'+el.value+':'+oldValues[name]);
     if (check) {
         if (!el.alreadyChanged) {
             valuesChanged++;
         }
         el.alreadyChanged=1;
         if (checkColor.charAt(0) == '#') {
            el.style.backgroundColor=checkColor;
         } else {
            if (!el.oldClassName && el.className) {
                el.oldClassName=el.className;
            }
            if (String(" " + el.className + " ").indexOf(checkColor)<0) {
                el.className=el.className + " " + checkColor;
            }
         }
     } else { 
         if (el.alreadyChanged) {
             valuesChanged--;
         }
         el.alreadyChanged=0;
         el.style.backgroundColor=''; 
         if (el.oldClassName) {
            el.className = el.oldClassName;
         }
     }
}

function markValue(name) {
     var el=document.getElementsByName(name)[0]; 
     el.alreadyChanged=1;
     valuesChanged++;
     if (checkErrColor.charAt(0) == '#')
        el.style.backgroundColor=checkErrColor;
     else
        el.className=checkErrColor;
}

function extendHref(el) {
   if (!el.origHref) {
     el.origHref=el.href;
   } else {
     el.href=el.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) {
         if (v.selectedIndex >= 0) {
            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;
      } else {
          window_width = 0;
          window_height = 0;
      }
   }
 }
}

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) {
   var div = document.getElementById(id);
   if (clear_form) {
      clearAllFormElements(div);
   }
   div.style.display='none';
   eval('top.divstatus_'+id+'=0;');
}

function showDivDisplay(id) {
   var 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) {

    var div = $(id);
	
	if (!div) {
		alert('div ' + id + ' not found.');
		return;
	}

	if (div.getStyle("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) {
   var div = document.getElementById(id);
   if (clear_form) {
     clearAllFormElements(div);
   }
   div.style.visibility='hidden';
}

function showDiv(id) {
   var 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 ; 
}

function positionHoverDiv ( ) {
    if (g_currentHover == '')
        return;
    
    var x   = g_mouseDevice.getMousePosX();
    var y   = g_mouseDevice.getMousePosY();
    var div = document.getElementById(g_currentHover);

    if (g_currentModeX == 'right') {
        if ((x + 15 + div.offsetWidth > document.viewport.getWidth() + getScrollX() - 19) && ( x - 10 - div.offsetWidth >= getScrollX())) {
            g_currentModeX = 'left';
            div.style.left = x - 10 - div.offsetWidth + 'px';
        } else {
            div.style.left = x + 15 + 'px';
        }
    } else { // g_currentMode == 'left'
        if ((x - 10 - div.offsetWidth < document.viewport.getWidth()) && (x + 15 + div.offsetWidth < document.viewport.getWidth() + getScrollX())) {
            g_currentModeX = 'right';
            div.style.left = x + 15 + 'px';
        } else {
            div.style.left = x - 10 - div.offsetWidth + 'px';
        }
    }

    if (g_currentModeY == 'bottom') {
        if ((y + 15 + div.offsetHeight > document.viewport.getHeight() + getScrollY()) && (y -  5 - div.offsetHeight >= getScrollY())) {
            g_currentModeY = 'top';
            div.style.top = y -  5 - div.offsetHeight + 'px';
        } else {
            div.style.top = y + 15 + 'px';
        }
    } else { // g_currentMode == 'top'
        if ((y -  5 - div.offsetHeight < getScrollY()) && (y + 15 + div.offsetHeight < document.viewport.getHeight() + getScrollY())) {
            g_currentModeY = 'bottom';
            div.style.top = y + 15 + 'px';
        } else {
            div.style.top = y -  5 - div.offsetHeight + 'px';
        }
    }
}

function showHoverDiv ( id, linkid, delay ) {
    if (g_hoverDivTimeout) {
        clearTimeout(g_hoverDivTimeout);
        if (document.getElementById(g_currentHover))
            hideHoverDiv(id, linkid);
    }
    g_hoverDivTimeout = setTimeout(function() {
        g_currentHover = id; 
        g_currentModeX = 'right'; 
        g_currentModeY = 'bottom';
        // to avoid 'jumping', we first make it a block without showing it yet
        var hd = document.getElementById(id);
        hd.style.display = 'block';
        hd.style.visibility = 'hidden';  
        // now we place it and show it in its correct position
        positionHoverDiv();
        hd.style.visibility = 'visible';  
    }, delay);
}

function hideHoverDiv ( id, linkid ) {
    clearTimeout(g_hoverDivTimeout);
    document.getElementById(id).style.display = 'none';
    g_currentHover = '';
}

HoverMouseHandler = Class.create ({

    initialize : function() {
    },

    onMouseOut : function ( e ) {
    },

    onMouseWheel : function ( e ) {
    },

    onMouseClick : function ( e ) {
    },

    onMouseDoubleClick : function ( e ) {
    },
    
    onMouseUp : function ( e ) {
    },

    onMouseDown : function ( e ) {
    },

    onMouseMove : function ( e ) {
        if ( g_currentHover == '' ) 
          return ; 
        positionHoverDiv();
    }
});


// 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);
        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);
        this.target.style.color = this.target.origColor;
        this.target.isDefaultText = false;
        checkEl(this.target, true);

        // 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 html = '<table class="jsCalendarHeadTable"><tr>';
        html += '<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>'; 
        html += '</tr><tr>';
        html += '<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>';
        html += '</tr></table>';
        html += '<table class="jsCalendarDaysTable"><tr>';
        
        var startDay   = (datee.getDay() + 6) % 7;
        var currentDay = datee.getDate() ; 
        while (currentDay > 1) {
            currentDay--;
            startDay = (startDay + 6) % 7 ;           
        }                   
        
        dayIndex    = -startDay ; 
        weekCounter = 0 ; 
        weekDay     = 0 ; 
        weekMonth   = 0 ; 
        weekYear    = 0 ; 
        totalDays   = startDay + this.getDaysPerMonth(datee.getMonth(), datee.getFullYear());

        html += '<td></td>';
        for (var i = 0; i < 7; i++) {
            html += '<td class="jsCalendarDayName">' + this.days[i] + '</td>';
        }       
        html += '</tr><tr>' ;   

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

            // first day in calendar?
            if (i == 0) {
                html += '<td class="jsCalendarWeekTD">' + this.getWeekNumber(year, month, day) + '</td>';  
            }

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

            // if tomorrow is Monday
            if ((i + 1) % 7 == 0) {
                weekCounter++;
                if (weekCounter < 5 || (weekCounter == 5 && dayCount > 35)) {
                    html += '</tr><tr><td class="jsCalendarWeekTD" id='+ this.id + '_weekDay_' + weekCounter +'>' + (this.getWeekNumber(year,month,day) + 1) + '</td>';
                } else {
                    html += '</tr><tr><td></td>';
                }
            }
            dayIndex++;
        }

        html += '</tr></table>';
        
        daysDiv.innerHTML = html;
        
        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;
    }
    
    // different date format than dd.mm.yyyy? cut off non-date part
    if (target.value.length > 10) {
        target.value = target.value.substr(0, 10);
    }
    
    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';

    document.getElementsByTagName('body')[0].appendChild(newDiv);                   
//    target.parentNode.appendChild(newDiv);                   
    
    // calculate positions of calendar (and check if newDiv would open outside 
    // visible window area and correct position if it does)
    var calX = getLeft(target) + getScrollX() - getAbsScrollX(target);
    if (calX + newDiv.offsetWidth > document.viewport.getWidth()) {
        calX -= (newDiv.offsetWidth > target.offsetWidth) ? newDiv.offsetWidth-target.offsetWidth : target.offsetWidth - newDiv.offsetWidth;
    }
    var calY = getTop(target) + getScrollY() - getAbsScrollY(target) + target.offsetHeight;
    if (calY + newDiv.offsetHeight > document.viewport.getHeight()) {
        calY -= newDiv.offsetHeight + target.offsetHeight;
    }
    
    newDiv.style.left = calX + 'px';
    newDiv.style.top  = calY + '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 --------------------------------------------------------------------- 




// ala martin pulldown

function pulldown_start(name) {
    select_element = document.getElementsByName(name)[0];
    select_element.style.display = 'none';
	if (!select_element.selectedIndex) {
		select_element.selectedIndex = 0;
	}
	var prevOption = null;
    for (i=0; i<select_element.options.length; i++) {
		var o = select_element.options[i];
        o.idx = i;
		o.level = Math.floor(o.getAttribute('level'));
		if (!o.level) {
			o.level = 0;
		}
		if (prevOption === null) {
			prevOption = o;
			continue;
		}
		if (prevOption.level < o.level) {
			prevOption.allowDive = true;
		} else {
			prevOption.allowDive = false;
		}
		prevOption = o;
    }

    // set temporary index to the father element of the current index
    update_title_div(select_element);
}

function get_father_idx(select_element, idx) {
    path = get_current_path(select_element, idx);

	if (idx === 0 || path.length === 0) {
		return null;
	}
    if (path.length <= 1) {
        return 0;
    }
	return path[path.length-2].idx;
}

function update_content_div(select_element) {
    // shows the elements below the tmpIndex

    children = get_children(select_element);
    html = "";
    html += "<a href=\"javascript:close_content_div('"+select_element.name+"')\" class=\"close\" title=\"Close ...\"><span>x</span></a>";

    father_idx = get_father_idx(select_element, select_element.tmpIndex);
    if (father_idx !== null) {
        html += "<a href=\"javascript:set_idx('"+select_element.name+"',"+father_idx+")\" class=\"back\" title=\"Back ...\"><span>&lt;-</span></a>";
    }
    html += "<div style=\"clear:both\"></div><ul>";

    path = get_current_path(select_element, select_element.selectedIndex);

    for (i=0; i<children.length; i++) {
        o = children[i];
		
        // check if the elemnt is the one selected
        selected = "";
        if (o.idx==select_element.selectedIndex) {
             selected = "selected";
        } else {
             // check if the element is in the seleced path
            for (jj=0; jj<path.length-1; jj++) {
                if (path[jj].idx==o.idx) {
                    selected = "pathselected";
                    break;
                }
            }
        }

		html += "<li>";
		if (o.allowDive) {
			html += "<a class=\"dive "+selected+"\" href=\"javascript:set_idx('"+select_element.name+"',"+o.idx+")\" title=\"Eine Ebene tiefer ...\">&gt;</a>";
		}
		if (o.disabled) {
			html += "<span class=\"disabled "+selected+"\">"+o.innerHTML+"</span>";
		} else {
			html += "<a class=\"select "+selected+"\" href=\"javascript:select_idx('"+select_element.name+"',"+o.idx+")\">"+o.innerHTML+"</a>";
		}
		html += '</li>';
    }   
	html += '</ul>';
    contentdiv = document.getElementById("content_"+select_element.name);
    contentdiv.innerHTML = html;
}

function select_idx(name, idx) {
    select_element = document.getElementsByName(name)[0];
    select_element.selectedIndex = idx;
	if (select_element.onchange) {
		select_element.onchange();
	}
    close_content_div(name);
}

function set_idx(name, idx) {
    select_element = document.getElementsByName(name)[0];
    select_element.tmpIndex = idx;

    update_content_div(select_element);
    update_title_div(select_element);
}

function update_title_div(select_element) {

    contentdiv = document.getElementById("content_"+select_element.name);
    titlediv = document.getElementById("title_"+select_element.name);

    if (contentdiv.open) {
        idx = select_element.tmpIndex;
    } else {    
        idx = select_element.selectedIndex;
    }
    path = get_current_path(select_element, idx);
   
    html_title  = "";
    if (path===null) {
        html_title = "no selection possible.";
	} else {
		for (i=0; i<path.length; i++) {
			if (html_title) {
                html_title += ", "
			}
			html_title += path[i].innerHTML;
		} 
	}
    if (contentdiv.open) {
        titlediv.innerHTML = html_title;
    } else {
        titlediv.innerHTML = "<a href=\"javascript:open_content_div('"+select_element.name+"')\">"+html_title+"</a>";
    }

}

function open_content_div(name) {
    select_element = document.getElementsByName(name)[0];
    contentdiv = document.getElementById("content_"+select_element.name);
    contentdiv.open = true;
    contentdiv.style.display="block";
	select_element.tmpIndex = get_father_idx(select_element, select_element.selectedIndex);
	update_content_div(select_element);
    update_title_div(select_element);
}

function close_content_div(name) {
    select_element = document.getElementsByName(name)[0];
    contentdiv = document.getElementById("content_"+select_element.name);
    contentdiv.open = false;
    contentdiv.style.display="none";
    update_title_div(select_element);
}

function get_current_path(select_element, idx) {
    var path = [];
	var currentOption = select_element.options[idx];
	if (!currentOption) {
		return path;
	}
    for (i=0; i<=idx; i++) {
        o = select_element.options[i];
		if (o.level <= currentOption.level) {
			path[o.level] = o;
		}
    }
    return path;
}

function get_children(select_element) {
    // get children, starting from the current index
    current_level = 0;

	var findLevel = 0;
	var startIdx = -1;
    if (select_element.tmpIndex) {
		startIdx = select_element.tmpIndex;
		findLevel = select_element.options[ startIdx ].level + 1;
    }
    children = [];
    for (i=startIdx+1; i<select_element.options.length; i++) {
        o = select_element.options[i];
		if (o.level == findLevel) {
            children.push(o);
			continue;
		}
		if (o.level >= findLevel) {
			continue;
		}
		break;
	}
    return children;
}

// Takes two objects and sorts them depending on their 'value' property
function editlinkSortCallback (a, b) {
    if (a.value > b.value)
        return 1;
    else if (a.value < b.value)
        return -1;
    else
        return 0;
}

// Sorts the editlinks with the given id according to the contents of 
// the div with the name set by sortDivName (each editlink needs to define
// such a div within its body if it wants to be sortable)
function editlinksSort (eid, sortDivName, reverse) { 
    
    var elkDiv = $('elk_' + eid);
    var slist = [];
    
    // loop over elk divs children and create objects
    for (var i=0; i<elkDiv.childNodes.length; i++) {
        var child = elkDiv.childNodes[i];
        var cid = child.getAttribute('id');
        // if the child is a child div for this editlink
        if (cid && cid.substr(0, 5 + String(eid).length) == 'elk_' + eid + '_') {
            // try to find the content to be sorted
            var sdiv = find_elements_by_id(sortDivName, ['div'], 'name', child);
            if (sdiv && sdiv.length>0) {
                // add object with value/div to sort array
                slist.push({value:sdiv[0].innerHTML.toLowerCase(), div:child});
            }
        }
    }
    
    // now sort the objects using our sorting callback
    slist = slist.sort(editlinkSortCallback);
    if (reverse) slist.reverse();
    
    // finally we just move the editlinks according to our sort array
    for (var i=0; i<slist.length; i++) {
        // clone the current element
        var copy = slist[i].div.cloneNode(true);
        // then remove original
        elkDiv.removeChild(slist[i].div);
        // and append clone to the end of the childNodes
        elkDiv.appendChild(copy);
    }

}

// walk through the childnodes of the given element and mark all inputs with 
// a small info-div
gDebugMarkInputsVisible = false;
function debug_mark_inputs (el, recursive) {
    // show markers
    for (var i=0; i<el.childNodes.length; i++) {
        var child   = el.childNodes[i];
        var nn      = child.nodeName;
        if (gDebugMarkInputsVisible) {
            // hide marker? 
            if (child.className == 'debug__inputMarker__') {
                child.parentNode.removeChild(child);
            }
        } else {
            // show marker? if it is any type of input element, add info div
            if (nn == 'INPUT' || nn == 'TEXTAREA' || nn == 'SELECT') {
                var type = child.getAttribute('type');
                if (type && type.toLowerCase() == 'hidden') {
					if (!child.name.match(/TL_/)) {
						continue;
					}
				}
                var div = document.createElement('div');
                div.style.border = '1px dotted rgb(153, 153, 153)';
                div.style.background = 'rgb(251, 187, 119)';
                div.className = 'debug__inputMarker__';
                child.parentNode.appendChild(div);
                div.innerHTML = child.getAttribute('name');
            }
        }
        // if element has childnodes, call self recursively and handle children
        if (child.hasChildNodes()) {
            debug_mark_inputs(child, true);
        }
    }
    if (!recursive) 
        gDebugMarkInputsVisible = !gDebugMarkInputsVisible;
}

function firebug(o) {
   if (Prototype.Browser.Gecko && 
       (typeof console != "undefined") && 
       (typeof console.debug == "function")) {
        console.debug(o);
   }
}

gFileBrowseHuri = null;
gFileBrowseStart = null;

function fileBrowse(parms) {
	parms.filebrowser = 1;
	parms.start = gFileBrowseStart;
	if (!parms.command) {
		new Ajax.Request(gFileBrowseHuri, {
			parameters: parms,
			onSuccess:handlerFunc,
			onFailure:errFunc,
			method: "get" });
	} else {

		var d = gFileBrowseHuri;
		$H(parms).each(function(a) { d = d + "&" + encodeURIComponent(a[0]) + "=" + encodeURIComponent(a[1])});

		document.location.href = d;
	}
}

function fileBrowserAddFile(opts) {
	var d = new Element("DIV");

	if (opts.buttons) {
		for (i=0; i < opts.buttons.length; i++) {
			var buttonInfo = opts.buttons[i];
			var b = new Element("BUTTON", {
                "class": buttonInfo["class"],
				"disabled": buttonInfo["disabled"]?true:false,
                "title": buttonInfo["title"]
            }).update(buttonInfo.name);
			
			buttonInfo.parms = {};
			$H(buttonInfo).each(function(a) {
				switch(a[0]) {
				case "class":
				case "title":
				case "name":
				case "link":
				case "parms":
					break;
				default:
					buttonInfo.parms[a[0]] = a[1];
					break;
				}
			});

			buttonInfo.parms["path"] = buttonInfo.link;

			Event.observe(b,"click",function(e) {
				fileBrowse(this.parms); 
				e.stop();
			}.bindAsEventListener(opts.buttons[i]));

			d.insert(b);

		}
	}
	
	var s = new Element("SPAN").update(opts.file);
	if (opts.link) {
        s.addClassName("directory");
		var a = s.wrap("A",{href:"#"});
		Event.observe(a,"click",function() {
			fileBrowse({path:opts.link});
		});
		d.insert(a);
	} else {
        s.addClassName("file");
		d.insert(s);
	}
	
    $("filebrowser").appendChild(d);
}

function fileBrowserEmpty() {
	$("filebrowser").update("");
	$("filebrowserPath").update("");
}

function fileBrowserPath(dir, back) {
	var b = new Element("BUTTON", {'class':'back'}).update("..");
	Event.observe(b,"click",function(e) { fileBrowse({path:back}); e.stop(); });

	$("filebrowserPath").update("");
	$("filebrowserPath").appendChild(new Element("SPAN").update(dir));
	$("filebrowserPath").appendChild(b);

}

function fileBrowserInit(huri, start) {
	gFileBrowseHuri = huri;
	gFileBrowseStart = start;

	document.write("<div id=filebrowserPath></div><div id=filebrowser></div>");
	fileBrowse({});
}


/* this disbles the input field, popuplink and adds a class */
function editDisable(eadb_column_ids, addClassName) {
	/* first find the INPUTs, TEXTAREAs, DIRECTLINKS */

	for(var i=0; i<eadb_column_ids.length; i++) {
		eadb_column_id = eadb_column_ids[i];

		find_elements(function(a, el) {
			if (a.indexOf("MI_FIELD_"+eadb_column_id) > -1) {
				if (addClassName) {
					el.addClassName(addClassName);
				}
				el.disabled = true;
			}
		}, ["INPUT","SELECT","TEXTAREA"], "name");
		

		find_elements(function(a, el) {
			if (a == eadb_column_id) {
				if (addClassName) {
					el.addClassName(addClassName);
				}
				el.disabled = true;
			} 
		}, ["INPUT"], "disablecontext");
		
		find_elements(function(a, el) {
			if (a.indexOf("MI_FIELD_"+eadb_column_id) > -1 || a == eadb_column_id) {
				if (addClassName) {
					el.addClassName(addClassName);
				}
				el.setAttribute("onclick", "return false;");
				el.setAttribute("href", "javascript://");
				el.title = "";
			} 
		}, ["A"], "disablecontext");
	}
}

var gFramesets = {};
function initFramesets(a) {
	gFramesets = a;
}

function setFrameset(mode) {
	if (!gFramesets[mode]) {
		alert("Mode "+mode+" not found. Define it by calling initFramesets({..}).");
		return;
	}
	var fs = parent.document.getElementsByTagName('FRAMESET')[0];
	fs.cols = gFramesets[mode];
}


function IMAGEUPLOAD_set_field(name, value, showValue) {
	// sets the fields for name to value, used by imageupload.php
	var el = document.getElementsByName(name);
	
	var show = parent.document.getElementsByName(name+'_SHOW');
	if (show.length) {
		// this is a singelink field
		setElement(name,value,showValue);
	} else {
		if (el.length) {
			el[0].value = value;
			if (document.getElementsByName(name+'_iptc')[0]) {
				document.getElementsByName(name+'_iptc')[0].value = value;
			}
			checkValue(name); 
		}
	}
}

function IMAGEUPLOAD_scan_iptc_selector() {
	// looks in the parent frame for iptc_selector information
	// and concats them to a comma separated list of values
  // searches in parent
	var ins = parent.document.getElementsByTagName("INPUT");
 
	var b = [];
	for (e in ins) {
		if (ins[e] && ins[e].name && ins[e].name.match(/^iptc__/)) {
			if (ins[e].checked) {
				b.push(ins[e].name.substr(6));
			}
		}
	}
	return b.join(",");
}

// FROM: http://www.movable-type.co.uk/scripts/latlong-convert-coords.html
// extend String object with method for parsing degrees or lat/long values to numeric degrees
//
// this is very flexible on formats, allowing signed decimal degrees, or deg-min-sec suffixed by 
// compass direction (NSEW). A variety of separators are accepted (eg 3º 37' 09"W) or fixed-width 
// format without separators (eg 0033709W). Seconds and minutes may be omitted. (Minimal validation 
// is done).

String.prototype.parseDeg = function() {
  if (!isNaN(this)) return Number(this);                 // signed decimal degrees without NSEW

  var degLL = this.replace(/^-/,'').replace(/[NSEW]/i,'');  // strip off any sign or compass dir'n
  var dms = degLL.split(/[^0-9.]+/);                     // split out separate d/m/s
  for (var i in dms) if (dms[i]=='') dms.splice(i,1);    // remove empty elements (see note below)
  switch (dms.length) {                                  // convert to decimal degrees...
    case 3:                                              // interpret 3-part result as d/m/s
      var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break;
    case 2:                                              // interpret 2-part result as d/m
      var deg = dms[0]/1 + dms[1]/60; break;
    case 1:                                              // decimal or non-separated dddmmss
      if (/[NS]/i.test(this)) degLL = '0' + degLL;       // - normalise N/S to 3-digit degrees
      var deg = dms[0].slice(0,3)/1 + dms[0].slice(3,5)/60 + dms[0].slice(5)/3600; break;
    default: return NaN;
  }
  if (/^-/.test(this) || /[WS]/i.test(this)) deg = -deg; // take '-', west and south as -ve
  return deg;
}
// note: whitespace at start/end will split() into empty elements (except in IE)


var googlemaps = {
    points: [],
    controls: [],
	markers: [],

	init: function(domID, options) {
		// if expand is set, we auto expand the div to maximum width and height
		googlemaps.domEl = $(domID);
		googlemaps.options = options;

		if (options.adaptHeight) {
			googlemaps.domEl.checkResize = function() {
				var dms = document.viewport.getDimensions();
				var maxHeight = dms.height - ( document.body.clientHeight - this.clientHeight );
				this.style.height = maxHeight+'px';
			}
		} else {
			googlemaps.domEl.checkResize = function() {};
		}

		Event.observe(window,'resize', function() {
			googlemaps.domEl.checkResize();
		});

		Event.observe(window,'load', function() {
			googlemaps.domEl.checkResize();
			if (googlemaps.options.tabSystemId > 0) {
				googlemaps.createMap(currentTabs[googlemaps.options.tabSystemId]);
			} else {
				googlemaps.createMap();
			}
		});
	},

	createMap: function(tabColNo) {
		/* if we are inside a tab system, we only create the
           map if the tabColNo is the current column */
		if (googlemaps.options.tabSystemId > 0) {
			if (tabColNo !== googlemaps.options.tabColNo) {
				return;
			}
		}

		googlemaps.map = new GMap2(googlemaps.domEl);
		googlemaps.map.setCenter(new GLatLng(0,0), 0);
		googlemaps.latLngBounds = new GLatLngBounds();
		
		// Set the maptype
		var map_types = {normal:G_NORMAL_MAP,satellite:G_SATELLITE_MAP,hybrid:G_HYBRID_MAP,physical:G_PHYSICAL_MAP}
		googlemaps.map.setMapType(map_types[googlemaps.options.map_type]);

		/* add controls */
		googlemaps.controls.each(function(control) {
			switch(control) {
			case 'small':
				googlemaps.map.addControl(new GSmallMapControl());
				break;
			case 'large':
				googlemaps.map.addControl(new GLargeMapControl());
				break;
			case 'overview':
				googlemaps.map.addControl(new GOverviewMapControl());
				break;
			case 'type':
				googlemaps.map.addControl(new GMapTypeControl());
				break;
			case 'scale':
				googlemaps.map.addControl(new GScaleControl());
				break;
			default:
			}
		});
		
		googlemaps.points.each(function(point) {
			var gPoint = new GLatLng(point.latitude, point.longitude);
			googlemaps.latLngBounds.extend(gPoint);
			
			var icon;
			switch(point.icon) {
			case 'green':
				icon = new GIcon();
				icon.image = 'gfx/gicon/green_dot/image.png';
				icon.shadow = 'gfx/gicon/green_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/green_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/green_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/green_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/green_dot/transparent.png';
				icon.imageMap = [19,0,20,1,21,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,23,13,23,14,22,15,21,16,20,17,20,18,19,19,19,20,18,21,18,22,17,23,17,24,17,25,17,26,16,27,16,28,16,29,16,30,16,31,14,31,14,30,14,29,14,28,14,27,14,26,13,25,13,24,13,23,12,22,12,21,12,20,11,19,10,18,10,17,9,16,8,15,7,14,7,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,7,5,7,4,8,3,9,2,10,1,11,0];
				break;
			case 'blue':
				icon = new GIcon();
				icon.image = 'gfx/gicon/blue_dot/image.png';
				icon.shadow = 'gfx/gicon/blue_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/blue_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/blue_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/blue_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/blue_dot/transparent.png';
				icon.imageMap = [22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;	
				case 'brown':
				icon = new GIcon();
				icon.image = 'gfx/gicon/brown_dot/image.png';
				icon.shadow = 'gfx/gicon/brown_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/brown_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/brown_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/brown_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/brown_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;
			case 'light blue':
				icon = new GIcon();
				icon.image = 'gfx/gicon/light_blue_dot/image.png';
				icon.shadow = 'gfx/gicon/light_blue_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/light_blue_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/light_blue_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/light_blue_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/light_blue_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;	
			case 'yellow':
				icon = new GIcon();
				icon.image = 'gfx/gicon/yellow_dot/image.png';
				icon.shadow = 'gfx/gicon/yellow_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/yellow_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/yellow_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/yellow_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/yellow_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;	
			case 'orange':
				icon = new GIcon();
				icon.image = 'gfx/gicon/orange_dot/image.png';
				icon.shadow = 'gfx/gicon/orange_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/orange_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/orange_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/orange_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/orange_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;	
			case 'lila':
				icon = new GIcon();
				icon.image = 'gfx/gicon/lila_dot/image.png';
				icon.shadow = 'gfx/gicon/lila_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/lila_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/lila_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/lila_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/lila_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;
			case 'red':
				icon = new GIcon();
				icon.image = 'gfx/gicon/red_dot/image.png';
				icon.shadow = 'gfx/gicon/red_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/red_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/red_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/red_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/red_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;
			case 'dark green':
				icon = new GIcon();
				icon.image = 'gfx/gicon/dark_green_dot/image.png';
				icon.shadow = 'gfx/gicon/dark_green_dot/shadow.png';
				icon.iconSize = new GSize(32,32);
				icon.shadowSize = new GSize(48,32);
				icon.iconAnchor = new GPoint(16,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/dark_green_dot/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/dark_green_dot/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/dark_green_dot/printShadow.gif';
				icon.transparent = 'gfx/gicon/dark_green_dot/transparent.png';
				icon.imageMap = 
[22,0,23,1,24,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,24,13,23,14,22,15,24,16,23,17,22,18,19,19,21,20,18,21,20,22,18,23,17,24,17,25,17,26,17,27,17,28,17,29,16,30,16,31,14,31,14,30,14,29,13,28,13,27,13,26,13,25,13,24,13,23,10,22,12,21,9,20,11,19,8,18,7,17,6,16,8,15,7,14,6,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,6,5,7,4,8,3,6,2,7,1,8,0];
				break;
			case 'monument':
				icon = new GIcon();
				icon.image = 'gfx/gicon/monument/image.png';
				icon.shadow = 'gfx/gicon/monument/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/monument/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/monument/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/monument/printShadow.gif';
				icon.transparent = 'gfx/gicon/monument/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;
			case 'ruin':
				icon = new GIcon();
				icon.image = 'gfx/gicon/ruin/image.png';
				icon.shadow = 'gfx/gicon/ruin/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/ruin/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/ruin/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/ruin/printShadow.gif';
				icon.transparent = 'gfx/gicon/ruin/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;
			case 'books':
				icon = new GIcon();
				icon.image = 'gfx/gicon/books/image.png';
				icon.shadow = 'gfx/gicon/books/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/books/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/books/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/books/printShadow.gif';
				icon.transparent = 'gfx/gicon/books/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;
			case 'books orange':
				icon = new GIcon();
				icon.image = 'gfx/gicon/books_orange/image.png';
				icon.shadow = 'gfx/gicon/books_orange/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/books_orange/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/books_orange/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/books_orange/printShadow.gif';
				icon.transparent = 'gfx/gicon/books_orange/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;
			case 'column':
				icon = new GIcon();
				icon.image = 'gfx/gicon/column/image.png';
				icon.shadow = 'gfx/gicon/column/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/column/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/column/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/column/printShadow.gif';
				icon.transparent = 'gfx/gicon/column/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;
			case 'headstone':
				icon = new GIcon();
				icon.image = 'gfx/gicon/headstone/image.png';
				icon.shadow = 'gfx/gicon/headstone/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/headstone/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/headstone/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/headstone/printShadow.gif';
				icon.transparent = 'gfx/gicon/headstone/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;
			case 'news':
				icon = new GIcon();
				icon.image = 'gfx/gicon/news/image.png';
				icon.shadow = 'gfx/gicon/news/shadow.png';
				icon.iconSize = new GSize(32,37);
				icon.shadowSize = new GSize(51,37);
				icon.iconAnchor = new GPoint(26,32);
				icon.infoWindowAnchor = new GPoint(16,0);
				icon.printImage = 'gfx/gicon/news/printImage.gif';
				icon.mozPrintImage = 'gfx/gicon/news/mozPrintImage.gif';
				icon.printShadow = 'gfx/gicon/news/printShadow.gif';
				icon.transparent = 'gfx/gicon/news/transparent.png';
				icon.imageMap = 
[31,0,30,1,31,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,31,29,30,30,29,31,23,32,22,33,21,34,20,35,19,36,12,36,11,35,10,34,9,33,8,32,2,31,1,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,1,1,2,0];
				break;																								
			default:
				icon = G_DEFAULT_ICON;
			}
			
			var gMarker = new GMarker(gPoint, icon);
			
			if (point.infoHtml) {
				var addDivHtml = '<div style="'+point.infoStyle+'" '+
					'class="'+point.infoClass+'">'+
					point.infoHtml
					+'</div>';
				
				GEvent.addListener(gMarker,'click', function() {
					googlemaps.map.openInfoWindow(
						gMarker.getLatLng(), 
						addDivHtml, 
						{
							// maxWidth: googlemaps.maxWidth
						}
					)
				});
			}
			
			googlemaps.markers.push(gMarker);
		});
		
		var maxZoom = googlemaps.map.getBoundsZoomLevel(googlemaps.latLngBounds);
		
		googlemaps.map.setZoom(maxZoom);
		googlemaps.map.setCenter(googlemaps.latLngBounds.getCenter());

		/* add a marker manager */
		googlemaps.mgr = new MarkerManager(googlemaps.map);
		googlemaps.mgr.addMarkers(googlemaps.markers, 0);
		googlemaps.mgr.refresh();

	},


	addControl: function(control) {
		googlemaps.controls.push(control);
	},

	addPoint: function(pointInfo) {
		// lets see if we have a marker at the same point

		var latitude = pointInfo.lat;
		var longitude = pointInfo.lng;
		var icon = pointInfo.icon;
		var infoHtml = pointInfo.html;
	
		latitude = latitude.parseDeg();
		longitude = longitude.parseDeg();

		var origLat = latitude;
		var origLng = longitude;
		
		/*
		firebug("attempting to add longitude:"+longitude+
				" latitude:"+latitude+
				" icon:"+icon);
*/
		var match = {point: null, type: 'add'};

		googlemaps.points.each(function(point) {
			if (match.type === 'addInfoHtml') {
				// we have a full match
				return;
			}
			/*
			firebug("checking longitude:"+point.longitude+
					" latitude:"+point.latitude+
					" icon:"+point.icon);
*/
			if (point.origLat === latitude &&
				point.origLng === longitude) {

				if (point.icon === icon) {
					match.point = point;
					match.type = 'addInfoHtml';
/*					firebug("full match"); */
				} else {
					match.point = point;
					match.type = 'offset';
/*					firebug("location match"); */
				}
			} else {
				// no match
			}
		});

		switch(match.type) {
		case 'addInfoHtml':
			/* firebug("same icon, same location, adding html"); */
			
			// same icon, add the html
			match.point.infoHtml = match.point.infoHtml + infoHtml;
			break;
		case 'offset':
			/* firebug("offsetting the location, not the same icon"); */
			
			var offsetLat = 0.0001;
			var offsetLng = 0.0002;
			
			// we can be sure that the point is always the first in this
			// location, so we can increment its offset 
			match.point.offset = match.point.offset+1;
			switch (match.point.offset) {
			case 1:
				latitude = latitude-offsetLat;
				longitude = longitude+offsetLng;
				break;
			case 2:
				latitude = latitude-offsetLat;
				break;
			case 3:
				latitude = latitude-offsetLat;
				longitude = longitude-offsetLng;
				break;
			case 4:
				longitude = longitude-offsetLng;
				break;
			case 5:
				latitude = latitude+offsetLat;
				longitude = longitude-offsetLng;
				break;
			case 6:
				latitude = latitude+offsetLat;
				break;
			case 7:
				latitude = latitude+offsetLat;
				longitude = longitude+offsetLng;
				break;
			case 8:
				longitude = longitude+offsetLng;
				break;
			default:
				alert("too many icon types (>8) in one location.");
			}
			// no break here, we need to add the new point
		default:
			googlemaps.points.push({
				latitude: latitude, 
				longitude: longitude,
				origLat: origLat,
				origLng: origLng,
				icon: icon,
				offset: 0,
				infoHtml: infoHtml,
				infoStyle: pointInfo.style,
				infoClass: pointInfo['class']
			});

			/* firebug(googlemaps.points); */
		}
	}
}


/* bildvergleich */

var imageCompare = {};

function findAllFrames(startwindow, frames) {
  // recursively find window
	if (typeof frames=='undefined') {
		frames = [];
	}
	// do we have frames?
	if (startwindow.frames && startwindow.frames.length > 0) {
		for (var i=0; i<startwindow.frames.length; i++) {
			frames.push(startwindow.frames[i]);
			findAllFrames(startwindow.frames[i], frames);
        }
    }
	return frames;
}


function startImageCompare(attrs) {
	// set attrs.selectOn and attrs.selectOff
	// starts the image compare, checks the window.opener for attrOn and attrOff
	
	if (!attrs.selectOn || !attrs.selectOff) {
		alert('\
startImageCompare needs the correct attrirbutes:\n\n\
startImageCompare(\n\
                {selectOn: "div[imagecompare]",\n\
                 selectOff: "div[result_standard]"}\n\
);\n');
    }

	// first we rescue the window.opener
	if (window.opener.name) {
		imageCompare.windowName = window.opener.name;
		imageCompare.windowTop = window.opener.top;
		imageCompare.selectOn = attrs.selectOn;
		imageCompare.selectOff = attrs.selectOff;
		imageCompare.change = function(switchOn) {
			var selectOn, selectOff;
			if (switchOn) {
				selectOn = imageCompare.selectOn;
				selectOff = imageCompare.selectOff;
			} else {
				selectOff = imageCompare.selectOn;
				selectOn = imageCompare.selectOff;
			}
			var frames = findAllFrames(imageCompare.windowTop);
			frames.each(function(f) {
				if (f.Prototype) {
					f.$$(selectOn).each(function(el) {
						el.style.display = 'block';
					});
					f.$$(selectOff).each(function(el) {
						el.style.display = 'none';
					});
				}
			});
		}
		checkImageCompare();
		Event.observe(window,'unload',function() {
			imageCompare.change(false);
		});
	}
}

function checkImageCompare() {
	if (imageCompare.change) {
		imageCompare.change(true);
		checkImageCompare.delay(1);
	}
}

