/*
 * <copyright>
 *  Copyright (c) 2002 by Hyperwave AG
 * </copyright>
 *
 * <file>
 *  Name:        windowlib.js
 *  Created:     2002-04-07 by sweber
 *  Description: file for virtual folders html dialogs (vf compatibility)
 *               window communication functions
 *
 *  $Id: $
 * </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 /*top.*/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")
      { // set focus
        the_element.focus();
      }
      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, "~");
  }
  
  //--------------------------------------------------------------------
  /**
   * 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 = decodeUtf8(str.replace(/%20/g," "));
      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() {
    if (!window_debug.window) {
      window_debug.window = window.open("", "debug", "height=800,width=300,top=0,left=0,resizable=yes");
      window_debug.window.document.open();
      window_debug.window.document.writeln("<html><head>");
      window_debug.window.document.writeln("<title>DEBUG</title>");
      window_debug.window.document.writeln("</head>");
      window_debug.window.document.writeln("<body style='font-family: courier; font-size: 80%; margin: 0px;'>");
    }
    var style = "border-bottom: 1px dashed gray; padding-bottom: 1px;";
    if (window_debug.last_date != document.lastModified) {
      style += " border-top: 1px dashed red;";
    }
    window_debug.window.document.writeln("<DIV style='" + style + "'>");
    for (var i = 0; i < arguments.length; i ++) {
      var curr = arguments[i];
      var type = typeof curr;
      var is_string = type == "string";
  
      if (!is_string) {
        window_debug.window.document.write("<i title='" + type + "'>");
      }
      window_debug.window.document.write((arguments[i] + "").replace(/</g, "&lt;"));
      if (!is_string) {
        window_debug.window.document.write("</i>");
      }
    }
    window_debug.window.document.writeln("</DIV>");
    window_debug.window.scrollTo(0, 1000000);
    window_debug.window.focus();
    top.moveTo(310, 0);
    window_debug.last_date = document.lastModified;
  }
  
  /**
   * 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;
  
  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 v6.4/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;
  }
}
window.FILE_WINDOWLIBJS_INCLUDED = true;

