function resizeMe(w, h) {
  if (document.all) {
    // IE
    window.top.resizeTo(w,h);
  } else {
    window.top.outerWidth=w;
    window.top.outerHeight=h;
  }
}

function centerMe(w, h) {
  window.moveTo((screen.width-w)/2, (screen.height-h)/2);
}

function focusMe() {
  window.focus();
}

function closeMe() {
  window.close();
}

function printMe(textIfManualPrint) {
  try {
    window.print();
  } catch (exception) {
    if ((textIfManualPrint != null) && (textIfManualPrint != "")) {
      alert(textIfManualPrint);
    }
  }
}

/**
 * Dummy Funktion
 * Methode kann von jeder JSP im Body eingebunden, und bei Bedarf überschrieben werden
 * @param w
 * @param h
 */
function initMe(w, h) {
  // do nothing
}

// Fokussiert das erste Eingabefeld, kann auch nur solche mit einem Prefix berücksichtigen
function focusFirstInput(onlyIdsWithPrefix) {
  if (onlyIdsWithPrefix == null) {
    onlyIdsWithPrefix = "";
  }
  var node = privateGetFocusFirstInputNodeRecursively(onlyIdsWithPrefix, document)
  if (node != null) {
//    alert(node.getAttribute("id"));
    node.focus();
    node.select();
  }
}

// Nicht direkt rufen, gibt das Feld zurück das fokussiert werden soll
function privateGetFocusFirstInputNodeRecursively(onlyIdsWithPrefix, node) {
  if (onlyIdsWithPrefix == "popup:") {
    // Für IE < 7 Sonderfall alle ComboBoxen entfernen die im
    // Hintergrund sind, weil die oben gezeichnet werden
    if (node.nodeName.toLowerCase() == "select") {
      // Wenn nicht im Popup angezeigt
      var matchString = "^" + onlyIdsWithPrefix.toLowerCase() + ".*$";
      //      alert("MATCH_STRING: " + matchString + " ONLY_PREFIX: " + onlyIdsWithPrefix + " NODE_ID: " + node.getAttribute("id").toLowerCase());
      if (!node.getAttribute("id").toLowerCase().match(matchString)) {
        node.style.visibility = "hidden";
      }
    }
  }
  if ((node.nodeName.toLowerCase() == "input") ||
      (node.nodeName.toLowerCase() == "textarea")) {
    try {
      var type = node.type.toLowerCase();
      // keine buttons
      if (type == "submit") {
        return null;
      }
      if (type == "button") {
        return null;
      }
      // keine radios
      if (type == "radio") {
        return null;
      }
      // keine hidden
      if (type == "hidden") {
        return null;
      }
      // keine disabled
      if (node.disabled) {
        return null;
      }
      // keine readOnly
      if (node.readOnly) {
        return null;
      }
      var matchString = "^" + onlyIdsWithPrefix.toLowerCase() + ".*$";
//      alert("MATCH_STRING: " + matchString + " ONLY_PREFIX: " + onlyIdsWithPrefix + " NODE_ID: " + node.getAttribute("id").toLowerCase());
      if ((onlyIdsWithPrefix != "") && (!node.getAttribute("id").toLowerCase().match(matchString))) {
        return null;
      }
      return node;
    } catch (exception) {
      // ignorieren
    }
  }
  var children = node.childNodes;
  for (var i = 0; i < children.length; i++) {
    var result = privateGetFocusFirstInputNodeRecursively(onlyIdsWithPrefix, children.item(i));
    if (result != null) {
      return result;
    }
  }
  return null;
}

/*
 * Wenn wir von einem Popupfenster aus den Katalogframe updaten wollen funktioniert das nicht wenn
 * wir ohne Frameset laufen (In einem Frameset geht das weil man den Frame mit dem jeweiligen IETK_FRAME
 * Wert ansprechen kann). Deshalb wird in dem Fall wenn der oberste ietk Frame keinen Namen hat einfach der Name
 * auf ippMainWindow gesetzt
 */
function saveMainWindow(topFrame, newName) {
  if (topFrame.name == "") {
    topFrame.name = newName;
  }
}

/*
 * Debugfunktion, oeffnet aktuellen DOM in neuem Fenster
 *
 */
function debugDOM(doc) {
  var frame = open();
  var writeDocument = frame.document;
  writeDocument.write('<html><head></head><body><table><tr><td nowrap>');
  debugDOMRec(writeDocument, "", doc);
  writeDocument.write('</td></tr></table></body></html>');
  return frame;
}

/*
 * Rekursiv
 * Wird von svg_misc_debugOpenSVGInFrame aufgerufen
 *
 */
function debugDOMRec(writeDocument, prefix, node) {
  var children = node.childNodes;
  writeDocument.write(prefix + node + ",&nbsp;name: " + node.nodeName + ",&nbsp;value: " + node.nodeValue + ",&nbsp;data: " + node.data);
  if(node.nodeType == 1) {
    for (var i = 0; i < node.attributes.length; i++) {
      if (node.attributes.item(i).nodeValue != null) {
        writeDocument.write(", " + node.attributes.item(i).nodeName + "=\"" + node.attributes.item(i).nodeValue + "\"");
      }
    }
  }
  writeDocument.write('<br>');
  for (var i = 0; i < children.length; i++) {
    debugDOMRec(writeDocument, prefix + "&nbsp;&nbsp;&nbsp;&nbsp;", children.item(i));
  }
}

/*
 * Schreibt einen Text in ein Debug Fenster
 */
function debugWrite(text) {
  if (text == null) return;
  try {
    debugdoc.write(text + "<br>");
  } catch (exception) {
    var frame = open();
    debugdoc = frame.document;
    debugdoc.write(text + "<br>");
  }
}

/*
 * Hilfsfunktion, entfernt Whitespaces um String
 *
 */
function trim(string) {
  return string.replace(/(^\s*)|(\s*$)/g,'');
}

/*
 * Gibt Hexwerte zurück
 */
function toCharCodes(text) {
  var result = "";
  for (var i = 0; i < text.length; i++) {
    if (i > 0) {
      result += "-";
    }
    result += text.charCodeAt(i);
  }
  return result;
}

/**
 *  Gibt zurück ob ein Object in einem Array enthalten ist
 */
function isInArray(array, text) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == text) {
      return true;
    }
  }
  return false;
}


/*
 * Frühere Version der Methode
 */
function disableFormsSetHourglass(newButtonText) {
  return setDocumentEnabled(document, false, newButtonText, false);
}

function setDocumentEnabled(documentToSetEnabled, enabled, newButtonText, recursively) {
  try {
    if (documentToSetEnabled == null) {
      documentToSetEnabled = document;
    }
    var body = (documentToSetEnabled.getElementsByTagName('body').length == 0) ? null : documentToSetEnabled.getElementsByTagName('body')[0];
    // Führt dazu dass die [OOOOOOOOOOOOO.........] Ladeanzeige unten rechts im IE spinnt
    if (body != null) {
      if (body.style.old_cursor == null) {
        body.style.old_cursor = body.style.cursor;
        body.style.cursor     = 'wait';
      } else {
        body.style.cursor     = body.style.old_cursor;
        body.style.old_cursor = null;
      }

    }

    var inputElements = documentToSetEnabled.getElementsByTagName('input');
    for (var i = 0; i < inputElements.length; i++) {
      if (inputElements[i].type == "submit") {
        if (inputElements[i].old_value == null) {
          if (newButtonText != null) {
            inputElements[i].old_value        = inputElements[i].value;
            inputElements[i].style.old_cursor = inputElements[i].style.cursor;
            inputElements[i].value        = newButtonText;
            inputElements[i].style.cursor = 'wait';
          }
        } else {
          inputElements[i].value        = inputElements[i].old_value;
          inputElements[i].style.cursor = inputElements[i].style.old_cursor;
          inputElements[i].old_value = null;
          inputElements[i].style.old_cursor = null;
        }

        // Führt dazu dass die [OOOOOOOOOOOOO.........] Ladeanzeige unten rechts im IE spinnt
        if (inputElements[i].old_disabled == null) {
          inputElements[i].old_disabled     = inputElements[i].disabled;
          inputElements[i].style.old_cursor = inputElements[i].style.cursor;
          inputElements[i].style.old_color  = inputElements[i].style.color;
          inputElements[i].disabled     = "disabled";
          inputElements[i].style.cursor = 'wait';
          inputElements[i].style.color  = "#aca899";
        } else {
          inputElements[i].disabled     = inputElements[i].old_disabled;
          inputElements[i].style.cursor = inputElements[i].style.old_cursor;
          inputElements[i].style.color  = inputElements[i].style.old_color;
          inputElements[i].old_disabled     = null;
          inputElements[i].style.old_cursor = null;
          inputElements[i].style.old_color  = null;
        }
      }
    }
    var aElements = documentToSetEnabled.getElementsByTagName('a');
    for (var i = 0; i < aElements.length; i++) {
      // Führt dazu dass die [OOOOOOOOOOOOO.........] Ladeanzeige unten rechts im IE spinnt
      if (aElements[i].old_disabled == null) {
        aElements[i].old_onclick      = aElements[i].onclick;
        aElements[i].style.old_cursor = aElements[i].style.cursor;
        aElements[i].style.old_color  = aElements[i].style.color;
        aElements[i].old_disabled     = aElements[i].disabled;
        aElements[i].old_href         = aElements[i].href;
        aElements[i].onclick      = "return false;";
        aElements[i].style.cursor = 'wait';
        aElements[i].style.color  = "#aca899";
        aElements[i].disabled     = "disabled";
        var href = aElements[i].getAttribute("href");
        if((href) && (href != null) && (href != "")){
          aElements[i].removeAttribute('href');
        }
      } else {
        aElements[i].onclick      = aElements[i].old_onclick;
        aElements[i].style.cursor = aElements[i].style.old_cursor;
        aElements[i].style.color  = aElements[i].style.old_color;
        aElements[i].disabled     = aElements[i].old_disabled;
        aElements[i].setAttribute('href', aElements[i].old_href);
        aElements[i].old_onclick      = null;
        aElements[i].style.old_cursor = null;
        aElements[i].style.old_color  = null;
        aElements[i].old_disabled     = null;
        aElements[i].old_href         = null;
      }
    }

    if (recursively) {
      for (var i = 0; i < documentToSetEnabled.frames.length; i++) {
        // Führt dazu dass die [OOOOOOOOOOOOO.........] Ladeanzeige unten rechts im IE spinnt
        setDocumentEnabled(documentToSetEnabled.frames[i].document, enabled,
                           newButtonText, recursively);
      }
    }
  } catch (exception) {
    // ignorieren
  }
  return true;
}


/**
 * Dialogfenster das per Default zentral auf dem Bildschirm positioniert wird.
 * options ist der Option-String der JS-Methode window.open() ohne width und height
 */
function newDlg(url, target, width, height, options) {
  if (options != "") {
    options += ", ";
  }
  options += "width=" + width + ", height=" + height;

  // Resizable yes wenn nicht explizit angegeben
  if (options.indexOf("resizable=") == -1) {
    options += ", resizable=yes";
  }

  // wenn Fensterposition nicht explizit vorgegeben positionieren wir auf Bildschirmmitte
  if ((options.indexOf("left=") == -1) || (options.indexOf("top=") == -1)) {
    var screenX = (screen.width-width)/2;
    var screenY = (screen.height-height)/2;
    options += ", left=" + screenX + ", top=" + screenY;
  }
  //alert(options);
  var dlg = window.open(url, target, options);
  if (dlg != null) { // null wenn geblockt durch Popup-Blocker
    dlg.focus();
  }
  return dlg;
}

/**
 * Prüft eine Eingabe im onKeyPress auf maxlength
 */
function checkInputMaxLength(textObject, max) {
  if (max > 0) {
    return (textObject.value.length < max);
  }
  return true;
}

/**
 * Browserunabhängige Bestimmung des Event-Ziels
 */
function eventTarget(event) {
  return (window.Event) ? event.target : event.srcElement;
}
/**
 * Callback
 * Sendet die geänderten Frame/View Darstellungen an den Server.
 */
function callbackHandler(ietkToolbarDoc, cbAction, cbVal) {
  var callbackIFrame = ietkToolbarDoc.document.getElementById("invisibleTarget");
  if (callbackIFrame != null) {
    callbackIFrame.src = "../callbackServlet?callback=" + cbAction + "&set=" + cbVal;
  }
}

/**
 * Objekt zur Bestimmung von Doppelclick Events (in einem Viewer)
 *
 * Verwendet, wenn die Controls kein double-click Event selbst anbieten
 */
function DoubleClickHandler() {
  this.lastPickedObj = null;
  this.pickTimeLastObj = null;
  this.timeoutId = null;

  /**
   * Methode zur Prüfung, ob der Click ein Doppelclick ist
   * @param currentlyPickedObject  aktuell angeclicktes Objekt
   * @param expiryTimeMilis        Zeitspanne, in der der (Folge-)Click als Doppelclick gewertet wird
   * @param debugFlag              Debug-Ausgaben ein-/ausschalten
   */
  this.isDoubleClick = function(currentlyPickedObject, expiryTimeMilis, debugFlag) {
    if (debugFlag) debugWrite("----------------- DOUBLE CLICK START -----------------");
    var pickTimeNow = new Date().getTime();
    if (debugFlag) {
      debugWrite("Current Obj: " + currentlyPickedObject + "\tLast Obj: " + this.lastPickedObject +
                 "\tEqual: " + (currentlyPickedObject == this.lastPickedObject));
      debugWrite("Current Timestamp: " + pickTimeNow + "\tLast Timestamp: " + this.pickTimeLastObject +
                 "\tDiff: " + (pickTimeNow - this.pickTimeLastObject));
    }
  //  if (debugFlag) debugWrite("picktime now: " + pickTimeNow + "\tprior picktime: " + pickTimeLastObject);
    var isDoubleClickBoolean = false;
    try {
      if ((this.pickTimeLastObject != null && typeof(this.pickTimeLastObject) != undefined) &&
          (this.lastPickedObject   != null && typeof(this.lastPickedObject)   != undefined)) {
  //      if (debugFlag) debugWrite("current object == last object: " + (currentlyPickedObject == lastPickedObject));
        if (currentlyPickedObject == this.lastPickedObject) {
          var diff = pickTimeNow - this.pickTimeLastObject;
          if (debugFlag) debugWrite("<b>diff: " + diff + "</b>");
          if (diff > 200 && diff < (expiryTimeMilis * 1)) {
            isDoubleClickBoolean = true;
          }
        }
      }
    } catch (exception) {
      if (debugFlag) debugWrite("exception: " + exception.message);
    }
    if (isDoubleClickBoolean) {
      this.pickTimeLastObject = null;
      this.lastPickedObject = null;
      window.clearTimeout(this.timeoutId);
    } else {
      this.pickTimeLastObject = pickTimeNow;
      this.lastPickedObject = currentlyPickedObject;
      this.timeoutId = setTimeout(function() {resetDoubleClickHandler(this);}, expiryTimeMilis);
    }
    if (debugFlag) {
      debugWrite("setting lastpicktime: " + this.pickTimeLastObject);
      debugWrite("setting lastpickobject: " + this.lastPickedObject);
      debugWrite("result: " + isDoubleClickBoolean);
      debugWrite("----------------- DOUBLE CLICK ENDE -----------------");
    }
    return isDoubleClickBoolean;
  }
}

/**
 * Setzt die aktuellen Attribute im DoubleClickHandler zurück
 * @param doubleClickHandler
 */
function resetDoubleClickHandler(doubleClickHandler) {
  doubleClickHandler.lastPickedObj = null;
  doubleClickHandler.pickTimeLastObj = null;
}

/**
 * Wandelt RGB in OLE Format um (Integer Wert zur Repräsentation)
 * @param red
 * @param green
 * @param blue
 */
function getRGBInteger(red, green, blue) {
  return (red + green*256 + blue*65536);
}
/**
 * Aus Calender.html entnommen
 * @param hexCode
 */
function hex2rgb(hexCode) {
    var hexCode = hexCode.replace(/#/,'');
    var rgb = new Array();
    rgb["red"] = parseInt(hexCode.substr(0,2),16);
    rgb["green"] = parseInt(hexCode.substr(2,2),16);
    rgb["blue"] = parseInt(hexCode.substr(4,2),16);
    return rgb;
}

/**
 * Prüft ob der String eine (Gleitkomma-)Zahl ist
 * @param str
 */
function isNumeric(str) {
  str = trim(str);
  str = str.replace(/,/, ".")
  var regexLiteral = /^[0-9]+[\.]?[0-9]*$/;
  return regexLiteral.test(str);
}

/**
 * Setzt das Highlighting einse Eintrages in der Tabelle
 *
 * Die aktuelle Zeile (theRow) die selektiert ist, wird als Attribut in der Tabelle eingetragen.
 * Ist bereits eine Zeile selektiert gewesen, wird diese automatisch deselektiert.
 * @param tablename
 * @param rowPrefix   ID der Zeile (ohne die Index-Ziffer)
 * @param theRow      Aktuelles Zeilen-Objekt
 * @param scrollToVisible
 */
function doHighlightBackground(tablename, rowPrefix, theRow, scrollToVisible) {
  var testInverse = /Inverse$/;
  if (theRow != null) {
    if (typeof(theRow.style) == 'undefined' || typeof(theRow.cells) == 'undefined') {
      return false;
    }
    if (scrollToVisible != null && scrollToVisible) {
      // Damit die erste Zeile immer oben ist
      var rowLine = theRow.id.substring(theRow.id.lastIndexOf("-") + 1);
      location.hash = rowPrefix + (rowLine -1);
    }
  }
  var table = document.getElementById(tablename);
  if (table != null) {
    var selectedRowId = table.getAttribute("selectedrow");
    var selectedRow = null;
    if (selectedRowId != null) {
      selectedRow = document.getElementById(selectedRowId);
    }
    if (selectedRow != null) {
      var row_cells_cnt = selectedRow.cells.length;
      for (var c = 0; c < row_cells_cnt; c++) {
        var className = selectedRow.cells[c].className;
        if (testInverse.test(className)) {
          var newClassName = className.substring(0, className.length - 7);
          selectedRow.cells[c].className = newClassName;
          for (var i = 0; i < selectedRow.cells[c].childNodes.length; i++) {
            var child = selectedRow.cells[c].childNodes[i];
            if (child.nodeName.toLowerCase() == "a") {
              child.className = newClassName;
            }
          }
        }
      }
    }
  }
  if (theRow == null) {
    return false;
  }
  var row_cells_cnt = theRow.cells.length;
  for (var c = 0; c < row_cells_cnt; c++) {
    var className = theRow.cells[c].className;
    theRow.cells[c].oldClassName = className;
    if (testInverse.test(className)) {
      var newClassName = className.substring(0, className.length - 7);
      for (var i = 0; i < theRow.cells[c].childNodes.length; i++) {
        var child = theRow.cells[c].childNodes[i];
        if (child.nodeName.toLowerCase() == "a") {
          child.className = newClassName;
        }
      }
    } else {
      var newClassName = className + "Inverse";
      theRow.cells[c].className = newClassName;
      for (var i = 0; i < theRow.cells[c].childNodes.length; i++) {
        var child = theRow.cells[c].childNodes[i];
        if (child.nodeName.toLowerCase() == "a") {
          child.className = newClassName;
        }
      }
    }
  }
  if (table != null) {
    table.setAttribute("selectedrow", theRow.id);
  }
  return true;  
}

/**
 * benötigt prototype.js
 * @param url Seite mit HTML Fragement das geladen werden soll
 * @param id HTML ID des Containers der mit HTML Fragment aktualisiert wird 
 */
function ajaxUpdateContainer(url, id) {
  new Ajax.Updater(id, url, {
      method: 'get'
  });  
}

