/**
 * <copyright>
 *  Copyright (c) Hyperwave GmbH 2010
 * </copyright>
 *
 * $Id: cookie.js 152677 2010-01-29 12:00:08Z merge $
 */
function setCookie(name, value, expire, domain) {
  var cookie = getCookie(name);
  if (cookie != value)
    document.cookie = name + "=" + encodeURIComponent(""+value) +
                      ((expire == null) ? "" : ("; expires=" + expire.toGMTString())) +
                      ";path=/" +
                      ((domain) ? ";domain=" + domain : "");
}
function getCookie(Name){
   var search = Name + "=";
   var cookie=null;
   if (document.cookie.length > 0) { // if there are any cookies
     offset = document.cookie.indexOf(search);
     if (offset != -1) { // if cookie exists
       offset += search.length;
                         // set index of beginning of value
       end = document.cookie.indexOf(";", offset);
                         // set index of end of cookie value
       if (end == -1)
          end = document.cookie.length;
       var cookie_value = document.cookie.substring(offset, end);
       if ( !cookie_value )
         cookie_value = "";
       return decodeURIComponent(cookie_value);
     }
   }
   return cookie;
}

function hw_reloadFunc(){
  window.location.reload();
}

var ahwcookie=getCookie("HW_Reload");
if(ahwcookie != null){
  var cstate = ahwcookie.split(':');
  if (cstate=="yes"){
    setCookie("HW_Reload","no",null);
    if (navigator.appName=="Netscape" || (navigator.platform.toLowerCase().indexOf('mac')!=-1))
      window.onload=hw_reloadFunc;
    else
      window.location.reload();
  }
}

/*
 * <copyright>
 *  Copyright (c) Hyperwave GmbH 2010
 * </copyright>
 *
 * <file>
 *  Name:        windowlib.js
 *  Created:     2002-04-07 by sweber
 *  Description: file for virtual folders html dialogs (vf compatibility)
 *               window communication functions
 *
 *  $Id: windowlib.js 154835 2010-05-04 15:20:21Z sweber $
 * </file>
 */

if (!window.FILE_WINDOWLIBJS_INCLUDED) {
  /**
   * This function returns true if the ui is generated in Hyperwave Explorer.
   *
   * @return: boolean: is hwe context or not
   */
  function isHwe() {
  	if(top.external && typeof top.external.HWEisHWEBrowser == "boolean" && top.external.HWEisHWEBrowser) {
  		return true;
  	}
  	else {
  		return false;
  	}
  }
  
  /**
   * This function returns the current version of the Hyperwave Explorer if the
   * ui is generated in hwe.
   *
   * @return: string: the hwe version
   */
  function getHweVersion() {
  	if(isHwe()) {
  		return top.external.HWEGetHWEVersion();
  	}
  	else {
  	  return "";
  	}
  }
    
  /**
   * close the current window
   *
   * @return: ...: return value of window.close()
   */
  function window_close() {
    if (isHwe()) {
  	 return top.external.HWECloseWindow(0);
    }

    return top.close();
  }
  
  /**
   * change the window size
   *
   * @param x: number: width of window
   * @param y: number: height of window
   *
   * @return: ...: return value of resize
   */
  function window_resizeTo(x, y) {
    if (isHwe()) {
    	return top.external.HWEResizeTo(x, y);
    }
    try
    {
      return top.resizeTo(x, y);
    }
    catch (e) {};
  }

  /**
   * change the window size
   *
   * @param x: number: width of window
   * @param y: number: height of window
   *
   * @return: ...: return value of resize
   */
  function window_resizeBy(x, y) {
    if (isHwe()) {
    	return top.external.HWEResizeBy(x, y);
    }

    return top.resizeBy(x, y);
  }

  function window_moveTo(x, y) {
    if (isHwe()) {
    	return top.external.HWEMoveTo(x, y);
    }

    return top.moveTo(x, y);
  }

  function window_moveBy(x, y) {
    if (isHwe()) {
    	return top.external.HWEMoveBy(x, y);
    }

    return top.moveBy(x, y);
  }

  function window_focus() {
    if (isHwe()) {
    	return top.external.HWESetFocus("");
    }

    return top.focus();
  }

  /**
   * This function executes a reload in listview.
   */
  function listview_reload() {
    if (isHwe()) {
    	return top.external.HWEListviewReload("");
    }
    
    var ref = _getListView();
    if (ref != null) {
      ref.location.replace(ref.location + "");
      return true;
    }
    else {
      return false;
    }
  }
  
  /**
   * This function loads an object path into the listview.
   */
  function listview_navigate(theObjectPath) {
    if (isHwe()) {
      return top.external.HWEListviewNavigate(theObjectPath);
    }
    
    var ref = _getListView();
    if (ref != null) {
      ref.location.href = theObjectPath;
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * opens a new window
   *
   * @param url: string: url of page
   * @param name: string: window name
   * @param style: string: the window style
   *
   * @return: object: the window object
   */
  function window_open(url, name, style) {
    if (isHwe()) {
  	 return top.external.HWEOpenWindow(url, name || "", style || "", arguments[3] || false /* replace */, arguments[4] || false /* modal */);
    }
    
    return open(url, name, style);
  }

  /**
   * set a string into a form element of another window (e.g. opener)
   *
   * @param args: object: function parameters
   * @param args.windowName: string: the name of the window ("opener" is default)
   * @param args.formName: string: name of the formular
   * @param args.elementName: string: name of the element
   * @param args.elementValue: string: value of the element to set
   * @param args.setFocus: boolean: set focus after execute the given element
   * @param args.type: string("set"|"get"): is it a set or a get operation?
   *
   * @return (type == "set"): boolean: operation successfull
   * @return (type == "get"): strint: value of the field
   */
  function window_transfer(args)
  {
    var pars = args || {};
    if (isHwe()) {
      if (pars.type == "set")
      {
        var ret = top.external.HWESetFormElementValue("parent", pars.formName, pars.elementName, pars.elementValue);

        var form_str = 'document.forms["' + pars.formName + '"]';
        var elem_str = form_str + '.elements["' + pars.elementName + '"]';
        var func_str = elem_str + '.onchange';
        var code = ["if (" + form_str + " && " + elem_str + " && " + func_str + ") {",
                    "  " + func_str + "()",
                    "}"];
        top.external.HWEExecScript("parent", code.join("\n"));

        if (pars.setFocus) { // set focus
        	top.external.HWESetFocus("parent", pars.formName, pars.elementName);
        }
        return ret;
      }
      else if (pars.type == "get")
      {
        return top.external.HWEGetFormElementValue("parent", pars.formName, pars.elementName);
      }
      throw 'Error: No type or unsupported type for function "window_transfer" given.';
    }
    
    var the_window = top.opener;
    if (!the_window || typeof(the_window) != "object" || the_window.closed)
    { // window doesn't exist or is unknown
      return pars.type == "get" ? "" : false;
    }
    var the_form = eval("the_window.document." + pars.formName);
    if (!the_form || typeof(the_form) != "object")
    { // form doesn't exist
      return pars.type == "get" ? "" : false;
    }
    var the_element = the_form[pars.elementName];
    if (!the_element || typeof(the_element) != "object")
    { // form doesn't exist
      return pars.type == "get" ? "" : false;
    }
    if (pars.type == "set")
    { // assign the value
      the_element.value = pars.elementValue;
      if (pars.setFocus &&
         (typeof the_element.focus == "function" || /* non-msie */
          typeof the_element.focus == "object" && the_element.focus && the_element.focus.call /* msie */))
      { // set focus
        try {
          the_element.focus();
        }
        catch (exc) {}
      }
      if (the_element.onchange)
      { // trigger onchange
        the_element.onchange();
      }
      return true;
    }
    else if (pars.type == "get")
    { // return the value
      return the_element.value || "";
    }
    throw "Error: No type for function \"window_transfer\" given.";
  }
  
  //--------------------------------------------------------------------
  /**
   * returns the selected objects from the main window
   *
   * @param args: object: function parameters
   * @param args.errMsg: string: error message
   *
   * @return: array: array of selected objects
   */
  function window_getSelectedObjects(args) {
    if (isHwe()) {
      return eval(top.external.HWEGetSelectedObjectsString());
    }
    
    if (top.opener && typeof top.opener == "object" && !top.opener.closed) {
      var g_listing = top.opener.top.gListing;
      if (typeof g_listing != "undefined") {
        return g_listing.getSelectedObjects();
      }
    }
    else if (args && args.errMsg) {
      alert(errMsg);
    }
    return [];
  }
  
  //--------------------------------------------------------------------
  /**
   * parse a string to get the form name and element name
   *
   * @param str: string: string to parse (e.g. "insertform['x']" or "insertform.x")
   *
   * @return object: return object
   * @return object.formName: name of form (e.g. "insertform")
   * @return object.elementName: name of element (e.g. "x")
   */
  function window_parseFormAndElementName(str)
  {
    var ret_obj = {formName: "", elementName: ""};
    var tmp = str.match(/(^.+\[\d+\])\s*([\.\[])(.+)/); // was form name  specfied with forms[0] or forms[1] etc. ?
    if (tmp == null) {
      tmp = str.match(/([^\.\[\s]+)\s*([\.\[])(.+)/); // no, form name was specified as string like "myform"
    }
  
    ret_obj.formName = tmp[1];
    if (tmp[2] == ".")
    {
      var idx = str.lastIndexOf(".");
      ret_obj.formName = str.substring(0,idx).replace(/\s+/g,"");
      ret_obj.elementName = str.substring(idx + 1).replace(/\s+/g,"");
    }
    else if (tmp[2] == "[")
    {
      ret_obj.elementName = tmp[3].match(/([\"\'])(.+)\1/)[2];
    }
    return ret_obj;
  }
  
  //--------------------------------------------------------------------
  /**
   * is a special escaping function (for passing string through urls)
   * @see: ./hwlib.js
   *
   * @param str: string: string to escape
   * @return string: escaped string
   */
  function window_escape(str)
  {
    return encodeURIComponent(str).replace(/~/g, "%7E").replace(/\%/g, "~");
  }
  
  //--------------------------------------------------------------------
  /**
   * the special unescaping function (for passing string through urls)
   * @see: ./hwlib.js
   *
   * @param str: string: escaped string
   * @return string: unescaped string
   */
  function window_unescape(str)
  {
    return decodeURIComponent(str.replace(/\~/g, "%"));
  }
  
  var window_old_status_ = null;
  function window_setStatus(str)
  {
    var is_IE = typeof(document.all) != "undefined";
    if (is_IE)
    {
      window_old_status_ = status;
      if (!str)
      {
        str = document.location.href;
        var action_separator = (str.indexOf(";") > 0 ? str.indexOf(";") : str.length);
        str = str.substring(0,action_separator);
      }
      window.status = decodeURIComponent(str);
      return true;
    }
    return false;
  }
  
  function window_resetStatus()
  {
    if (window_old_status_ != null)
    {
      status = window_old_status_;
    }
    return true;
  }
  
  /**
   * This function loads an url into the opener location.
   *
   * @param args: object: parameter object
   * @param args.url: string | void: the target url (if empty the current url will be used -> reload)
   * @param args.op: boolean | false: set location in opener window
   * @return boolean: success or not
   */
  function window_setLocation(args)
  {
    var args = args || {};
    try {
      var ref = top;
      if (args.op) {
        // execute on opener
        try {
          ref = top.opener.top.frames.HW_Subframe.frames.HW_Mainframe;
        }
        catch (e) {
          ref = top.opener;
        }
      }
  
      if (args.url) {
        ref.location.href = args.url;
      }
      else {
        ref.location.replace(ref.location.href);
      }
    }
    catch (e) {
      return false;
    }
    return true;
  }
  
  /**
   * Reloads the opener window.
   *
   * @param args.keepUrl: boolean | false: should the url be the same as before the reload.
   *                                       otherwise the action will be truncated
   * @return boolean: success or not
   */
  function window_reloadOpener(args)
  {
    var args = args || {};
    try {
      if (top.window.opener) {
        var locRef = top.window.opener.location;
  
        if (top.window.opener.top.frames.HW_Subframe &&
            top.window.opener.top.frames.HW_Subframe.frames.HW_Mainframe) {
          locRef = top.window.opener.top.frames.HW_Subframe.frames.HW_Mainframe.location;
        }
  
        var openloc = locRef.href;
  
        if (!args.keepUrl) {
          var intidx = openloc.indexOf(';internal');
          if (intidx != -1) {
            openloc = openloc.substring(0, intidx);
          }
          openloc += ';internal&Parameter=' + new Date().valueOf();
          var context = top.window.opener.top.gCurrentContext;
          if (context) {
            openloc += "&ctx=" + context;
          }
        }
  
        locRef.replace(openloc);
      }
    }
    catch (e) {
      return false;
    }
    return true;
  }
  
  /**
   * debug function for client side debug
   */
  function window_debug() {
    function htmlEscape(str) {
      return (str + "").replace(/(\<|\>|\&|\"|\'|\n|\r)/g,
                                function (match, c) {
                                  if (c == "<") {
                                    return "&lt;";
                                  }
                                  if (c == ">") {
                                    return "&gt;";
                                  }
                                  if (c == "&") {
                                    return "&amp;";
                                  }
                                  if (c == '"') {
                                    return "&quot;";
                                  }
                                  return "&#" + c.charCodeAt(0) + ";";
                                });
    }
    
    if (window_debug.window) {
      var win = window_debug.window;
      var doc = win.document;
    }
    else {
      window_debug.window = window.open("", "debug", "height=800,width=300,top=0,left=0,resizable=yes,scrollbars=yes");
      var win = window_debug.window;
      var doc = win.document;
      var start_html = ["",
                        "<html>",
                        "<head>",
                        "<title>DEBUG</title>",
                        "</head>",
                        "<body style='font-family: courier; font-size: 80%; margin: 0px;'>",
                        ""].join("");
      
      doc.open();
      doc.writeln(start_html);
    }

    var ctr = win.ctr_ || (win.ctr_ = 0);
    win.ctr_ ++;

    var style = "border-bottom: 1px dashed gray; padding-bottom: 1px; white-space: pre-wrap;";
    if (window_debug.last_date != document.lastModified) {
      window_debug.last_date = document.lastModified;
      style += " border-top: 1px dashed red;";
    }
    try {
      var stack = new Error().stack || "";
      stack = stack.replace(/^\(/mg, "???(");
      stack = stack.replace(/^/mg, " ~ ");
    }
    catch (exc) {
      var stack = "";
    }

    var id = "stack_" + ctr;
    var oc = "var s = document.getElementById('" + id + "').style; s.display = s.display == 'none' ? 'block' : 'none';";

    doc.write("<div style='" + htmlEscape(style) + "' onclick='" + htmlEscape(oc) + "'>");
    for (var i = 0; i < arguments.length; i ++) {
      var type = typeof arguments[i];
      var curr = htmlEscape(arguments[i]);
      curr = curr.replace(/\b(window|document|onload|onunload|onresize)\b|(\-+(\&gt\;)+|(\&lt\;)+\-+)/g,
                          function (match, m1, m2) {
                            if (m1) {
                              return "<u>" + m1 + "</u>";
                            }
                            if (m2) {
                              return "<b style='color: red;'>" + m2 + "</b>";
                            }
                            return match;
                          });
      if (type == "string") {
        doc.write(curr);
      }
      else {
        doc.write("<i title='" + htmlEscape(type) + "'>" + curr + "</i>");
      }
    }
    doc.writeln("</div>");
    doc.writeln("<div id='" + htmlEscape(id) + "' style='display: none; font-weight: bold; white-space: pre-wrap;'>" + htmlEscape(stack) + "</div>");
    
    win.scrollTo(0, 1e6);
  }

  /* This is an object to hold some debug functions - kind of oop */
  $debug = {};

  $debug.writeln = window_debug;
  
  /**
   * This function returns some properties of a given object.
   *
   * <xmp>
   * $debug.getProperties(x, ["x", "y"]); // returns "x = ...\ny = ..."
   * $debug.getProperties(obj, ["client", "offset", "scroll"], ["Width", "Height", "Top", "Left"]);
   *   // returns "clientWith = ...\nclientHeight = ...\nclientTop = ...\nclientLeft = ...\n..."
   * </xmp>
   * 
   * @param obj: Object: the object to test
   * @param propName1: string[]: list of property names
   * @param propName2: string[]|void: list of property postfixes
   * @return: string: the debug information
   */
  $debug.getProperties = function (obj, propName1, propName2) {
    var res = [];
    (propName1 || []).each(function (prop1) {
        (propName2 || [""]).each(function (prop2) {
            var key = prop1 + prop2;
            res.push([key, obj[key]].join(" = "));
          });
      });
    return res.join("\n");
  };

  /**
   * This method returns all dimension properties of an object.
   * e.g. clientWith, clientHeight, ...
   *
   * @param obj: Object: the object to test
   * @return: string: the debug information
   */
  $debug.getDimensions = function (obj) {
    return "id = " +obj.identify() +
      "\n" +
      $debug.getProperties(obj, ["client", "offset", "scroll"], ["Width", "Height", "Top", "Left"]) +
      "\n" +
      "style_width = " + obj.getStyle("width") +
      "\n" +
      "style_height = " + obj.getStyle("height") +
      "\n" +
      "width = " + obj.getWidth() +
      "\n" +
      "height = " + obj.getHeight();
  };

  /**
   * This method calls a given function periodically and write the output
   * into a debug window.
   *
   * @param func: function: the debug function
   */
  $debug.watchFunction = function (func, _id) {
    var id = _id || "watch_object_" + new Date().valueOf();

    var cache = this.watchFunction.cache || (this.watchFunction.cache = {});
    var win = cache[id];

    if (!cache[id] || cache[id].closed) {
      cache[id] = window.open("about:blank", id, "height=300,width=300");
      var win_ = cache[id];
      addToOnunload(function () { win_.close(); });
    }
    var win = cache[id];
    var doc = win.document;
    
    doc.open("text/plain");
    doc.writeln(func());
    doc.close();
    
    if (!_id) {
      var interval = setInterval(function () {
          try {
            $debug.watchFunction(func, id);
          }
          catch (exc) {
            clearInterval(interval);
          }
        }, 1000);
    }
  };

  /**
   * This method write request properties of a given object to a
   * debug window periodically. This is similar as method `getProperties`
   * but the output is directly written into a debug window.
   *
   * @param obj: Object: the object to test
   * @param propName1: string[]: list of property names
   * @param propName2: string[]|void: list of property postfixes
   */
  $debug.watchObject = function (obj, propName1, propName2) {
    this.watchFunction(function () {
        return $debug.getProperties(obj, propName1, propName2);
      });
  };
  
  /**
   * This function calls an other function in opener window and returns the return value.
   * Only strings can be handled by this function.
   * Maybe you can use eval() and com.hyperwave.util.ObjectExt.static_.toSource() on client side.
   * Up to 9 parameters can be handled.
   *
   * @param theFunctionName: string: the function name to call in opener
   * @param p1: string | void: the 1st parameter
   * @param p2: string | void: the 2nd parameter
   * @param p3: string | void: the 3rd parameter
   * @param p4: string | void: the 4th parameter
   * @param p5: string | void: the 5th parameter
   * @param p6: string | void: the 6th parameter
   * @param p7: string | void: the 7th parameter
   * @param p8: string | void: the 8th parameter
   * @param p9: string | void: the 9th parameter
   *
   * @return string: the return value
   */
  function window_executeInOpener(theFunctionName) {
    if (isHwe()) {
      var code = theFunctionName + "(";
      for (var i = 1; i < arguments.length; i ++)
      {
        code += 'decodeURIComponent("';
        code += encodeURIComponent(arguments[i]);
        code += '")';
        if (i < (arguments.length-1))
        {
          code += ", ";
        }
      }
      code += ")";
      return decodeURIComponent(top.external.HWEExecScriptFunction('parent', code));
    }
    
    // parameter check
    if (arguments.length > 10) {
      throw 'To much arguments for function call "' + theFunctionName + '" in window_executeInOpener!';
    }
  
    if (typeof theFunctionName != 'string') {
      throw 'Wrong parameters for window_executeInOpener! 1st argument must be typeof string.';
    }
    
    for (var i = 1; i < arguments.length; i ++) {
      if (typeof arguments[i] != 'undefined' && typeof arguments[i] != 'string') {
        throw 'Wrong parameters for window_executeInOpener! ' + i + '. argument must be typeof string.';
      }
    }
  
    try {
      if (navigator.appName == "Microsoft Internet Explorer") { // apply didn't worked in FF
        var ret = top.opener[theFunctionName].call(top.opener, arguments[1] || ''
                                                             , arguments[2] || ''
                                                             , arguments[3] || ''
                                                             , arguments[4] || ''
                                                             , arguments[5] || ''
                                                             , arguments[6] || ''
                                                             , arguments[7] || ''
                                                             , arguments[8] || ''
                                                             , arguments[9] || '');
      }
      else { // call didn't worked in IE
        var new_args = [];
        for (var i = 1; i < arguments.length; i ++) {
          new_args.push(arguments[i]);
        }
        var ret = top.opener[theFunctionName].apply(top.opener, new_args);
      }
    }
    catch (e) {
      // If something goes wrong here, check the function called above. It seems it is not possible
      // to catch an error or exception of the opener window. So an exception can happen but cannot be catched here.
      throw 'Error calling function "' + theFunctionName + '" in window_executeInOpener!\n\n' + e;
    }
  
    if (typeof ret == 'undefined' || ret == null) {
      ret = '';
    }
    else if (typeof ret == 'boolean' || typeof ret == 'number') {
      ret = ret.toString();
    }
    else if (typeof ret != 'string') {
      throw 'Wrong return value of called function "' + theFunctionName + '" in window_executeInOpener! Must be typeof string.';
    }
  
    return ret;
  }
  
  /**
   * This is a shortcut to function window_transfer with type "get".
   * @param theFormName: string: the form name
   * @param theElementName: string: the element name
   *
   * @return string: the element value
   */
  function window_getFormValueFromOpener(theFormName, theElementName) {
    return window_transfer({type: "get",
                            formName: theFormName,
                            elementName: theElementName});
  }
  
  /**
   * This is a shortcut to function window_transfer with type "set".
   * @param theFormName: string: the form name
   * @param theElementName: string: the element name
   * @param theElementValue: string: the element value
   *
   * @return boolean: success or not
   */
  function window_setFormValueInOpener(theFormName, theElementName, theElementValue) {
    return window_transfer({type: "set",
                            formName: theFormName,
                            elementName: theElementName,
                            elementValue: theElementValue});
  }
  
  /**
   * This function returns the reference to the listview.
   *
   * @return: window|null: the window reference to listview
   */
  function _getListView() {
    var ref = top;
    try {
      while (ref.name != "HW_Mainwindow") {
        if (!ref.opener || ref.opener.closed) {
          return;
        }
        ref = ref.opener.top;
      }
      
      if (ref.frames.HW_Subframe &&
          ref.frames.HW_Subframe.frames.HW_Mainframe) {
        ref = ref.frames.HW_Subframe.frames.HW_Mainframe;
      }
      else {
        ref = null;
      }
    }
    catch (exc) {
      // alert(exc + "");
      ref = null;
    }
    return ref;
  }
  
  isHWE = isHwe;
  getHWEVersion = getHweVersion;
  
  function adjustForHWE() {
    if (isHwe()) {
      // tell the HWE, that the JS compatibility code is already defined
      if (typeof top.external.HWESetCompatibilityVersion != "undefined") { // necessary because type is "unknown"?!
        top.external.HWESetCompatibilityVersion(1);
      }

      // for web context, this function is defined in webapp/lib/reloadandclose.html
      // function defined as anonymous so that javascript interpreter does not overwrite the function definition
      // in reloadandclose.html (function definition are searched on parsing js files and used regarless the
      // if statement is true or false) see also HVF/PR-866
      window_reloadandclose = function () {
        return top.external.HWECloseWindow(1);
      };

      // the following function is not provided in templates
      hwvfSendMsg = function (recipient, msg, bAppend) {
        top.external.HWESendMessage(recipient, msg, bAppend || false);
      };
    }

    if (isHwe()) {
      //hwvfListViewNavigate = listViewNavigate = listview_navigate;
      //hwvfListViewReload = listViewReload = listview_reload;
      window.open = hwvfWindowOpen = window_open;
      window.focus = hwvfFocus = window_focus;
      window.moveBy = hwvfWindowMoveBy = window_moveBy;
      window.moveTo = hwvfWindowMoveTo = window_moveTo;
      window.resizeBy = hwvfWindowResizeBy = window_resizeBy;
      window.resizeTo = hwvfWindowResizeTo = window_resizeTo;
      window.close = hwvfclose = window_close;

      hwvfreloadandclose = window_reloadandclose;
      hwvfWindowTransfer = window_transfer;
      hwvfGetSelectedObjects = window_getSelectedObjects;
      hwvfExecuteInOpener = window_executeInOpener;
    }
  };
  adjustForHWE();
  
}
window.FILE_WINDOWLIBJS_INCLUDED = true;

/*
 * <copyright>
 *  Copyright (c) Hyperwave GmbH 2010
 * </copyright>
 *
 * <file>
 *  Name:        cswindowlib.js
 *  Created:     2003-05-16 by sweber
 *  Description: collection of function to handle the window events "onload", "onunload", "onresize"
 *
 *  $Id: cswindowlib.js 153885 2010-03-24 17:54:55Z sweber $
 * </file>
 */

//--------------------------------------------------------------------
/**
 * This function sizes the iframe with the passed id so that the whole content is visible.
 * Is for example used in cluster handling and for (full) collection heads
 *
 * @param theFrame: object: iframe object that should be sized
 */

function sizeframe(theFrame)
{
  function findFooter() {
    var divs = document.getElementsByTagName("div");
    for (var i = divs.length - 1; i >= 0; i --) {
      if (divs[i].className == "DisplayAreaFooter") {
        return divs[i];
      }
    }
    return null;
  }

  if (theFrame.contentWindow.document.body.tagName == "FRAMESET" ||
      theFrame.hw_displayAsFrameSet) {
    var footer = findFooter();
    if (footer && document.getElementsByTagName("iframe").length == 1) {
      // if the current view contains just one iframe,
      // than the frameset should be sized
      // that the footer is visible without any scrollbars
      addToOnresize(function () {
            theFrame.style.height = (document.body.offsetHeight - footer.offsetHeight) + "px";
        })(); // return value is the function itself and will be executed once immediatly
    }
    else {
      theFrame.style.height = "100%";
    }
    var d_ = theFrame.ownerDocument;
    var w_ = d_.defaultView || d_.parentWindow;
    if (w_.frameElement) {
      w_.frameElement.hw_displayAsFrameSet = true;
    }
    return;
  }

  try {
    var doc = theFrame.contentWindow.document;
    var dummy = doc.createElement("div");
    doc.body.appendChild(dummy);

    var has_body_style = false;
    try { // maybe we get an access denied when an external style sheet is linked
      if (doc.styleSheets) {
        for (var i = 0; i < doc.styleSheets.length; i ++) {
          var rules = doc.styleSheets[i].cssRules || doc.styleSheets[i].rules; // one for FF and one for IE
          for (var j = 0; j < rules.length; j ++) {
            var a_rule = rules[j];
            if (a_rule.selectorText &&
                a_rule.selectorText.toLowerCase() == "body") {
              var dummy2 = doc.createElement("div");
  
              if (a_rule.style.margin && a_rule.style.margin.match(/[1-9]/)) { // has a value not zero
                has_body_style = true;
                dummy2.style.margin = a_rule.style.margin;
              }
              if (a_rule.style.borderWidth && a_rule.style.borderWidth.match(/[1-9]/)) {
                has_body_style = true;
                dummy2.style.border = a_rule.style.border;
              }
              if (a_rule.style.padding && a_rule.style.padding.match(/[1-9]/)) {
                has_body_style = true;
                dummy2.style.padding = a_rule.style.padding;
              }
  
              if (has_body_style) {
                dummy.appendChild(dummy2);
              }
            }
          }
        }
      }
    }
    catch (exc) {
    }

    var height1=dummy.offsetTop + (has_body_style ? dummy.offsetHeight : 0);
    var height2=doc.body.scrollHeight;
    if (height2<=300)
    {  // 300 is the initial height of iframe. When the size is less than this
       // the scroll information is no longer correct
      height2=height1;
    }

    var new_height = Math.max(height1, height2);
    theFrame.style.height = new_height + "px";
    doc.body.removeChild(dummy);
    doc.body.style.overflowX = "auto";
    doc.body.style.overflowY = "hidden";

    var test_height = Math.max(doc.body.scrollHeight, doc.body.parentNode.scrollHeight);
    if (test_height > new_height) {
      theFrame.style.height = test_height + "px";
    }
    return;
  }
  catch (e) {
  }
  
  try
  {
    var id = theFrame.id;
    var element=document.getElementById(id);
    if (navigator.appName.indexOf("Netscape")!=-1)
    {
      try
      {
        var h=eval(id+".document.body.offsetHeight");
      }
      catch(e)
      { // in this case [id].document is not defined, we assume the initial height
        h=300;
      }
      
      if (h!=300)
      {
        element.style.height = (h + 35) + "px";
      }
      else
      {
        element.style.height = (h+element.contentWindow.scrollMaxY+35) + "px";
      }
    }
    else
    {
      var element2=eval(id);
      element.style.height = element2.document.body.scrollHeight + "px";
    }
  }
  catch(e) {
  }
}

function hw_htmlEscape(string)
{
  if (typeof string != "string")
    string += "";
  return string.
    replace(/&/g, "&amp;").
    replace(/</g, "&lt;").
    replace(/>/g, "&gt;").
    replace(/\"/g, "&quot;").
    replace(/\'/g, "&#39;");
}

function hw_htmlUnescape(string)
{
  if (typeof string != "string")
    string += "";

  return string.replace(/&(lt|gt|quot|amp|#(\d{1,5})|#x([0-9a-fA-F]{1,4}));/g,
                        function (match, key, deccode, hexcode) {
                          if (hexcode) {
                            return String.fromCharCode(parseInt(hexcode, 16));
                          }
                          if (deccode) {
                            return String.fromCharCode(parseInt(deccode, 10));
                          }
                          if (key == "amp") {
                            return "&";
                          }
                          if (key == "quot") {
                            return "\"";
                          }
                          if (key == "gt") {
                            return ">";
                          }
                          if (key == "lt") {
                            return "<";
                          }
                          return match;
                        });
}

/* this function escapes ALL characters with an char code <=31 and char code >=127
 * by &#charcode;
 */
function hw_htmlEscapeStrong(string)
{
  if (typeof string != "string")
    string += "";
  string = hw_htmlEscape(string);
  
  var ret = "";
  var string_length = string.length;
  for (var i=0; i<string_length; i++)
  {
    var charcode = string.charCodeAt(i);
    if (charcode < 32 || charcode > 126)
    {
      ret += "&#x" + charcode.toString(16) + ";";
    }
    else
    {
      ret += string.charAt(i);
    }
  }
  return ret;
}


/**
 * This function escape a string for use in js strings.
 * mode 0: CR -> \r, LF -> \n, \ -> \\, ' -> \', " -> \"
 * mode 1: CR -> \r, LF -> \n, \ -> \\
 *
 * @param string: string: string to escape
 * @param mode: number | 0: mode for escapenig
 *
 * @return: string: escaped string
 */
function escapeString(string, mode)
{
  if (!string)
    return "";
  if (mode & 1) {
    var re = /([\r\n\\])/g;
  }
  else {
    var re = /([\"\'\r\n\\])/g;
  }
  return string.replace(re, function (theMatch, theChar) {
    switch (theChar) {
      case "\r": return "\\r";
      case "\n": return "\\n";
      default: return "\\" + theChar;
    }
  });
}

/**
 * This function unescape a string as complement to escapeString.
 * mode 0: \r -> CR, \n -> LF, \\ -> \, \' -> ', \" -> "
 * mode 1: \r -> CR, \n -> LF, \\ -> \
 *
 * @param string: string: string to unescape
 * @param mode: number | void (0): mode for unescapenig
 *
 * @return: string: unescaped string
 */
function unescapeString(string, mode)
{
  if (!string)
    return "";
  if (mode & 1) {
    var re = /\\([\\nr])/g;
  }
  else {
    var re = /\\([\"\'\\nr])/g;
  }
  return string.replace(re, function (theMatch, theChar) {
    switch (theChar) {
      case "r": return "\r";
      case "n": return "\n";
      default: return theChar;
    }
  });
}

/**
 * This function checks the given number and returns a number
 * greater equals 0.
 *
 * @param x: number: a number
 * @return: a number at least 0
 */
function hw_min0(x) {
  if (isNaN(x)) {
    return 0;
  }
  else {
    return Math.max(0, x - 0);
  }
}

/**
 * This function returns a px value derived from the given input
 * but at least 0.
 *
 * @param x: number: a number to be converted to `x`px
 * @return: string: the px value
 */
function hw_min0px(x) {
  return hw_min0(x) + "px";
}

if (!window.FILE_CSWINDOWLIBJS_INCLUDED) {

  window.HW_pageLoaded = false;

  CSWINDOWLIBJS_CATCHERRORS = false;
  // global onload array
  ONLOAD_ARRAY_FIRST = [];
  ONLOAD_ARRAY = [];
  ONLOAD_ARRAY_LAST = [];

  // global onunload array
  ONUNLOAD_ARRAY_FIRST = [];
  ONUNLOAD_ARRAY = [];
  ONUNLOAD_ARRAY_LAST = [];
  
  // global onresize array
  ONRESIZE_ARRAY_FIRST = [];
  ONRESIZE_ARRAY = [];
  ONRESIZE_ARRAY_LAST = [];
  
  function cswindowlib_doIt(execArray) {
    for (var i = 0; i < execArray.length; i ++) {
      var exec = execArray[i];

      if (CSWINDOWLIBJS_CATCHERRORS) {
        try {
          if (typeof exec == "string") {
            eval(exec);
          }
          else {
            exec();
          }
        }
        catch (e) {
          alert(e.name + ': ' + e.message);
        }
      }
      else {
        if (typeof exec == "string") {
          eval(exec);
        }
        else {
          exec();
        }
      }
    }
  }
  
  // overwrite the onload function
  Event.observe(window, "load", function () {
    cswindowlib_doIt(ONLOAD_ARRAY_FIRST);
    cswindowlib_doIt(ONLOAD_ARRAY);
    cswindowlib_doIt(ONLOAD_ARRAY_LAST);

    window.HW_pageLoaded = true;
    });
  
  // overwrite the onunload function
  Event.observe(window, "beforeunload", function () {
      Event.stopObserving(window, "beforeunload", arguments.callee);

      ONUNLOAD_ARRAY.unshift(window.onunload || function () {});
      
      window.onunload = function () {
        window.HW_pageLoaded = false;
        
        cswindowlib_doIt(ONUNLOAD_ARRAY_FIRST);
        cswindowlib_doIt(ONUNLOAD_ARRAY);
        cswindowlib_doIt(ONUNLOAD_ARRAY_LAST);
      };
    });
   
  // overwrite the onresize function
  Event.observe(window, "resize", function () {
    cswindowlib_doIt(ONRESIZE_ARRAY_FIRST);
    cswindowlib_doIt(ONRESIZE_ARRAY);
    cswindowlib_doIt(ONRESIZE_ARRAY_LAST);
    });
  
  //--------------------------------------------------------------------
  /**
   * handler for onload's
   *
   * @param aFuncStr: string: string to eval onload
   * @param aHint: enum string: enum that handles when the function will be called
   *                    addToOnload.FIRST : the function is called before functions with aHint NORMAL or LAST
   *                    addToOnload.NORMAL: the function is called after functions with aHint FIRST and
   *                              befor functions with aHint LAST
   *                    addToOnload.LAST  : the function is called after functions with aHint FIRST or NORMAL
   */
  function addToOnload(aFuncStr,aHint) {
    if (aFuncStr) {
      if (aHint && aHint==addToOnload.FIRST)
      {
        ONLOAD_ARRAY_FIRST[ONLOAD_ARRAY_FIRST.length] = aFuncStr;
      }
      else if (aHint && aHint==addToOnload.LAST)
      {
        ONLOAD_ARRAY_LAST[ONLOAD_ARRAY_LAST.length] = aFuncStr;
      }
      else
      {
        ONLOAD_ARRAY[ONLOAD_ARRAY.length] = aFuncStr;
      }
    }
    return aFuncStr;
  }
  
  //--------------------------------------------------------------------
  /**
   * handler for onunload's
   *
   * @param aFuncStr: string: string to eval onunload
   * @param aHint: enum string: enum that handles when the function will be called
   *                    addToOnunload.FIRST : the function is called before functions with aHint NORMAL or LAST
   *                    addToOnunload.NORMAL: the function is called after functions with aHint FIRST and
   *                              befor functions with aHint LAST
   *                    addToOnunload.LAST  : the function is called after functions with aHint FIRST or NORMAL
   */
  function addToOnunload(aFuncStr,aHint) {
    if (aFuncStr) {
      if (aHint && aHint==addToOnunload.FIRST)
      {
        ONUNLOAD_ARRAY_FIRST[ONUNLOAD_ARRAY_FIRST.length] = aFuncStr;
      }
      else if (aHint && aHint==addToOnunload.LAST)
      {
        ONUNLOAD_ARRAY_LAST[ONUNLOAD_ARRAY_LAST.length] = aFuncStr;
      }
      else
      {
        ONUNLOAD_ARRAY[ONUNLOAD_ARRAY.length] = aFuncStr;
      }
    }
    return aFuncStr;
  }
  
  //--------------------------------------------------------------------
  /**
   * handler for onresize's
   *
   * @param aFuncStr: string: string to eval onresize
   * @param aHint: enum string: enum that handles when the function will be called
   *                    addToOnresize.FIRST : the function is called before functions with aHint NORMAL or LAST
   *                    addToOnresize.NORMAL: the function is called after functions with aHint FIRST and
   *                              befor functions with aHint LAST
   *                    addToOnresize.LAST  : the function is called after functions with aHint FIRST or NORMAL
   */
  function addToOnresize(aFuncStr,aHint) {
    if (aFuncStr) {
      if (aHint && aHint==addToOnresize.FIRST)
      {
        ONRESIZE_ARRAY_FIRST[ONRESIZE_ARRAY_FIRST.length] = aFuncStr;
      }
      else if (aHint && aHint==addToOnresize.LAST)
      {
        ONRESIZE_ARRAY_LAST[ONRESIZE_ARRAY_LAST.length] = aFuncStr;
      }
      else
      {
        ONRESIZE_ARRAY[ONRESIZE_ARRAY.length] = aFuncStr;
      }
    }
    return aFuncStr;
  }

  //define constants to use for the addToxxx functions
  
  addToOnresize.FIRST = addToOnunload.FIRST = addToOnload.FIRST ="FIRST";
  addToOnresize.NORMAL = addToOnunload.NORMAL = addToOnload.NORMAL ="NORMAL";
  addToOnresize.LAST = addToOnunload.LAST = addToOnload.LAST ="LAST";
  
  //--------------------------------------------------------------------
  /**
   * Calling this function, an interval will be started checking the
   * opener window. When the opener window is closed, the current window
   * will be closed automatically.
   */
  function closeOnOpenerClose()
  {
    function checkOpener() {
      try {
        if (!window.opener || window.opener.closed) {
          window_close();
        }
      }
      catch (e) {
        window_close();
      }
    }
    setInterval(checkOpener, 250);
  }
}

addToOnload(adjustForHWE,addToOnload.FIRST);

window.FILE_CSWINDOWLIBJS_INCLUDED = true;

