///////////////////////////////////////////////////////////////////////////
//         Copyright (C) 1999 Computer Associates International, Inc
// as an unpublished work. This notice does not imply unrestricted or public
// access to these materials which are a trade secret of Computer Associates
// International or its subsidiaries or affiliates (together referred to as
// CA), and which may not be reproduced, used, sold or
// transferred to any third party without CA's prior written consent.
//
//                         All Rights Reserved.
//
//                       RESTRICTED RIGHTS LEGEND
// Use, duplication, or disclosure by the Government is subject to
// restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in
// Technical Data and Computer Software clause at DFARS 252.227-7013.
////////////////////////////////////////////////////////////////////////////
// Module:  ahdmenus.js
// Created: 04/04/01
////////////////////////////////////////////////////////////////////////////
// Description:
//    Miscellaneous functions for menu support
//
//
////////////////////////////////////////////////////////////////////////////

// @(#)$Id: ahdmenus.js SDr12.1.5 2009/03/20 12:45:52 tooda01 Exp $

// setup_for_menubar()
//   Set the window.onload to create our menubar

var retry_count = 0;

function setup_for_menubar(name)
{
  //dLog("setup_for_menubar(" + name + ") [" + window.parent.name + "]");
  window.__menuBar = void(0);
  window.menubarFrame = void(0);
  var mbFrame;
  for ( var w = window;
          w != null && w != ahdframeset && w != w.parent;
            w = w.parent ) {
    if ( typeof w.frameElement == "object" &&
         w.frameElement != null &&
         w.frameElement.tagName == "IFRAME" &&
         ! w.name.match(/menuOK/) )
      break;
    mbFrame = w.parent.frames["menubar"];
    if ( typeof mbFrame == "object" && mbFrame != null &&
		 mbFrame.name == "menubar" )
      break;
  }
  if ( typeof mbFrame == "object" &&
       mbFrame != null ) {
    if ( typeof mbFrame.__menuBar != "object" ||
         mbFrame.__menuBar == null ) {
      retry_count++;
      if ( retry_count < 10 ) {
        var timeout = retry_count * 100;
        if ( typeof name == "string" )
          window.setTimeout("setup_for_menubar('" + name + "');", timeout);
        else
          window.setTimeout("setup_for_menubar();", timeout);
      }
    }
    else {
      // We only build menus if there is a menubar frame at our level.  This
      // avoids peculiar results for windows containing deferred tabs.
      window.menubarFrame = mbFrame;
      window.__menuBar = mbFrame.__menuBar;
      window.__menuBar.deferSetupCompletion = ahdtop.cstUsingScreenReader;
      window.menubarOnload = null;
	if ( typeof name != "string" ) {
       		 if ( typeof propFormName != "string" ) 
			name = ""; 
		else {
			name = propFormName;
			if ( typeof propFormName3 == "string" &&
				propFormName3.length > 0 )
				name += "_" + propFormName3;
		 }
        if ( typeof argID == "string" )
          name += "_" + argID;
        if ( typeof rptName != "undefined" &&
             typeof argSearchSqlClause == "string" &&
             argSearchSqlClause.length > 0 )
          name += "_" + argSearchSqlClause;
        if ( typeof cawf_procid == "string" && cawf_procid.length > 0 )
          name += "_" + cawf_procid;
        // Ensure menu is refreshed after change order attach/detach
        if ( typeof argChange == "string" ) {
          if ( ! argChange.match(/^\s*$/) )
            name += "_attchg";
        }
        if ( typeof argActive == "string" &&
             ( typeof cfgNX_EDIT_INACTIVE != "string" ||
                cfgNX_EDIT_INACTIVE != "no" ) )
          name += "_" + argActive;
      }
      window.menubarName = name;

      // We build the menubar right away to get the hotkeys right

      find_build_menubar();

      // We also set an onload in case the user presses the Back button
     
      if ( typeof window.onload != "undefined" )
        window.menubarOnload = window.onload;
      window.onload = find_build_menubar_onload;
    }
  }
}

function evaluate_menubar_func(win, func_name, parm_str, code_str)
{
    eval("window." + func_name + " = function (" + parm_str + ") {" + code_str + "}");
    var f = eval("window." + func_name);
    f(window, win);
}

// find_build_menubar()
//   Invoked after loading of a form with a menubar.  Searches the
//   parent and opener windows for a build_memubar() function and runs it.

function find_build_menubar()
{
  //dLog("find_build_menubar() menubarName(" + menubarName + ") __menubarName(" + __menuBar.name + ")" );
  if ( menubarName != "" &&
       menubarName == __menuBar.name ) {
     // We haveve already built the menubar - just reregister its action
     // keys for the new window using it
     __menuBar.reregisterActionKeys(window);
  }
  else {
    var w = window;
    var top_frame = ahdframeset;
    while ( 1 ) {
      if ( typeof w.build_menubar != "undefined" && typeof w.build_menubar != "unknown" ) {
	var found = 0;
        if ( w.menubarName != menubarName ||
             w.menubarName == "" ||
             w == window ) { 
          //dLog("Calling build_menubar in " + w.name);
	  if (w != window &&
	      ahdframeset != ahdtop)	
	  {
	    // Instead of calling the menubar function 
	    // remotely, we create the function with 
	    // the function string and eval it locally, 
	    // so we can avoid some IE memory leak. 
	    var func_str = w.build_menubar.toString();
	    if (func_str.match(/^function *([^ \(]+) *\((.*)\) *[^\{]+\{([^$]+)\}$/))
	    {
		evaluate_menubar_func(w, RegExp.$1, RegExp.$2, RegExp.$3);
		found = 1;
	    }
	    else 
	    // If the function found is not original (it doesn't have 
	    // function name), we can't use it, because only in the 
	    // window where the original function is located has all 
	    // menu functions.   
	    if (func_str.match(/^function *\((.*)\) *[^\{]+\{([^$]+)\}$/))
	    {
		// The window holding the original menu functions should
		// be saved in the menubar object of the window found. Try
		// to get it first.
		if (typeof w.__menuBar == "object" && 
		    w.__menuBar != null &&
		    typeof w.__menuBar.definingWindow == "object" &&
		    w.__menuBar.definingWindow != null)
		{
		    w = w.__menuBar.definingWindow;
		    continue;
		}    
		// Cannot find a valid window object. Search in next 
		// window. 
		found = 2;
	    }
	  }
	  if (!found)
	    w.build_menubar(window);
        }
	if (found != 2)
	{
	    enableBackToList();
	    return;
	}
      }

      try 
      {
      if ( w != top_frame &&
           typeof w.parent == "object" && w != w.parent )
        w = w.parent;
      else if ( w != ahdtop &&
                typeof w.opener == "object" && w.opener != null && 
		!w.opener.closed ) {
	var cur_w = w;
        w = w.opener;
	// The original tab page could be hidden in the main 
	// window. Check for the saved ahdframe window. 
	if (w == ahdtop &&
	    typeof cur_w.ahdframeset.menubar_ahdframe != "undefined" &&
	    !cur_w.ahdframeset.menubar_ahdframe.closed)
	{
	    w = cur_w.ahdframeset.menubar_ahdframe; 
	}
	else 
	// If it's a top window, check from its 
	// ahdframe window.
	if (w == w.ahdframeset)
	    w = w.ahdframe; 
        top_frame = w.ahdframeset;
      }
      else
      // In case the opener is closed, 
      // we default to ahdtop.ahdframe.
      if ((w != ahdtop) &&
	  (typeof ahdtop == "object") &&
	  (ahdtop != null) &&
	  !ahdtop.closed) 
      {
	w = ahdtop.ahdframe;
	top_frame = ahdtop.ahdframeset;
      }
      else 
	break;
    } catch(e) { break; }
    }
    //dLog("Internal error - can't find build_menubar function for window " + window.name);
  }
   

  // Enable the Back to List button if appropriate
 
  enableBackToList();
}

// enableBackToList();
// Enable the Back to List button if appropriate
// It will be appropriate if we are in Avoid Popups mode, have at
// least one list URL saved, and are not showing an edit form

function enableBackToList() {
  if ( ahdtop.cstReducePopups &&
       ahdtop == ahdframeset ) {
    var lastUrlIndex = -1;
    var urlArray = menubarFrame.listUrlArray;
    if ( typeof urlArray == "object" &&
         urlArray.length > 0 &&
         ( typeof _dtl != "object" ||
           typeof _dtl.edit != "boolean" ||
           ! _dtl.edit ) ) {
      lastUrlIndex = urlArray.length - 1;
      if ( urlArray[lastUrlIndex] == window.document.URL )
        lastUrlIndex--;
    }
    if ( lastUrlIndex < 0 )
      menubarFrame.ImgBtnDisableButton("btnbackToList");
    else {
      menubarFrame.ImgBtnEnableButton("btnbackToList");
      if ( document.URL.indexOf("OP=CANCEL") != -1 )
        menubarFrame.backToList();
    }
  }
}

// backToList()
//   Redisplay the most recent list form in the main window
function backToList()
{
  if ( ahdtop == ahdframeset &&
       typeof listUrlArray == "object" &&
       listUrlArray.length > 0 ) {
     var lastUrlIndex = listUrlArray.length - 1;
     var url = listUrlArray[lastUrlIndex];
     if ( url == ahdframeset.ahdframe.document.URL ) {
       listUrlArray[lastUrlIndex] = void(0);
       listUrlArray.length = lastUrlIndex;
       if ( --lastUrlIndex < 0 ) {
         ImgBtnDisableButton("btnbackToList");
         return;
       }
       url = listUrlArray[lastUrlIndex];
     }
     listUrlArray[lastUrlIndex] = void(0);
     listUrlArray.length = lastUrlIndex;
     ahdframeset.ahdframe.location.replace(url);  
   }
}

// find_build_menubar_onload()
//    Call find_build_menubar() and any outstanding onload function
function find_build_menubar_onload()
{
  find_build_menubar();
  if ( typeof window.menubarOnload == "function" ) {
    // Temporarily set onload to null to prevent recursive call
    window.saveMenubarOnload = window.menubarOnload;
    window.menubarOnload = null;
    window.saveMenubarOnload();
    window.menubarOnload = window.saveMenubarOnload;
  }
}

// addMenuItem()
//   Add an item to the menubar itself.  This function calls the
//   siteMenuMod() function to determine whether or not to add the item.
var menuActive;
var menuID;
var menuName;
var menuCount = 0;
var submenuCount = 0;

function addMenuItem(itemName, callExit)
{
    menuActive = true;
    var menuNameCurr = itemName;

    if ( typeof callExit == "boolean" && callExit == true )
    {
        // Do not change menuName prior to this block,         
        // we need to operate on the previous menu here 
	if ( submenuCount > 0 )
	    // Allow site to add items to previous menu
	    siteMenuitemAdd(menuName);
		
	// Allow site to modify this menu
        menuName = menuNameCurr;
	var rc = siteMenuMod(menuName);
    
	if ( typeof rc == "boolean" ||
	     typeof rc == "int" )
	    menuActive = rc;
	else if ( typeof rc == "string" )
	{
	    if ( rc.length == 0 )
		menuActive = false;
	    else 
		menuNameCurr = rc;
	}
    }

    menuName = menuNameCurr; 
 
    if ( menuActive )
    {
	menuCount++;
	menuID = "mn" + menuCount;
      
	if ( _browser.isNS == true )
	    NS_AddMenuItem(menuID, menuName);
	else 
	    Menu_Lib_AddMenuItem(menuID, menuName, "", "");
    }
  
    submenuCount = 0;
}

// addSubMenuItem()
//   Add an item to a dropdown menu
function addSubMenuItem(itemName, script, callExit)
{
    addSubMenuItem_internal(itemName,
			    "ahdtop." + script,
			    "cai_main",
			    callExit);
}

function addSubMenuItem_internal(itemName, script, target, callExit)
{
    if ( menuActive )
    {
	var submenuActive = true;
	var submenuName = itemName;
	if ( typeof callExit == "boolean" && callExit )
	{
	    // Allow site to modify this submenu
	    var rc = siteMenuitemMod(menuName, submenuName);
	    if ( typeof rc == "boolean" |
		 typeof rc == "int" )
		submenuActive = rc;
	    else if ( typeof rc == "string" )
	    {
		if ( rc.length == 0 )
		    submenuActive = false;
		else 
		    submenuName = rc;
	    }
	}
	if ( submenuActive )
	{
	    submenuCount++;
	    var submenuID = menuID + "_" + submenuCount;
	    if ( _browser.isNS == true )
		NS_AddSubMenuItem(submenuID,submenuName,script,target);
	    else 
		Menu_Lib_AddSubMenuItem(submenuID,submenuName,"",script,target);
	}
    }
}

// endMenu()
//    Complete the menubar
function EndMenu()
{
    if ( submenuCount > 0 )
	// Allow site to add items to previous menu
	siteMenuitemAdd(menuName);
  
    //Allow site to end more menubar items
    siteMenuAdd();
    if ( _browser.isNS == true )
	NS_EndMenu();
    else 
	Add_Input_Field();
    submenuCount = 0;
}

// Netscape menu implementation
var submenu_x_posn = 0;
var submenu_y_posn = 0;
function NS_AddMenuItem(menuID, menuName)
{
    if ( menuCount == 1 )
	document.write("<TABLE class='divMenuBar' HEIGHT=30 border=0 cellspacing=0 cellpadding=0><TR><TD>");
    if ( submenuCount > 0 )
    {
	if ( _browser.supportsLayers == true )
	  document.write("</LAYER>");
	else
	  document.write("</DIV>");
	submenuCount = 0;
    }
   
    document.write("<A CLASS='clsMenuBarItem' HREF=\"javascript:void(0)\" " +
		   "onMouseOver=\"NS_ShowMenu('Menu" + menuCount +
		   "')\">&nbsp;" + menuName + "&nbsp;</A>");
    submenu_x_posn = document.links[document.links.length-1].x;
    submenu_y_posn = document.links[document.links.length-1].y+24;
    document.write("<SPAN class=\"clsSeparator\">|</SPAN>");
}

function NS_AddSubMenuItem(menuID, menuName, script, target)
{
    if ( submenuCount == 1 )
	if ( _browser.supportsLayers == true )
		document.write("<LAYER ID=Menu" + menuCount +
		       " left='" + submenu_x_posn +
		       "' top='" + submenu_y_posn + "' width='200'" +
		       " visibility=hidden bgColor=#9CC2E4" +
		       " onMouseOut=\"NS_ShowMenu()\"" +
		       " z-index=99>");
	else
		document.write("<DIV ID=Menu" + menuCount +
		       " left='" + submenu_x_posn +
		       "' top='" + submenu_y_posn + "' width='200'" +
		       " visibility=hidden bgColor=#9CC2E4" +
		       " onMouseOut=\"NS_ShowMenu()\"" +
		       " z-index=99>");
    document.write("<A CLASS='clsSubMenuItem' HREF=\"javascript:" + script + "\"");
    if (target != "")
	document.write(" target=" + target);

    document.write(">&nbsp;" + menuName + "</A>");
}

function NS_ShowMenu(tgt)
{
    var i;
    var filter_timeout_called = false;
    for ( i = 0; i < document.layers.length; i++ )
    {
	var curr = document.layers[i];
	if (curr.name.indexOf("Menu") < 0)
	    continue;

	if ( curr.name == tgt )
	{
	    curr.visibility = "show";
	    if ( typeof searchFilterSetTimeout == "function" )
	    {
		searchFilterSetTimeout();
		filter_timeout_called = true;
	    }
	}	
	else
	{
	    curr.visibility = "hidden";
	    if ( ! filter_timeout_called )
	    {
		if ( typeof searchFilterClearTimeout == "function" )
		    searchFilterClearTimeout();
		filter_timeout_called = true;
	    }
	}	
    }
}

function NS_EndMenu()
{
    if ( submenuCount > 0 )
    {
	if ( _browser.supportsLayers == true )
	  document.write("</LAYER>");
	else
	  document.write("</DIV>");
	submenuCount = 0;
    }
    if ( menuCount > 0 )
    {
	document.write("</TD><TD WIDTH=90%>&nbsp;</TD></TR></TABLE>");
    }
}

var win_width;
var win_height;

function NS_next()
{
    var flds = NS_find_form();
}

function NS_find_form()
{
    // Can not give a name to layer (DIV) becuase  
    // somehow the name can mess up the alignment, 
    // so use the following way to get the correct
    // layer.
    var flds;
    var layers = document.layers;
    var len = layers.length;
    var i;
    for (i = 0; i < len; i++)
    {
	if (layers[i].document.forms["menu_flds"])
	{
	    flds = layers[i].document.forms["menu_flds"];
	    break;
	}
    }
    return flds;
}

function do_openDetail(factory, num, text) 
{
	var attr_name;
    if ((factory == "cr") || (factory == "iss"))
	attr_name = "ref_num";
    else if (factory == "chg")
	attr_name = "chg_ref_num";
    else if ( factory.match(/^(\w+)\.(\w+)$/) ) {
        factory = RegExp.$1;
        attr_name = RegExp.$2;
        if ( factory == "pb" ) {
           if ( attr_name == "id" )
           {
              profile_browser("cnt:" + num, text);
           }   
           else
              profile_browser("cnt:" + attr_name + ":" + num, text,1);
           return;
        } 
	if ( factory == "gpb" ) {
		gpb_pop_global_detail(attr_name, num);
		return;
	}
    }
    else 
    {
	alertmsg("Please_select_detail_type"); // Please select detail type
	return;
    }

    if ( attr_name == "ref_num" ||
         attr_name == "chg_ref_num" ) {
       var ahdwin = ahdtop.detailForms[factory + num];
       if ( typeof ahdwin == "object" &&
            typeof ahdwin.name == "string" &&
            typeof ahdwin.closed == "boolean" &&
            ! ahdwin.closed ) {
          ahdwin.focus()
          if ( typeof ahdframe._dtl == "object" )
             ahdframe._dtl.firstField.focus();
          return;
       }
    }
  
    var query_str = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator() +
	"+OP=GET_DOB+PERSID=" +
        nx_escape(factory + ":" + attr_name + ":" + num) +
        "+FACTORY_TEXT=" + nx_escape(text) +
        "+KEEP.IsPopUp=1" +
        "+KEEP.backfill_form=" + nx_escape("javascript:replaceList") +
        "+KEEP.backfill_field=persistent_id" +
        "+KEEP.Is3FieldContact=0";
	if (cfgGlobalSD!="") {
		query_str+="+GLOBALSD_ACTIVE_ZONE="+ahdtop.gpb_active_zone;
	}
	if(ahdtop.propIsITIL && factory=="cr") {
		query_str+="+GLOBAL=1";
	}
        
    if(factory == "KD")
	{	
		OpenDocumentViewer(num, 2);
	}	
	else
	{
		popupWithURL(query_str);
	}	
}

function replaceList(persid)
{
   var url = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator() +
	     "+OP=GET_DOB+PERSID=" + nx_escape(persid);
   replace_page(url);
}

function upd_main_window(form)
{
	if ( ahdframeset.name != "AHDtop" ) 
	    ahdtop.focus();
    
	var url = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator();
       
	if ( form.match(/\.htmpl/) )
	    url +='+OP=JUST_GRONK_IT+HTMPL=' + form;
	else
	    url += '+OP=' + form;
    
	for ( var i = 1; i < arguments.length; i++ )
	    url += "+" + arguments[i];
	ahdtop.document.location.href = url;
}

// upd_frame()
//    Load a form into the main (content) frame
function upd_frame(form)
{
    var ahdtop = get_ahdtop(true);
    if ( typeof ahdtop == "object" )
    {
    if ( window != ahdframe ) 
	    ahdtop.focus();

	var url = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator();
	if ( form.match(/\.htmpl/) )
	    url +='+OP=JUST_GRONK_IT+HTMPL=' + form;
	else
	    url += '+OP=' + form;
      
	for ( var i = 1; i < arguments.length; i++ )
	    url += "+" + nx_escape(arguments[i]).replace(/%3D/i,"=");
	ahdtop.ahdframe.document.location.href = url;
    }
}

// upd_specific_frame()
//    Load a form into a specific main form frame
function upd_specific_frame(toolbarTab, form)
{
	if (ahdtop.cstReducePopups && typeof _dtl != "undefined" && _dtl.edit)
	{
		alertmsg("Please_save_or_cancel_to_proceed");
		return;
	}
  ahdtop.focus();
  if (typeof ahdtop.toolbar == "object" && typeof ahdtop.toolbar.mainframe == "function")
    var tgt = ahdtop.toolbar.mainframe(toolbarTab);
  else 	
    var tgt = ahdtop.ahdframe;
  if ( tgt != null ) {
     var url = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator();
     if ( form.match(/\.htmpl/) )
     {
        if (form.match(/search_(cr|chg|iss|in|pr)\.htmpl/) && ahdtop.cfgInitListSearch == "Yes")
        {            
            var fac = RegExp.$1;
            url += "+OP=SEARCH+FACTORY="+fac+"+QBE.EQ.active=1"+"+QBE.EQ.assignee="+ahdtop.cstID;
	    if (ahdtop.propIsITIL && (form == "search_cr.htmpl"))
		url += "+ADDITIONAL_WHERE=" + nx_escape("( type = 'R' OR type = '' OR type IS NULL )");    
        }
        else if (form == "list_cr_kt.htmpl")
        {
            url += "+OP=SEARCH+FACTORY=cr+HTMPL=list_cr_kt.htmpl";			
        }
        else if (form == "list_iss_kt.htmpl")
        {
            url += "+OP=SEARCH+FACTORY=iss+HTMPL=list_iss_kt.htmpl";			
        }
        else
	{
            url +='+OP=JUST_GRONK_IT+HTMPL=' + form;
	    if (ahdtop.propIsITIL && (form == "search_cr.htmpl"))
		url += "+DEFAULT_TO_CR=1";
	}
     }
     else
         url += '+OP=' + form;
   
     for ( var i = 2; i < arguments.length; i++ )
         url += "+" + nx_escape(arguments[i]).replace(/%3D/i,"=");

     tgt.document.location.href = url;
    }
}

// upd_workframe()
//    Load something (normally JavaScript) into the workframe.
//    This could be the workframe in a popup window.
function upd_workframe(form)
{
    if ( typeof ahdframeset.workframe == "object" )
    {
	var url = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator();
	if ( form.match(/\.htmpl/) )
	    url +='+OP=JUST_GRONK_IT+HTMPL=' + form;
	else
	    url += '+OP=' + form;
      
	for ( var i = 1; i < arguments.length; i++ )
	    url += "+" + nx_escape(arguments[i]).replace(/%3D/i,"=");

	if ((ahdframeset.name == "AHDtop") &&
	    (ahdframeset.frames.length > 1))
	    load_workframe(url, 0, "UPD_WORKFRAME");
	else
	if (typeof ahdframeset.workframe == "object" &&
	    ahdframeset.workframe != null) 
	    display_new_page(url,ahdframeset.workframe);
    }
}

function invoke_sd_url(servername, jobcontainer)
{
    var w, url;
	if (servername == "ERROR" && jobcontainer == "ERROR")
	{
		url = ahdtop.cfgNX_SDURL+"html/web_dm_login.html?USERID=";
		w = window.open(url,"","width=850,height=600,location");
		next_workframe("UPD_WORKFRAME");
		check_popup_blocker(w);
		return;
	}

	url = ahdtop.cfgNX_SDURL + 
					"servlet/iDispatcher?FILE=/html/web_dm_login_context.html.tpl&CALLINGAPP=SERVICEDESK&APPLICATION=SD&SERVER=" +
					servername + 
					"&NODEID=SDJobContainer@" + 
					servername +
					"!0!" + 
					jobcontainer +
					"&USERID="; 

   w = window.open(url, "", "width=800,height=600,scrollbars,resizable,menubar,location,status,toolbar");
   next_workframe("UPD_WORKFRAME");   
   check_popup_blocker(w);
}


function invoke_uam_url(policy_type, server_name, object_domain_id, object_id, domain_id)
{
    var w, url;
	if (policy_type == "ERROR")
	{
	    url = ahdtop.cfgNX_UAMURL+"html/web_dm_login.html?USERID=";
	    w = window.open(url,"","width=850,height=600,location");

	    next_workframe("UPD_WORKFRAME");
	    check_popup_blocker(w);
	    return;
	}
	var policyType = "";
	var minus_1 = "";
	var delim = "!";
	if (policy_type == "10")
	{
		policyType = "AmoEventPolicy";
		minus_1 = "-1!";
		delim = "~";
	}
	else if (policy_type == "11")
	{
		policyType = "AmoPolicy";
	}

	url = ahdtop.cfgNX_UAMURL + 
					"servlet/iDispatcher?FILE=/html/web_dm_login_context.html.tpl&CALLINGAPP=SERVICEDESK&APPLICATION=AM&SERVER=" +
					server_name + 
					"&NODEID=" + 
					policyType + 
					"@" + 
					object_domain_id + 
					"!" +
					minus_1 + 
					object_id +
					delim +
					domain_id + 
					"&USERID="; 

   w = window.open(url, "", "width=800,height=600,scrollbars,resizable,menubar,location,status,toolbar");
   next_workframe("UPD_WORKFRAME");
   check_popup_blocker(w);
}


function invoke_uam_asset(server_name, unit_domain_id, unit_id, type, domain_id)
{
    var w, url;
	if (server_name == "ERROR")
	{
	    url = ahdtop.cfgNX_UAMURL+"html/web_dm_login.html?USERID=";
	    w = window.open(url,"","width=850,height=600,location");
	    next_workframe("UPD_WORKFRAME");
	    check_popup_blocker(w);
	    return;
	}

	url = ahdtop.cfgNX_UAMURL + 
					"servlet/iDispatcher?FILE=/html/web_dm_login_context.html.tpl&CALLINGAPP=SERVICEDESK&APPLICATION=AM&SERVER=" +
					server_name + 
					"&NODEID=AmoUnitComputer@" + 
					unit_domain_id + 
					"!" +
					unit_id +
					"!" +
					type + 
					"~" + 
					domain_id + 
					"&USERID=";

   w = window.open(url, "", "width=800,height=600,scrollbars,resizable,menubar,location,status,toolbar");
   next_workframe("UPD_WORKFRAME");
   check_popup_blocker(w);
}

// post_external()
//    Submit a form that invokes an external program with a BOPSID
// SDT 24122 - be sure to call next_workframe() before exit.
function post_external(form_name, bopsid)
{
   if ( form_name == "no" ) {
      popupCiWindow(ahdtop.ciSearchWindow, "BOPSID="+bopsid, "", 1);
      next_workframe("UPD_WORKFRAME");
      return;
   }
   
   // SDT 20818 Warning:
   // NS7 thinks content is a window, even though
   // it really should not be there...so check for cai_main first.
   var f = void(0);
   // PWC - 02/27/04 - Replace xxx.content and xxx.cai_main with ahdframe
   //if ( typeof parent.cai_main == "object" )
   //   f = parent.cai_main.document.forms[form_name];
   //if ( typeof f != "object" || f == null ) {
   //   if ( typeof parent.content == "object" )
   //       f = parent.content.document.forms[form_name];
   if ( typeof ahdframe == "object" )
	  f = ahdframe.document.forms[form_name];
   if ( typeof f != "object" || f == null ) {      
		if ( typeof parent.gobtn == "object" )
		f = parent.gobtn.document.forms[form_name];
		if ( typeof f != "object" || f == null ) {
		next_workframe("UPD_WORKFRAME");
		alertmsg("182",form_name);
					// Cannot find form %1 to post to external interface
		return;
		}
   }
   if ( typeof f.target == "string" &&
        f.target.length > 0 )
   {
      var w;
      if (_browser.isIE && _browser.isMAC)
      {
	var features="menubar=1";
	features=",location=1";
	features+=",toolbar=1";
	features+=",status=1";
	features+=",scrollbars=yes";
	w = window.open(cfgCAISD + "/html/empty.html", "", features);
      }
      else 
      {
	w = window.open(cfgCAISD + "/html/empty.html", "");
      }
      if (!check_popup_blocker(w))
	return;
      w.name = f.target;
      w.focus();
   }
   if ( f.BOPSID.type == "hidden" ||
        f.BOPSID.type == "text" )
      f.BOPSID.value = bopsid;
   f.submit();
   next_workframe("UPD_WORKFRAME");
}

function customize_scoreboard()
{
    var ahdtop = get_ahdtop(true);
    if ( typeof ahdtop == "object" )
    {
		// PWC - 03/01/04 _ Replace reference to content with ahdframeset
		//if ( window.name != "content" ) 
		if ( ahdframeset != ahdtop )
			ahdtop.focus();
		if ("function" == typeof ahdtop.scoreboard.maintain_tree) {
			 ahdtop.scoreboard.maintain_tree("cnt:" + cstID);
		} else {
			 alertmsg("Please_wait_until_the_scoreboa");
		}
    }
}

// img_button()
//    Create a button with an image
function img_button(btn_id, btn_name, btn_width, operation, alt)
{
    document.writeln(img_button_text(btn_id, btn_name, btn_width, operation, alt));
}

function img_button_text(btn_id, btn_name, btn_width, operation, alt)
{
    var up = cfgCAISD +  "/img/b_" + btn_name + "_up.gif";
    var down = cfgCAISD +  "/img/b_" + btn_name + "_down.gif";
    var func = operation;
    if ( func.indexOf("(") == -1 )
	func = "\"upd_frame('" + func + "'); return false;\"";
    else if ( func.substr(0,1) != '"' &&
	      func.substr(0,1) != "'" )
	func = '"' + func + ';return false;"';
    else 
	func = funcWithQuotes(func);

    var temp_str = "<A ID=\"" + btn_id + "\" " +
	"HREF=\"javascript:void(0)\" ";

    temp_str += "onClick=" + func + ">" + 
	"<IMG BORDER=0 SRC='" + up + "' " + 
	"WIDTH=\"" + btn_width + "\" HEIGHT=\"23\" " +
	"onMouseOver=\"window.status='';return true;\"" +
	"onMouseDown=\"this.src='" + down + "';return true;\" " +
	"onMouseOut=\"this.src='" + up + "';return true;\" " +
	"onMouseUp=\"this.src='" + up + "';return true;\"></A>";

    // See if this is the default button

    if ( typeof default_button_name != "string" )
       default_button_name = "btn001";
    if ( btn_id == default_button_name &&
         typeof imgBtnDefault != "object" ) {
       imgBtnDefault = new Object();
       imgBtnDefault.enabled = true;
       imgBtnDefault.func = func.substr(1,func.length-14);
    }

    return temp_str;
}

function funcWithQuotes(func)
{
    
    var pos = 0;
    var isSQ = 1;
    var pos_s = func.lastIndexOf("'");
    var pos_d = func.lastIndexOf("\"");
    if ((pos_s >= 0) && (pos_d >= 0))
    {
	if (pos_s > pos_d)
	    pos = pos_s;
	else 
	{
	    isSQ = 0;
	    pos = pos_d;
	}
    }
    else if (pos_s >= 0)
	pos = pos_s;
    else
    {
	isSQ = 0;
	pos = pos_d;
    }

    func = func.slice(0, pos) + ";return false;";
    if (isSQ)
	func += "'";
    else 
	func += "\"";

    return func;
}

//  pdm_submit()
//    Submit a form and operation in the OP field
function pdm_submit(form_name, operation, action, replace)
{
    if ( action_in_progress() && ahdframe.currentAction != 0 )
       return;
    if ( typeof ahdtop == "object" &&
         typeof ahdtop.wspReplaceAllDone == "boolean" &&
         ahdtop.wspReplaceAllDone &&
         typeof operation == "string" &&
         operation != "UPDATE" ) {
      alertmsg("Operation_suppressed_in_WSP_pr");
      return; // WSP readonly preview session
    }
    if ( typeof action == "number" )
       set_action_in_progress(action);
    var f = window.document.forms[form_name];
    // For 55 form
    var set_id, htmpl;
    if ( typeof f.elements["HTMPL"] == "object" )
       htmpl = f.elements["HTMPL"];
    if ( typeof f.elements["SET.id"] == "object" )
       set_id = f.elements["SET.id"];
      

    var is_55_analyst = 0;
    if ( (typeof propFormRelease == "undefined" || propFormRelease < 60) &&
         (typeof cfgUserType == "undefined" || cfgUserType == "analyst") )
        is_55_analyst = 1;
    
    // For analyst only.    
    if (is_55_analyst && typeof htmpl == "undefined" && typeof set_id == "object")
    {
	if (propFormName == "detail_alg_edit.htmpl" || 
	    propFormName == "xfer_esc_cr.htmpl" || 
	    propFormName == "request_status_change.htmpl" ||
	    propFormName == "cr_attach_chg.htmpl" ||
	    propFormName == "cr_detach_chg.htmpl" ) 
	{
	    set_id.name = "INPUT_FIELDS_TO_PARSE";
	    ahdframeset.top_splash.next_persid = "cr:" + set_id.value;
	    set_id.value = "HTMPL=show_main_detail.htmpl&SET.id=" + set_id.value;
	}
	if (propFormName == "detail_chgalg_edit.htmpl" || 
	    propFormName == "xfer_esc_chg.htmpl" || 
	    propFormName == "order_status_change.htmpl")
	{
	    set_id.name = "INPUT_FIELDS_TO_PARSE";
	    ahdframeset.top_splash.next_persid = "chg:" + set_id.value;
	    set_id.value = "HTMPL=show_main_detail.htmpl&SET.id=" + set_id.value;
	}
	if (propFormName == "nf.htmpl")
	{
	    var factory = f.elements["FACTORY"];
	    if (typeof factory != "undefined")
	    {
		set_id.name = "INPUT_FIELDS_TO_PARSE";
		ahdframeset.top_splash.next_persid = factory.value + ":" + set_id.value;
		set_id.value = "HTMPL=show_main_detail.htmpl&SET.id=" + set_id.value;
	    }
	}
    }
    if (typeof f.elements["use_template"] == "object" && 
	f.elements["use_template"].value == "1" && 
	f.onsubmit == null)
    {
    set_action_in_progress(ACTN_SAVE);
    }
    if ( typeof f != "object" )
	   alertmsg("Operation_%1_ignored_-_can't_f", operation, form_name);
             // Operation %1 ignored - can't find form %2
	    else
	    {
		if ( typeof operation == "string" &&
		     operation.length > 0 )
		{
		    if ( typeof f.OP == "object" )
			f.OP.value = operation;
		    else
	        alertmsg("Form_operation_%1_ignored_-_fo", operation, f.name);
                  // Form operation %1 ignored - form %2 has no OP field
		}
                if ( typeof divLoadForm == "function" )
                   divLoadForm(f);
        if ( typeof f.onsubmit == "undefined" ||
		     f.onsubmit == null ||
		     f.onsubmit() )
			if (typeof replace == "boolean" && replace)
			{
			    if ( _browser.isIE )
			    {
				window.location.replace(""); 
				f.submit();
			    }
			    else 
				replace_location_with_forms(f);
			}
			else
			    f.submit();
	    }
}

//  pdm_reset()
//    Reset all forms when Reset button is pressed
function pdm_reset()
{
	for (var i = 0; i < window.document.forms.length; i++) {
		window.document.forms[i].reset();
	}
}

function browseWithURL(url)
{
    display_new_page(url);
}

// view_scoreboard()
//    Add the scoreboard to a form popped up from another application
function view_scoreboard()
{
   var ahdtop = get_ahdtop();
   if ( typeof ahdtop != "object" ||
        ahdtop.propInitialPopup != "1" )
       return;
   if ( confirm(msgtext("Do_you_want_restart_your_sessi")) ) {
      ahdtop.close_all_windows();
      var url = cfgCgi +
                "?SID=" + cfgSID +
                "+FID=" + fid_generator() + 
                "+OP=MENU";

      ahdtop.onunload = null;
      // To avoid logout, set the logout flag.
      if (typeof ahdtop.AHD_logout_requested != "undefined")
	ahdtop.AHD_logout_requested = true; 
      ahdtop.document.location.href = url;
   }
}


// doesContain()
//    Simulate the IE contains function in NS6
function doesContain(parent, child)
{
   var elems = parent.getElementsByTagName(child.tagName);
   for (var e = 0; e < elems.length; e++) {
      if (child == elems[e])
      	 return true;
   }
   return false;	      	 
}

/////////////////////////////////////////////////////////////////
//
//	Call this to update your KT form values with the very latest
//	ticket info before invoking KT.  This is really only needed when the ticket
//	is in an editable state and thus the values can be monkeyed with before launching KT.
//
//	from_window: a window object where the source elements are
//	from_fname: name of the source form
//	to_fname:	name of the target form
//	attr_arr:	an array of arrays.  Each sub array must have two
//				elements, the first is the name of the element value to copy,
//				the second is the element target.
//				Use SET or KET prefixes for the target elements.
//				Right now the target must be a simple input element with a 'value' member
//		e.g.:
//		attr_arr = [["KEY.category", "CATEGORY"], ["SET.affected_resource", "SD_ASSET_ID"]]
//
//////////////////////////////////////////////////////////////////
function ci_update_fields(from_window, from_fname, to_fname, attr_arr)
{

    if ( action_in_progress() && ahdframe.currentAction != 0 )
       return;
       
	// SDT 24347 - For older forms, the appropriate KT <form> may
	//	not be defined.  For 6.0+, we still check in case this op
	//	is called before the form finishes loading.
	if (typeof document.forms[to_fname] ==  "undefined" && 
		(typeof propFormRelease == "undefined" || propFormRelease < 60))
    {
		alertmsg("The_ci_search_form_is_missing.", "ci_search.htmpl", propFormName);  
		return;
    }
    
    // Only need to copy values from editable tickets
    // Pre 6.0 doesn't understand _dtl.
    if (typeof propFormRelease == "number" && propFormRelease >= 60 &&
		(typeof from_window == "undefined" || typeof from_window._dtl == "undefined" || !from_window._dtl.edit)) 
	{
		return;
	}

	
	// Get the source and target forms
	var fromForm, toForm;
	toForm = document.forms[to_fname];
	if (typeof from_window == "object" && from_window != null) {
		fromForm = from_window.document.forms[from_fname];
	} else {
		fromForm = document.forms[from_fname];
	}
	
	for (var i = 0; i < attr_arr.length; i++) {
		var innerArr = attr_arr[i];
		
		copy_set_or_key_val(fromForm, toForm, innerArr[0], innerArr[1]);
	}
	

}

//////////////////////////////////////////////////////////////////////
//
//	Copy an element value to another between forms.  
//	
//	fromForm - actual form object as the source
//	toForm - actual target form object
//	from_attr - name of attribute to search for and copy from fromForm
//	to_attr - name of attribute to copy value from from_attr value
//
//	If the element is a select object and we requested "KEY.fromForm", then
//	we want the symbol for the SREL.  
//
//	Returns -1 if some exception encountered.
//////////////////////////////////////////////////////////////////////
function copy_set_or_key_val(fromForm, toForm, from_attr, to_attr)
{

	// This is only for editable forms!!  Target forms should have default values!

	if (typeof fromForm == "undefined" || typeof toForm == "undefined" ||
		typeof from_attr == "undefined" || typeof to_attr == "undefined") 
	{
		return -1;
	}
	
	var attrPrefix = "";
	var plainAttrName = "";
		
	if (0 == from_attr.indexOf("KEY.") || 0 == from_attr.indexOf("SET.")) {
		attrPrefix = from_attr.slice(0, 3);
		plainAttrName = from_attr.slice(4);
	} else {
		return -1;
	}
	
	var src_elm = fromForm.elements[from_attr];
	
	if (typeof src_elm != "object" || src_elm == null) {
		// Couldn't find it.  Maybe this is really a select element?
		if ("KEY" == attrPrefix) {
			src_elm = document.main_form.elements["SET." + plainAttrName]; 
			if (typeof src_elm != "object" || src_elm == null || src_elm.type != "select-one") 
			{
				return -1; 
			}
		} else {
			return -1;
		}
	} 
    
    var val = null;
    
    // Search for source attr, breaking
    //	as soon as we find it.
    if (src_elm.type == "select-one") {
		// Find the option that has text matching val.  If we were
		//	passed KEY.name, match on options.text.  If we're passed
		//	SET.name, match on the value
		var opts = src_elm.options;
		var idx = src_elm.selectedIndex;
			
		if ("KEY" == attrPrefix) {
			val = opts[idx].text;;
		} else {
			val = opts[idx].value;
		}
		
	} else {
		val = src_elm.value;
	}
	
   
    // Finally do the copy
    if (null != val) {
		var to = toForm.elements[to_attr];
		if (typeof to == "object")
			to.value = val;
		else {
			return -1;
		}
	}
	return 0;
}

var mouseoverMenus = ( typeof ahdtop == "object" && ahdtop.mouseoverMenus );

// The following functions implement ContextMenus, a DynLayer application

// ContextMenu constructor
//    Setup a context menu.  Must be called during document load.
var ctxMenus = new Array();
var activeCtxMenu = void(0);
function ContextMenu(name)
{
   this.name = name;
   this.mnum = ctxMenus.length;
   this.itemCnt = 0;
   this.actKeys = "";
   this.items = new Array();
   this.func = new Array();
   this.dynlayer = void(0);
   this.hdlTimeout = void(0);
   this.isVisible = false;
   this.mouseless = false;
   this.focused = false;
   this.owningWindow = window;
   this.inum = -1;
   this.changeLabel = void(0);
   this.AlwaysShow = false;
   ctxMenus[this.mnum] = this;

   var out;
   if ( ahdtop.cstUsingScreenReader &&
        ( name != "rClickMenu" ||
          ! ahdtop.propDebugScript ) ) {
      this.usingScreenReader = true;
      this.menuDisplayedOnce = false;
      out = "<select id='ctx_" + this.mnum + "' style='display:none;'></select>";
   }
   else {
      this.usingScreenReader = false;
      out = "<div id='" + name +
            "' style='position:absolute;z-index:1;display:none' ";
      if ( _browser.isIE55 )
          out += "onMouseOut=\"parent.contextMenuMouseOut(event," +
                 this.mnum + ")\" "+
                 "onMouseOver=\"parent.contextMenuMouseOver(" +
                 this.mnum + ")\">\n";
      else
          out += "onMouseOut=\"contextMenuMouseOut(event," +
                 this.mnum + ")\" "+
                 "onMouseOver=\"contextMenuMouseOver(" +
                 this.mnum + ")\">\n";
      out += "<table cellpadding=1 cellspacing=0 border=0 bgcolor='#cccccc'><tr><td><table id='" + name + "Tbl' cellpadding=0 cellspacing=0 border=0>\n";
   }
    document.writeln(out);
}

// ContextMenu.addItem()
//    Add a new item to the menu.  Must be called during document load
ContextMenu.prototype.addItem = function( text, func, img, extended )
{
   if ( typeof siteContextMenuitemMod != "undefined" ) {
      var label = siteContextMenuitemMod(this.name, text);
      if ( typeof label == "boolean" && ! label )
         return;
      if ( typeof label == "string" && label.length > 0 )
         text = label;
   }
   var strID = "ctx_" + this.mnum + "_" + this.itemCnt;
   this.items[this.itemCnt] = { id: strID,
                                label: text,
                                func: func,
                                img: img,
                                extended: extended,
                                isActive: true,
                                isHidden: false,
                                addArgLen: ContextMenu.prototype.addItem.arguments.length };
   if ( ! this.usingScreenReader ) {
      var out = "<TR id=tr" + strID + "><TD";
      out+= ">";        // @IG    31 Mar 2004
      if ( ContextMenu.prototype.addItem.arguments.length > 2 && img != "" )    // @IG    31 Mar 2004
          out += "<IMG id=img" + strID + " src='" + img + "'>";
      out += "</TD><TD CLASS=menubar_unselected_background ID=" + strID + "_cell";        // @IG    31 Mar 2004
      
      if ( _browser.isIE55 )
      {
          out += " onMouseOver=\"parent.contextMenuCellMouseOver(" + this.mnum + "," + this.itemCnt + ")\"";
          out += " onMouseOut=\"parent.contextMenuCellMouseOut(" + this.mnum + "," + this.itemCnt + ")\"";
      }
      else 
      {
          out += " onMouseOver=\"contextMenuCellMouseOver(" + this.mnum + "," + this.itemCnt + ")\"";
          out += " onMouseOut=\"contextMenuCellMouseOut(" + this.mnum + "," + this.itemCnt + ")\"";
      }

      out += "><A ID=" + strID;
      out += " CLASS='menu_unselected_text' onMouseOver='return true;' ondragstart='return false;' ";
      if ( _browser.isIE55 )
      {
          out += " HREF=" + cfgCAISD + "/html/empty.html";
          if ( ContextMenu.prototype.addItem.arguments.length > 3 && extended == 1 )         // @IG    31 Mar 2004
            out += " onClick='parent.pm_execFunc(\"" + strID + "\")'";
          else    {         
            if (mouseoverMenus)
                out += " onClick=\"parent." + func + "\"";
            else
                out += " onClick=\"parent." + func + ";parent.contextMenuKeyDown(null,35,0);\"";//Sending 13 to simulate enter and hide the menu
          }
          out += " onMouseOver=\"parent.contextMenuFocus(" + this.mnum + ")\">";
      }
      else
      {
          if ( ContextMenu.prototype.addItem.arguments.length > 3 && extended == 1 )         // @IG    31 Mar 2004
            out += " HREF='javascript:pm_execFunc(\"" + strID + "\"," + String(this.mnum) + ")'>";
          else
            out += " HREF=\"javascript:" + func + "\" onclick=\"contextMenuHide(" + String(this.mnum) + ");\">";
      }
      var actKey = "";
      if (text.indexOf("[") != -1)
      {
        var initialval = text.indexOf("[");
        var endval = text.indexOf("]");
        var actkeylen = (endval-1)-initialval;
        actKey = text.substr(initialval+1,actkeylen);        
        text = text.substr(0,initialval);
      }
      actKey = bestKey( actKey, text, this.actKeys );
      this.actKeys += actKey;
      out += fmtLabelWithActkey( text, actKey );
      out += "</A></TD></TR>\n";

      document.writeln(out);
   }
   
   this.itemCnt++;
   return strID;
}

ContextMenu.prototype.eval_func = function (funcString)
{
    eval(funcString);    
}
ContextMenu.prototype.changeItemLabel = function (itemCnt, changeToText)
{
    if ( this.usingScreenReader ) {
      if ( itemCnt < this.items.length )
        this.items[itemCnt].label = changeToText;
      return;
    }
    var id = "ctx_" + this.mnum + "_" + itemCnt;
    var doc;
    if ( _browser.isIE55 )
    {
    if (this.isVisible == false)
    {
        this.changeLabel = "this.changeItemLabel(" + itemCnt + ", '" + changeToText+ "')";
        return;
    }
    if (typeof this.popup.document == "undefined") return;
    doc = this.popup.document.body.document;
    }
    else
        doc = document;
    this.changeLabel = void(0);
    var menuItem = doc.getElementById(id);
    if (typeof menuItem == "undefined")
    return;
    var temp_str = this.actKeys.substring(0, itemCnt) + 
    this.actKeys.substring(itemCnt + 1, this.actKeys.length);

    var actKey = "";
    if (changeToText.indexOf("[") != -1)
    {
    var initialval = changeToText.indexOf("[");
    var endval = changeToText.indexOf("]");
    var actkeylen = (endval-1)-initialval;
    actKey = changeToText.substr(initialval+1,actkeylen);        
    changeToText = changeToText.substr(0,initialval);
    }
    actKey = bestKey(actKey, changeToText, temp_str);
    this.actKeys = this.actKeys.substring(0, itemCnt) + actKey + 
    this.actKeys.substring(itemCnt + 1, this.actKeys.length);
    menuItem.innerHTML = fmtLabelWithActkey(changeToText, actKey);
}

// ContextMenu.finish()
//    Complete a context menu.  Must be called during document load.
ContextMenu.prototype.finish = function()
{
   if ( typeof siteContextMenuitemAdd != "undefined" )
      siteContextMenuitemAdd(this.name, this);
   if ( ! this.usingScreenReader )
      document.writeln("</TABLE></TD></TR></TABLE></DIV>");
}

// ContextMenu.tr()
//     Build a tr tag on a row with a context menu.  The tag includes
//     an oncontextmenu event (unless we are using mouseover menus)
ContextMenu.prototype.tr = function(extraCode, tagargs )
{
  var out = "<tr";
  if ( typeof tagargs == "string" && tagargs.length > 0 )
    out += " " + tagargs;
  if ( ! ahdtop.mouseoverMenus ) {
    out += " oncontextmenu=\"";
    if ( typeof extraCode == "string" &&
         extraCode.length > 0 )
      out += extraCode + ";";
    if ( this.usingScreenReader )
      out += this.name + ".show(event,this,0);\"";
    else
      out += this.name + ".show(event,null,0);\"";
  }
  out += ">";
  return out;
}

// ContextMenu.mouseEvents()
//     Build onMouseOver and onMouseEvents for a context menu
ContextMenu.prototype.mouseEvents = function(extraCode)
{
  var out = "";
  if ( ahdtop.mouseoverMenus &&
       ! this.usingScreenReader ) {
    out = " onMouseOver=\"";
    if ( typeof extraCode == "string" && extraCode.length > 0 )
    for ( var i = 0; i < arguments.length; i++ )
      out += extraCode + ";";
    out += this.name + ".show(event,this);\"" +
           " onMouseOut=\"" + this.name + ".hide();return true;\"";
  }
  return out;
}

// ContextMenu.show()
//    Show a context menu after a delay (default 1/2 second)
//       e - can be either a mouseover event or the string "mouseless"
//       assoc - the link (anchor) object associated with this display
//       delay - milliseconds before menu is shown
//       IgnoreScroll - default to false. Needed when launching the KT tree
ContextMenu.prototype.show = function( e, assoc, delay, IgnoreScroll )
{
   this.ifired = false;
   if (typeof IgnoreScroll != "boolean")
   {
       IgnoreScroll = false;
   }
   var x = 0, y = 0;
   var mouseless = ( typeof e == "string" && e == "mouseless" );
   
   // If we are not using the classic "hover-over" resultset context menu
   // activation, then display this menu only if we activated it with the
   // mouseless interface

   if ( typeof assoc == "object" &&
        assoc != null && 
        typeof assoc.tagName == "string" &&             
        ( mouseoverMenus || mouseless ) ) {
      x = assoc.offsetWidth;
      //var dbg_text = "wid=" + x;
      for ( e = assoc; e.tagName != "BODY"; e = e.parentNode ) {
         if ( e.tagName == "TD" ) {
            x += e.offsetLeft;
            y += e.offsetTop;
            if ( e.id.match(/sched_/) ) {
               y += 20;
            }
         }
         if ( e.tagName == "TABLE" ) {
            x += e.offsetLeft;
            y += e.offsetTop;
         }
         if (e.tagName == "A" ) {
            if ( e.id.match(/sched_/) ) {
              x += 20;
              y += 20;
            }
            else {
              x += e.offsetLeft;
              y += e.offsetTop;
            }
         }
         // Adjust x and y for enclosing DIVs (scrollbars and notebook)
         if ( e.tagName == "DIV" &&
              e.id.match(/scrollbar|nbtab/) ) {
            if ( _browser.isIE55 ) {
               // This line causes the position of the context menu in
               // Mozilla to be off.  It should apply only to IE
               x += e.offsetLeft;                        
               y += e.offsetTop;
            }
            x -= e.scrollLeft;
            y -= e.scrollTop;
         }
         //dbg_text += "\n"  +e.tagName + " id=" + e.id + " left=" + e.offsetLeft + " top=" + e.offsetTop + " scrollLeft=" + e.scrollLeft + " scrollTop=" + e.scrollTop + " x=" + x + " y=" +y;
      }
      // Adjust x and y for popup function.
      if ( _browser.isIE55 ) {
         x -= document.body.scrollLeft;
         y -= document.body.scrollTop;
      }
      //dLog(dbg_text);
   }
   else if ( _browser.isIE ) {
       if ( window.event.ctrlKey )
         return;
       x = window.event.clientX - 3;
       y = window.event.clientY - 3;
       if ( _browser.isIE55 ) {
          if ( ! IgnoreScroll ) {
            x += document.body.scrollLeft;
            y += document.body.scrollTop;
          }
       }
   }
   else {
       if ( e.ctrlKey )
         return;
       x = e.pageX - 3;
       y = e.pageY - 3;
   }

   this.x = x;
   this.y = y;

   if ( typeof assoc != "object" )
      assoc = null;
   if ( typeof delay != "number" )
      delay = 500;
   if ( typeof this.hdlTimeout != "undefined" ) {
      if ( assoc == this.assoc )
         return;
      window.clearTimeout(this.hdlTimeout);
      this.hdlTimeout = void(0);
   }
   if (  ! _browser.isIE55 && this.isVisible && ! this.usingScreenReader ) {
      if ( assoc != this.assoc ) {
         this.assoc = assoc;
         if (!_browser.isIE)
         {
            var menuData = document.getElementById(this.name);
            var height = menuData.offsetHeight;
            var width = menuData.offsetWidth;
            if ( y+height > window.innerHeight)
            {
                y -= height;
                if (y < 0)
                    y = 0;
            }
            if ( x+width > window.innerWidth)
            {
                x -= width;
                if (x < 0)
                    x = 0;     
            }
         }
         this.dynlayer.moveTo( x, y );
      }
   }
   else {
      if ( _browser.isIE55 && this.isVisible )
         contextMenuHide(this.mnum);
      this.assoc = assoc;
      this.mouseless = mouseless;
      if ( delay == 0 )
         contextMenuShow(this.mnum);
      else
         this.hdlTimeout = window.setTimeout( "contextMenuShow(" + this.mnum + ")",
                                              delay );
   }
   return false;
}

// contextMenuShow()
//    Part 2 of ContextMenu.show().  Should not be called directly.
function contextMenuShow(mnum)
{
   var ahdtop = get_ahdtop();
   if ( typeof ahdtop == "object" &&
        typeof ahdtop.LoadingPopup == "object" &&
        typeof ahdtop.LoadingPopup.closed == "boolean" &&
        !ahdtop.LoadingPopup.closed &&
        mnum.AlwaysShow == false)
      return;

   if ( mnum < ctxMenus.length ) {
      var e;
      var td;
      var m = ctxMenus[mnum];
      if ( typeof m.hdlTimeout != "undefined" ) {
         window.clearTimeout(m.hdlTimeout);
         m.hdlTimeout = void(0);
      }

      if ( m.usingScreenReader ) {
        contextMenuBuildScreenReaderMenu( m );
        return false;
      }

      // If we are using the classic "hover-over" resultset context menu
      // activation, set the focus on the window the resultset is in.
      if ( mouseoverMenus )
          m.owningWindow.focus();
      m.owningWindow.setTempKeyDownHandler(contextMenuKeyDown);
      if ( _browser.isIE55 ) {
         var menuData = document.getElementById(m.name);
         if ( typeof menuData == "object" && menuData != null ) {
            menuData.style.display = "";
            var width = menuData.scrollWidth;
            var height = menuData.scrollHeight;
            menuData.style.display = "none";
            var popup = window.createPopup();
            if ( typeof ahdtop == "object" && ahdtop != null ) {
               var popupStyle = popup.document.createStyleSheet();
               if ( ahdtop.menuStyles.length == 0 )
                  ahdtop.initMenuStyles(window);
               for ( var i = 0; i < ahdtop.ctxmenuStyles.length; i++ ) {
                  var ruleName = ahdtop.ctxmenuStyles[i][0];
                  var ruleText = ahdtop.ctxmenuStyles[i][1];
                  popupStyle.addRule( ruleName, ruleText );
               }
               if ( typeof editPopupStyles == "function" )
                 editPopupStyles(popupStyle);
            }
            popup.document.body.innerHTML =
                          menuData.outerHTML.replace(/self\./ig,"parent.");
            e = popup.document.body.document.getElementById(m.name);
            e.style.display = "";
            popup.show( m.x, m.y, width, height, window.document.body );
            m.popup = popup;
            m.inum = -1;
         }
      }
      else {
         if ( typeof m.dynlayer != "object" )
            m.dynlayer = new DynLayer(m.name);

         var x = m.x;
         var y = m.y;
         if (!_browser.isIE)
         {
            m.dynlayer.show();
            var menuData = document.getElementById(m.name);
            var height = menuData.offsetHeight;
            var width = menuData.offsetWidth;
            if ( y+height > window.innerHeight)
            {
                y -= height;
                if (y < 0)
                    y = 0;
            }
            if ( x+width > window.innerWidth)
            {
                x -= width;
                if (x < 0)
                    x = 0;     
            }
         }
         
         m.dynlayer.moveTo( x, y );         
         m.dynlayer.show();
         if ( _browser.isIE )
            m.dynlayer.layer.scrollIntoView();
      }
      m.isVisible = true;
      activeCtxMenu = m;
      if ( m.mouseless ) {
         var d = ( _browser.isIE55 ? m.popup.document.body.document
                                   : document );         
         for ( i = 0; i < m.items.length; i++ )
           if ( m.items[i].isActive &&
                ! m.items[i].idHidden )
             break;
         if ( i >= m.items.length )
           i = 0;
         e = d.getElementById("ctx_" + m.mnum + "_" + i);
         td = d.getElementById("ctx_" + m.mnum + "_" + i + "_cell");
         if ( typeof e == "object" && e != null ) {
             e.className = "menu_selected_text";            
             m.inum = i;
         }
         if ( typeof td == "object" && td != null ) {
             td.className = "menubar_selected_background";
         }
      }
      if ( typeof m.changeLabel != "undefined" )
      {
        m.eval_func(m.changeLabel);
        m.changeLabel = void(0);
      }
   }
}

// contextMenuBuildScreenReaderMenu()
//    Build a dropdown-style menu for use with a screen reader (eg JAWS)
function contextMenuBuildScreenReaderMenu(menu)
{
  if ( typeof menu.assoc == "object" && menu.assoc != null ) {
    ahdtop.contextMenu = menu;
    var w = ahdtop.contextMenuWindow;
    if ( typeof w == "object" && ! w.closed )
      w.close();
    var features = "resizable" +
                   ",height=" + (50 + menu.items.length * 14) +
                   ",width=240";
    //if ( _browser.isNS )
    //  features += ",screenX=" + ( screenX + menu.x ) +
    //              ",screenY=" + ( screenY + menu.y );
    //else
    //  features += ",top="  + ( screenTop + menu.y ) +
    //              ",left=" + ( screenLeft + menu.x );
    
    w = window.open(ahdtop.usdHTML["ctxmenu"], "", features );
    if (!check_popup_blocker(w))
	return;
    ahdtop.contextMenuWindow = w;
  }
}

// contextMenuEval()
//    Callback to run a context menu function
function contextMenuEval(i)
{
   eval(ahdtop.contextMenu.items[i].func);
}
                      
// ContextMenu.hide()
//    Hide a conteclientxt menu after a delay (default 1/4 second)
ContextMenu.prototype.hide = function( delay )
{
   if ( typeof this.hdlTimeout != "undefined" ) {
      window.clearTimeout(this.hdlTimeout);
      this.hdlTimeout = void(0);
   }
   if ( this.isVisible &&
        ! this.usingScreenReader ) {
      if ( typeof delay != "number" ) {
        if ( typeof delay != "string" || delay != "nofocus" )
          delay = 250;
        else {
          // Support "nofocus" argument to prevent refocusing on form element
          // with the context menu.  This is useful in the Change Calendar
          // and Scheduler to prevent the form from stealing back the focus
          // after Alt+Tab with hover information showing (SCO 22633)
          delay = 0;
          if ( this.mnum < ctxMenus.length ) {
            var m = ctxMenus[this.mnum];
            m.assoc = null;
          }
        }
      }
      if ( delay == 0 )
         contextMenuHide(this.mnum);
      else
         this.hdlTimeout = window.setTimeout( "contextMenuHide(" + this.mnum + ")",
                                              delay );
   }
}

// contextMenuHide()
//    Part 2 of ContextMenu.hide().  Should not be called directly.
function contextMenuHide(mnum)
{
   if ( mnum < ctxMenus.length ) {
      var m = ctxMenus[mnum];
      if ( typeof m.hdlTimeout != "undefined" ) {
         window.clearTimeout(m.hdlTimeout);
         m.hdlTimeout = void(0);
      }
      if ( m.isVisible ) {
         if ( _browser.isIE55 ) {
           // Without this check, context menu disappears
           // when quickly moving mouse to it. 
           if ( mouseoverMenus && m.focused )
             return;
           if ( typeof m.popup == "object" )
             m.popup.hide();
         }
         else
            m.dynlayer.hide();
         m.isVisible = false;
         activeCtxMenu = void(0);
         m.owningWindow.setTempKeyDownHandler(null);
         if ( typeof m.assoc == "object" && m.assoc != null )
            try {m.assoc.focus()} catch(e) {};
      }
   }
}

// ContextMenuMouseOver()
//    User has moused into our layer.  Cancel any pending actions.
function contextMenuMouseOver(mnum)
{
   if ( mnum < ctxMenus.length ) {
      var m = ctxMenus[mnum];
      m.focused = true;
      if ( typeof m.hdlTimeout != "undefined" ) {
         window.clearTimeout(m.hdlTimeout);
         m.hdlTimeout = void(0);
      }
   }       
return true;
}

// ContextMenuMouseOut()
//    User has moused out of our layer.  Cancel any pending actions,
//    and hide the menu if the user has really left it.
function contextMenuMouseOut(ev, mnum)
{
   if ( _browser.isIE )
      ev = window.event;
   window.status = window.defaultStatus;
   if ( mnum < ctxMenus.length ) {
      try {
        var m = ctxMenus[mnum];
        m.focused = false;
        if ( typeof m.hdlTimeout != "undefined" ) {
          window.clearTimeout(m.hdlTimeout);
          m.hdlTimeout = void(0);
        }
        if ( m.isVisible ) {
          if ( _browser.isIE55 ) {
              m.hide(100);
          }
          else if ( ! m.dynlayer.isInside(ev) ) {
              m.dynlayer.hide();
              m.isVisible = false;
              activeCtxMenu = void(0);
              m.owningWindow.setTempKeyDownHandler(null);
          }
        }
      } catch(e) {}
   }
   return true;
}

// ContextMenuMouseOver()
//    User has moused into our layer.  Cancel any pending actions.
function contextMenuCellMouseOver(mnum, itemCnt)
{
   if ( mnum < ctxMenus.length ) {
    try {
      var m = ctxMenus[mnum];      
  
      var d = ( _browser.isIE55 ? m.popup.document.body.document
                                  : document );
      var e = d.getElementById("ctx_" + mnum + "_" + itemCnt);
      var td = d.getElementById("ctx_" + mnum + "_" + itemCnt + "_cell");
      if ( typeof e == "object" && e != null ) {
        e.className = "menu_selected_text";                
      }
      if ( typeof td == "object" && td != null ) {
        td.className = "menubar_selected_background";
      }
    } catch(e) {}
  }
    
  return true;
}

// ContextMenuMouseOver()
//    User has moused into our layer.  Cancel any pending actions.
function contextMenuCellMouseOut(mnum, itemCnt)
{
   if ( mnum < ctxMenus.length ) {
    try {
      var m = ctxMenus[mnum];      
  
      var d = ( _browser.isIE55 ? m.popup.document.body.document
                                  : document );
      var e = d.getElementById("ctx_" + m.mnum + "_" + itemCnt);
      var td = d.getElementById("ctx_" + m.mnum + "_" + itemCnt + "_cell");
      if ( typeof e == "object" && e != null ) {
        e.className = "menu_unselected_text";                
      }
      if ( typeof td == "object" && td != null ) {
        td.className = "menubar_unselected_background";
      }
    } catch(e) {}
  }
    
  return true;
}

// contextMenuKeyDown()
//    Mouseless navigation of the menu
function contextMenuKeyDown(active_element,keycode,shiftkey)
{
   if ( typeof activeCtxMenu != "object" || activeCtxMenu == null )
      return true; // Help! We have a keydown handler but no menu
   var m = activeCtxMenu;
   if ( _browser.isIE55 &&
        ( typeof m.popup != "object" ||
          ! m.popup.isOpen ) ) {
          
         // SDT 23759
         // We could get here if user exited popup with Esc
         // key.  Clean up the internal object properly with hide()
         // and continue.
         m.hide(0);
          m.focused = false;
          return true;
   }
   var i, new_inum = m.inum;
   // Note: Cannot use symbolics in switch statement below because this
   //       file is used in customer & employee interfaces which must
   //       support (ugh) Netscape 4
   switch ( keycode ) {
      case 38: // ARROW_UP:
         for ( i = m.inum - 1; i >= 0; i-- ) {
           if ( m.items[i].isActive &&
                ! m.items[i].isHidden ) {
             new_inum = i;
             break;
           }
         }
         break;

      case 40: // ARROW_DOWN:
         for ( i = m.inum + 1; i < m.itemCnt; i++ ) {
           if ( m.items[i].isActive &&
                ! m.items[i].isHidden ) {
             new_inum = i;
             break;
           }
         }
         break;

      case 9: // TAB:
         m.hide(0);
         return true;

      case 37: // ARROW_LEFT:
         m.hide(0);
         break;
         
      case 35: // ESC:
         m.hide(0);
         break;

      case 13: // ENTER:
         m.hide(0);
         m.ifired = true;
         eval( m.items[m.inum].func );
         break;

      default:
         var key = String.fromCharCode(keycode).toUpperCase();
         var posn = m.actKeys.indexOf(key);
         if ( posn != -1 ) {
            m.hide(0);
            eval( m.items[posn].func );
         }
         break;
   }
   if ( m.inum != new_inum ) {
      var d, e, td;
      if ( _browser.isIE55 )
         d = m.popup.document.body.document;
      else
         d = document;
      if ( m.inum >= 0 ) {
         e = d.getElementById("ctx_" + m.mnum + "_" + m.inum);
         td = d.getElementById("ctx_" + m.mnum + "_" + m.inum + "_cell");
         if ( typeof e == "object" && e != null )
            e.className = "menu_unselected_text";
         if ( typeof td == "object" && td != null )
            td.className = "menubar_unselected_background";
         
      }
      e = d.getElementById("ctx_" + m.mnum + "_" + new_inum);      
      if ( typeof e == "object" && e != null )
         e.className = "menu_selected_text";
      
      td = d.getElementById("ctx_" + m.mnum + "_" + new_inum + "_cell");      
      if ( typeof td == "object" && td != null )
         td.className = "menubar_selected_background";
         
      m.inum = new_inum;
   }
   return false;
}

// bool()
//   General purpose function to convert a field to Boolean
function bool(arg)
{
   switch ( typeof arg ) {
      case "boolean":   return arg;
      case "string":    return arg.length == 1 && arg != "0";
      case "number":    return arg != 0;
      default:          return false;
   }
}

// activateStatistics()
//     Activate the response time statistics feature
function activateStatistics(showAlert)
{
  if ( typeof ahdtop == "object" && ahdtop != null ) {
    if ( typeof ahdframeset == "object" &&
         ahdframeset != ahdtop )
      ahdtop.activateStatistics(false)
    else
      ahdtop.popup_req_time = new Array();
    if ( typeof showAlert != "boolean" || showAlert )
      alertmsg("Response_time_statistics_activ"); // Response time statistics activated
  }
}

// showStatistics()
//    Popup the statistics dialog
function showStatistics()
{
   var stats;
   if ( typeof formCheckpoint == "object" ) {
     var loadTime = formCheckpoint["load"];
     if ( typeof formCheckpoint["request"] == "undefined" ) {
        if ( typeof propFormName == "string" &&
             propFormName == "bin_form_np.htmpl" )
           return;
        stats = msgtext("Request_Time:_unknown"); // Request Time:  unknown
     }
     else {
        var reqTime = formCheckpoint["request"];
        stats = msgtext("Request_Time:_%1", fmtTimeDiff(reqTime)); // Request Time %1
     }
     var doneTime = new Date();
     stats += "\n" + msgtext("Load_Start:_%1", fmtTimeDiff(loadTime,reqTime)) + // Load Start %1
              "\n" + msgtext("Load_Complete:_%1", fmtTimeDiff(doneTime,loadTime)); // Load Complete %1
     if ( typeof reqTime == "object" )
        stats += "\n" + msgtext("User_Resp_Time:_%1_secs", // User Resp Time: %1 secs
                 (doneTime.getTime() - reqTime.getTime()) / 1000);
     if ( ! confirm(stats) ) {
        var ahdtop = get_ahdtop();
        if ( typeof ahdtop == "object" && ahdtop != null )
           ahdtop.popup_req_time = void(0);
     }
   }
}

function fmtTimeDiff(endTime, startTime)
{
   var s = endTime.toTimeString();
   if ( typeof startTime == "object" ) {
      var delta = endTime.getTime() - startTime.getTime();
      s += " (" + delta / 1000 + " " + msgtext("secs") + ")";
   }
   return s;
}

function do_ci_60()
{
    var w_name = get_popup_window_name("ci_window");
    
    // Write out array params - this pre-6.0 compatibility is intended
    //	only for requests.  See detail_cr.htmpl and ci_update_fields()
    var js = "<script>var fromArr = new Array();";
	
	js += 'fromArr[0] = ["KEY.category", "CATEGORY"];';
	js += 'fromArr[1] = ["KEY.affected_resource", "ITEM"];';
	js += 'fromArr[2] = ["SET.affected_resource", "SD_ASSET_ID"];';
	js += 'var dOptField = cfgSearchStr;' ;
	js += 'if (null == dOptField || "" == dOptField) ' ;
	js += 'dOptField = "description";' ;
	js += 'fromArr[3] = ["SET." + dOptField, "DESCRIPTION"];' ;
	js += "</script>";
	
    js += img_button_text('KT_NLS', 'search_nls', 125, "\"ci_update_fields(window, 'main_form', 'ci_search', fromArr);popupCiWindow('" + w_name + "' ,'ci_search', '', 1)\"", "<INPUT TYPE=BUTTON VALUE=\'Search NLS\' onClick=\"ci_update_fields(window, 'main_form', 'ci_search', fromArr);popupCiWindow('" + w_name + "' ,'ci_search', '', 1)\">");
    document.writeln(js); 
}

function redo_ci_60()
{
    var file_name = propFormName;
    if (typeof cfgUserType == "string" &&
	cfgUserType == "analyst" && 
	propFormName == "detail_cr_ro.htmpl")
    {
	file_name = "crro_alg_tab.htmpl";
    }
    var temp = '<TD VALIGN=TOP class=detailro><A HREF="javascript:void(0)" onClick="alertmsg(\'To_browser_solution,_please_us\', \'' + file_name + '\')" >' + msgtext("Detail") + '</A></TD>';
    return temp;
}

function cst_do_ci_60()
{
    var tmp = img_button_text('KT_NLS', 'search_nls', 125, "\"cst_popup_knowledge()\"", "<INPUT TYPE=BUTTON VALUE=\'Search NLS\' onClick=\"cst_popup_knowledge()\">");
    document.writeln(tmp);     
}

function cst_popup_knowledge()
{
	var search_form = document.forms["ci_search"];
	// todo : need a new message here
	if (typeof search_form ==  "undefined")
	{
	    alertmsg("The_ci_search_form_is_missing.", "cst_ci_search.htmpl", propFormName);  
	    return;
	}
	var description_elem = search_form.elements["DESCRIPTION"];
	var main_form = document.forms["main_form"];
	var set_desc_elem;
	if (typeof main_form == "object")
	    set_desc_elem = main_form.elements["SET.description"];
	    
	if (typeof search_form !="object" || 
	    typeof description_elem !="object" ||
	    typeof set_desc_elem !="object")
	    return;
	
	description_elem.value = set_desc_elem.value;

	popupCiWindow("ci_search", "ci_search");
}

// Copy and Paste (IE only)
function copyContent()
{
    var selectedText = document.selection;
	if (selectedText.type == 'Text') {
		var newRange = selectedText.createRange();
		newRange.execCommand('copy');
	} else 
		alert('select a text in the page and then choose this option');
    if (rClickMenu)
        rClickMenu.hide(0);
}

function pasteContent()
{
    if (paste_field && window.clipboardData)
    {
        var copy_content = window.clipboardData.getData('Text');
        paste_field.value = copy_content;
    }    
    if (rClickMenu)
        rClickMenu.hide(0);
 
}

// refreshForm()
//    Refresh this form if possible
function refreshForm()
{
   var url = "";
   // make window list a special case
   if ((typeof propFormName == "string") && 
       (propFormName == "window_list.html"))
   {
	window.location.reload();
	return;
   }
   // make the SD scoreboard a special case
   if ((typeof propFormName == "string") && 
       (propFormName == "scoreboard.htmpl") &&
       (typeof window.request_reload != "undefined"))
   {
	window.request_reload();
	return;
   }
   // make the profile browser a special case
   // Calling reload can cause JS loading problem 
   // when using servlet. 
   if ((typeof window.parent == "object") && 
       (typeof window.parent.page == "object"))  
   {
	if ((typeof window.parent.menu == "object") && (propFormName == "profile_menu.htmpl")){
	    window.parent.menu.location.href = window.parent.menu.location.href;
	}else{
		if ((typeof window.parent.scratchpad == "object") && (propFormName == "scratchpad.htmpl")){
	    	window.parent.scratchpad.location.href = window.parent.scratchpad.location.href;
    	}else{
	    	window.parent.page.location.href = window.parent.page.location.href;
    	}
	}
	return;
   }
       
   if ( typeof propFormName3 != "string" ||
        propFormName3.toString() != "edit" ) {
      url = window.document.URL;
      if ( typeof propFormName1 == "string" &&
           propFormName1 == "detail" &&
           typeof argPersistentID == "string" ) {
         var colon = argPersistentID.indexOf(":");
         if ( colon != -1 )
            url = cfgCgi + "?SID=" + cfgSID + "+FID=" + cfgFID +
                  "+OP=SHOW_DETAIL+FACTORY=" +
                  argPersistentID.slice(0,colon) +
                  "+PERSID=" + nx_escape(argPersistentID);
      }
      if ((typeof propFormName1 == "string") &&
	  (propFormName1 == "list"))
      {
	    // If it's refreshing the first page of the search 
	    // result, call doSearch() because it now does 
	    // POST so URL doesn't contain search string.
	    if ((typeof cfgCurrent == "string") &&
		(cfgCurrent == "1")&& !url.match(/OP=SEARCH/)) 
	    {
		doSearch();
		return;
	    }
	    else 
	    {
		// For the rest, it still does GET.
		if ((url.match(/OP=PG/) || url.match(/OP=LIST_ALL/) || url.match(/OP=SEARCH/)) &&
		    !url.match(/REFRESH=1/)) 
    
		{ 
		    url += "+REFRESH=1"; 
		}
	    }
       }
   }
   if ( url.indexOf("?") == -1 ||
        url.match(/OP=(CANCEL|DELETE|UPDATE)/) ||
        url.indexOf("HTMPL=update_lrel_") != -1 || //don't allow to refresh any update lrel forms
        url.indexOf("HTMPL=kt_dtbuilder") != -1 )	// in case of Tree Designer
      alertmsg("Sorry,_unable_to_refresh_this_"); // Unable to refresh this form
   else {
      set_action_in_progress(ACTN_LOADFORM);
      url = url.replace(/\'/g,"%27");
      replace_page(url);
   }
}

// ContextMenu.activateItem()
// Activate menu item
ContextMenu.prototype.activateItem = function( id )
{
  for ( var i = this.items.length - 1; i >= 0; i-- ) {
    var item = this.items[i];
    if ( item.id == id ) {
      if ( ! item.isActive ) {
        item.isActive = true;
        if ( ! this.usingScreenReader ) {
          var oMenu = document.getElementById(id);
          if ( oMenu != null )
          {
            oMenu.style.color = "";
          }
		}
      }
      return;
    }
  }
}
// ContextMenu.deactivateItem()
// Deactivate menu item
ContextMenu.prototype.deactivateItem = function( id )
{
  for ( var i = this.items.length - 1; i >= 0; i-- ) {
    var item = this.items[i];
    if ( item.id == id ) {
      if ( item.isActive ) {
        item.isActive = false;
        if ( ! this.usingScreenReader ) {
          var oMenu = document.getElementById(id);
          if ( oMenu != null ){
            oMenu.style.color = "gray";
          }
        }
      }
      return;
    }
  }
}

// ContextMenu.showItem()
// Show menu item
ContextMenu.prototype.showItem = function( id )
{
  for ( var i = this.items.length - 1; i >= 0; i-- ) {
    var item = this.items[i];
    if ( item.id == id ) {
      if ( item.isHidden ) {
        item.isHidden = false;
        if ( ! this.usingScreenReader ) {
          var oTR = document.getElementById("tr" + id);
          if ( oTR != null )
            oTR.style.display = "";
        }
      }
      return;
    }
  }
}

// ContextMenu.hideItem()
// Hide menu item
ContextMenu.prototype.hideItem = function( id )
{
  for ( var i = this.items.length - 1; i >= 0; i-- ) {
    var item = this.items[i];
    if ( item.id == id ) {
      if ( ! item.isHidden ) {
        item.isHidden = true;
        if ( ! this.usingScreenReader ) {
          var oTR = document.getElementById("tr" + id);
          if ( oTR != null )
            oTR.style.display = "none";
        }
      }
      return;
    }
  }
}

// Change image
ContextMenu.prototype.changeImage = function( id, img )
{
	var oImg = document.getElementById("img" + id);
	if (oImg != null)
	{
		oImg.src = img;
	}
}

// Execute menu item
function pm_execFunc(id, mnum)
{
  if ( typeof activeCtxMenu != "undefined" && activeCtxMenu != null ) {
    for ( var i = activeCtxMenu.items.length - 1; i >= 0; i-- ) {
      var item = activeCtxMenu.items[i];
      if ( item.id == id ) 
      {
        if ( item.isActive && 
             ! item.isHidden ) 
         {
          eval(nx_unescape(item.func));
          activeCtxMenu.hide(0);
        }
        if(typeof nmum != "undefined")
        {
			contextMenuHide(mnum);
        }
        return;
      }
    }
  }
}

// show_preferences()
//    popup the User Preferences form

function showPreferences()
{
	var features="directories=no"+
		",location=no"+
		",height=" + popupHeight(MEDIUM_POPUP) +
		",width=" + popupWidth(MEDIUM_POPUP)+
		",status=no";
	
	if (typeof ahdtop.useDefaultPrefs == "undefined" || 
	    typeof ahdtop.prefsRecID == "undefined")
	{
	    alertmsg("Unable_to_start_preferences_pa");
	    return;
	}
	
	if(ahdtop.useDefaultPrefs)
	{	
		popup_window('pref:' + ahdtop.cstID, 'CREATE_NEW', 0, 0, features, 'FACTORY=USP_PREFERENCES', 'PRESET=ANALYST_ID:' + ahdtop.cstID, 'KEEP.SHOW_KT_PREFS=' + ahdtop.CanUserPerformAction("ROLE_PREFERENCES"));
	}
	else
	{
		popup_window('pref:' + ahdtop.prefsRecID, 'UPDATE', 0, 0, features, 'PERSID=USP_PREFERENCES:' + ahdtop.prefsRecID, 'KEEP.SHOW_KT_PREFS=' + ahdtop.CanUserPerformAction("ROLE_PREFERENCES"));	
			
	}	
}
//////////////////////////////////////////////////////////////
// function popup_solution_survey(doc_id, doc_BUID, doc_tenant, doc_title, sdLaunched, ticket_factory, launched_itil)
// called when $prop.SOL_SURV_FORCE_VOTE == "1" and document not rated
//
function popup_solution_survey(doc_id, doc_BUID, doc_tenant, doc_title, sdLaunched, ticket_factory, launched_itil)
{
	var features="directories=no"+
				",location=no"+
				",height=" + popupHeight(SMALL_POPUP) +
				",width=" + popupWidth(SMALL_POPUP)+
				",status=no";
	popup_window('SOLUTION_SURVEY:' + doc_id, 'JUST_GRONK_IT', -1, -1, features, 'HTMPL=kt_solution_survey_popup.htmpl', 'doc_id='+ doc_id, 'doc_BUID=' + doc_BUID, 'doc_tenant='+ doc_tenant, 'doc_title=' + doc_title, 'SD_LAUNCHED=' + sdLaunched, '+TICKET_FACTORY=' + ticket_factory, '+LAUNCHED_ITIL=' + launched_itil);	
}
//
////////////////////////////////////////////////////////////////
// findIt()
// Returns the value of a named element, or null if it cannot be found.
//	fromForm - an actual form object to search for the target
//	fromAttr - name of the element to search for
//
//	This funciton is designed specifically to find element names following
//	the forms "SET.name" and "GET.name".  It will handle
//	select elements correctly.
////////////////////////////////////////////////////////////////
function findIt(fromForm, from_attr)
{

	// This is only for editable forms!!  Target forms should have default values!

	if (typeof fromForm == "undefined" || typeof from_attr == "undefined") 
	{
		return null;
	}
	
	var attrPrefix = "";
	var plainAttrName = "";
		
	if (0 == from_attr.indexOf("KEY.") || 0 == from_attr.indexOf("SET.")) {
		attrPrefix = from_attr.slice(0, 3);
		plainAttrName = from_attr.slice(4);
	} else {
		return null;
	}
	
	var src_elm = fromForm.elements[from_attr];
	
	if (typeof src_elm != "object" || src_elm == null) {
		// Could not find it.  Maybe this is really a select element?
		if ("KEY" == attrPrefix) {
			src_elm = document.main_form.elements["SET." + plainAttrName]; 
			if (typeof src_elm != "object" || src_elm == null || src_elm.type != "select-one") 
			{
				return null; 
			}
		} else {
			return null;
		}
	} 
    
    var val = null;
    
    // Search for source attr
    if (src_elm.type == "select-one") {
		// Find the option that has text matching val.  If we were
		//	passed KEY.name, match on options.text.  If we are passed
		//	SET.name, match on the value
		var opts = src_elm.options;
		var idx = src_elm.selectedIndex;
			
		if ("KEY" == attrPrefix) {
			val = opts[idx].text;
		} else {
			val = opts[idx].value;
		}
		
	} else {
		val = src_elm.value;
	}
	
    return val;
}

// logSolution()
//    Called to open a solution activity.  Appends the asset name
// SDT 24262 Special feature - pass along set values of select elements to
//	log form so we have an opportunity to  lookup their ids for KT.  Only
//	needed on an editable form where these values can change before KT 
//	is popped.
function logSolution( query_str )
{
    query_str += "+ACTIVITY_LOG_TYPE=SOLN";
   
    // Only need to copy values from editable tickets
    // Pre 6.0 does not understand _dtl.
    if (typeof propFormRelease != "undefined" && propFormRelease >= 60 &&
		typeof _dtl != "undefined" && _dtl.edit) 
	{
		// Get values to pass to KT for a submit op,
		//	regardless of factory
		var pri = findIt(document.main_form, "SET.priority");
		var sev = findIt(document.main_form, "SET.severity");
		var urg = findIt(document.main_form, "SET.urgency");
		var imp = findIt(document.main_form, "SET.impact");
		if (null != pri)
			query_str += "+KEEP.pri_enum=" + pri;
		if (null != sev)
			query_str += "+KEEP.sev_enum=" + sev;
		if (null != urg)
			query_str += "+KEEP.urg_enum=" + urg;
		if (null != imp)
			query_str += "+KEEP.imp_enum=" + imp;
			
	}  
   
    popupActivityWithURL(query_str);

    // Set the flag to refresh the Solutions tab on save

    if ( typeof window._dtl == "object" )
      window._dtl.tabReloadOnSave += " soln";
}

function addViewSubMenuItems(menu, factory, RefNum)
{
	if ((0 + cfgUserAuth) > 1)
	{
		if ((0 + cfgAccessNotify) > 0)
			menu.addItem(menu.id + "NotifHst",
						 msgtext("Notification_History..."), // Notification History...
						 "",
						 "show_hist('" + factory + "', '" + RefNum + "', '" + argID + "')",
						 true);

		menu.addItem(menu.id + "ATEV",
				  msgtext("Event_History..."), // Event History...
				  "",
				  "show_evt('" + factory + "', 'atev', '" + argID + "')",
				  true, true);
		menu.addItem(menu.id + "EVTDLY",
				  msgtext("Event_Delay_History..."), // Event Delay History...
				  "",
				  "show_evt('" + factory + "', 'evtdly', '" +  argID + "')",
				  true, true);
	}
        menu.addInternalItem("idInTheKnowNotifyList",
			     msgtext("In-The-Know_Notify_List..."), // In-The-Know Notify List...
			     "",
			     "JavaScript: update_lrel('" + factory + "', '" + argPersistentID +
			     "', 'cnt', 'notify_list', '" + msgtext("Contact_List") + "', '" + msgtext("Contact_to_Notify") + "', '')",
			     "",
			     true);
}

/* Function: show_evt
	 * Parameters: fac		- object factory
	 * 			   ref_num	- reference number
	 *			   id		- id
	 *
	 * Return: none
	 *
	 * Purpose: Display the event history for a chg object in a new pop-up window
	 */
	function show_evt(fac, search_fac, id)
	{
		var wc = "+KEEP.where_clause=obj_id='" + fac + ":" + id + "'";
		var obj = "+KEEP.obj_type=" + fac;
		
		if (fac == "mgs") 
			var q = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator() + 
				"+OP=SEARCH+FACTORY="+search_fac+wc+obj;
		else
			var q = cfgCgi + "?SID=" + cfgSID + "+FID=" + fid_generator() + 
				"+OP=SEARCH+FACTORY="+search_fac+wc;
		var nh = preparePopup(q, "", "width=800,height=400,scrollbars,resizable");
		nh.focus();
	}	 

// The openDetail function for gobtn_role.htmpl 
function openDetail_role()
{
    ImgBtnEnableButton("btndflt");
    var searchKey = document.goBtnForm.searchKey;
    var key = searchKey.value.replace(/[\<\\"]/g,"");
    searchKey.value = "";
    if ( key.match(/^ *$/) ) 
    {
	searchKey.focus();
	return;
    }
    var ticket_type = document.goBtnForm.ticket_type;
    var ticket_type_obj = ticket_type[ticket_type.selectedIndex];
    var ticket_code = ticket_type_obj.value;
    var resource = go_list[ticket_code].resource;
    if (!ahdtop.cstReducePopups)
	ahdtop.go_role_menubar = go_list[ticket_code].role_menu;
    else 
	ahdtop.go_role_menubar = void(0);
    var add_where = ""
    var fac_arr = resource.match(/^.*factory=([^\+]+)\+.*$/i);
    if (fac_arr != null && fac_arr.length == 2)
    {
	var factory = fac_arr[1];
	if (factory == "cr" || 
	    factory == "chg" || 
	    factory == "iss" || 
	    factory == "in" || 
	    factory == "pr")
	{
	    if (ahdtop.propIsITIL && factory == "cr")
	    {
		add_where = "+ADDITIONAL_WHERE=" + 
			    nx_escape("(type='R' OR type='' OR type IS NULL)");
	    }

	    if (factory == "in" || factory == "pr")
		factory = "cr";
	    var ahdwin = ahdtop.detailForms[factory + key];
	    if ( typeof ahdwin == "object" &&
		 typeof ahdwin.name == "string" &&
		 typeof ahdwin.closed == "boolean" &&
		 ! ahdwin.closed ) 
	    {
		ahdwin.focus()
		if ( typeof ahdframe._dtl == "object" )
		    ahdframe._dtl.firstField.focus();
		return;
	    }
	}	
    }
    var srch_key = key;
    if (!resource.match(/^Javascript/i))
	srch_key = nx_escape(key);
    resource = resource.replace(/\$searchKey/g, srch_key);
    resource = resolveWebFormVars(resource);
    if (resource.match(/^javascript:/i))
    {
	eval(resource);	
    }  
    else 
    {
	if (add_where != "")
	    resource += add_where;
	ahdtop.popupWithURL(resource);
    }
}

function KDKeywordSearch (searchKey)
{
    ahdtop.SearchText = "QBE.IN.ebr_search_text=" + searchKey;
    var ebrSearchOrAndExact;
    if (ahdtop.GetUSPPreferences("ONE_B_MATCH_TYPE") == "2")				
	ebrSearchOrAndExact = "ALL";
    else if (ahdtop.GetUSPPreferences("ONE_B_MATCH_TYPE") == "3")
	ebrSearchOrAndExact = "EXACT";
    else
	ebrSearchOrAndExact = "ANY";
	
	for(var i=ahdtop.toolbarTab.length-1;i>=0;i--)
	{
		if (ahdtop.toolbarTab[i].code=="kt")
				ahdtop.toolbar.tabClick(i);
	}
	
    ahdtop.upd_frame("SEARCH", "FACTORY=KD", ahdtop.SearchText, "QBE.EQ.ebr_search_type=KEYWORDS", 
		     "QBE.EQ.ebr_match_type=" +  ebrSearchOrAndExact , 
		     "QBE.EQ.ebr_primary_order=" + ahdtop.GetUSPPreferences("ONE_B_SEARCH_ORDER"), 
		     "DOMSET=KD_list_ebr_RELEVANCE"); 
}

