// JavaScript code for Inmagic's Web Edit
// Copyright © 2002-2008 Inmagic, Inc., Woburn, MA, USA. All rights reserved.

var   bUseISAPI      = true;
var   bIsCS          = false;

var   dbtw_root;
var   dbtw_xsl;
var   dbtw_help;
var   dbtw_action;
var   dbtw_prod;

      if (bIsCS)
         {
         dbtw_root      = 'ics-wpd';
         dbtw_xsl       = '/ics-wpd/xsl/';
         dbtw_help      = '/ics-wpd/help/';
         dbtw_action    = '/ics-wpd/exec/icswppro.dll';
         dbtw_prod      = 'WebPublisher for SQL';

         if (bUseISAPI == false)
            dbtw_action = '/ics-wpd/exec/icspcgi.exe';
         }
      else
         {
         dbtw_root      = 'dbtw-wpd';
         dbtw_xsl       = '/dbtw-wpd/xsl/';
         dbtw_help      = '/dbtw-wpd/help/';
         dbtw_action    = '/dbtw-wpd/exec/dbtwpub.dll';
         dbtw_prod      = 'WebPublisher';

         if (bUseISAPI == false)
            dbtw_action = '/dbtw-wpd/exec/dbtwpcgi.exe';
         }

//    state variables
      var   gsb_AutoFormat_inProgress   = false;
      var   gsb_entrySepKeyPressed      = false;
      var   gsb_setFocusToFirstTabBox   = true;
      var   gsb_browserIsIE             = (navigator.appName == "Microsoft Internet Explorer");
      var   gsb_browserIsIE55orLater    = false;
      var   gsb_dataModified            = false;
      var   gsb_cookieNameIsFormName    = false;

//    box specific variables
      var   gbox_styleBorderStyle     = '';
      var   gbox_styleBorderWidth     = '';
      var   gbox_styleHeight          = '';

      var   gbox_bAutoResize          = false;
      var   gbox_bMaxResize           = false;
      var   gbox_nLineCount           = 0;
      var   gbox_nMinLines            = 0;
      var   gbox_nMaxLines            = 0;

      var   gbox_inputIx                  = '';
      var   gbox_choicesListType          = 2;
      var   gbox_choicesListURL           = '';
      var   gbox_inputFieldNameListXML    = '';
      var   gbox_inputFieldNameListNonXML = '';
      var   gbox_inputFieldNameSelected   = 0;
      var   gbox_maxListLength            = 0;
      var   gbox_includeNonPreferredTerms = 1;

//    global form hidden variables
      var   gform_AC                  = '';
      var   gform_BG                  = '';
      var   gform_FG                  = '';
      var   gform_TN                  = '';
      var   gform_QS                  = '';
      var   gform_BMX                 = 20;
      var   gform_MV                  = '';
      var   gform_OEH                 = '';
      var   gform_OEX                 = '';

//    global form other variables
      var   gform_formSelectionIndex  = -1;
      var   gform_CookieNamePrefix    = '';
      var   gform_Password            = '';

      var   gform_bBoxAutoFormat             = true;
      var   gform_bBoxHighlighting           = true;
      var   gform_bBoxHighlightingEnabled    = (true && gsb_browserIsIE);
      var   gform_bFromSingleRecordView      = false;
      var   gform_cAlternateEntryChar        = '';
      var   gform_sBoxEntrySeparatorKey      = '';

      var   gform_nFirstTabOrderBox    = -1;
      var   gform_nFirstPwBox          = -1;

//    ichoices form colors
      var   ichoices_bgColor           = '';
      var   ichoices_fgColor           = '';

//    other
      var   dbtw_params       = '';
      var   wp_server         = window.location.protocol + '//' + window.location.host;
      var   wp_lose_edits_msg = 'Changing to a different edit form will discard any unsaved changes.  Proceed?';

      if (navigator.appVersion.split("MSIE")[1])
         gsb_browserIsIE55orLater = (parseFloat(navigator.appVersion.split("MSIE")[1]) > 5.4);

function before_form_change(select_object)
   {
   gform_formSelectionIndex = select_object.selectedIndex;
   }


function dbtw_form_change(select_object, action, params)
   {
   if (gsb_dataModified)
      {
      if (!confirm(wp_lose_edits_msg))
         {
         select_object.selectedIndex = gform_formSelectionIndex;
         return;
         }
      }

   var new_form = escape(select_object.options[select_object.selectedIndex].text);
   var i = new_form.indexOf( "+" );
   while ( i >= 0 )
      {
	   new_form = new_form.substring( 0, i ) +
	               "%2B" +
	               new_form.substring( i+1, new_form.length );
	   i = new_form.indexOf( "+" );
   	}

   var form_key = "EF=";
   var n1 = params.indexOf( form_key );
   var n2 = n1 + form_key.length;
   var n3 = params.indexOf( "&", n2 );
   var n4 = params.length;
   var form_change_url = action + "?AC=CHANGE_DISPLAY" +
                           params.substring( 0, n2 ) +
                           new_form +
                           params.substring( n3, n4 );
	window.location.href = form_change_url;
   }

function dbtw_prev(prev_url)
   {
   editFormSetPassword();
   editFormPurgeTextCache(1);
	window.location.href = prev_url;
   }

function dbtw_next(next_url)
   {
   editFormSetPassword();
   editFormPurgeTextCache(2);
	window.location.href = next_url;
   }

function dbtw_new_search(query_url)
   {
   editFormSetPassword();
   editFormPurgeTextCache(3);
	window.location.href = query_url;
   }

function dbtw_init_page()
   {
   editFormGetVariables();
   editFormGetPassword();
   editFormGetText();
   setFocusToFirstTabBox();
   }

function dbtw_initialize(tb_name, bUsePassword, msg_file)
   {
   // tb_name, bUsePassword are unused, and are present to be compatible with generated HTML
   // msg_file, if present and not empty, supplies a message file
   var actMsgFile = "";
   if ((arguments.length >= 3) && (msg_file.length > 0))
      actMsgFile = "&MF=" + msg_file;

   // Support setting localized strings
   document.write("\r\n<script type=\"text/javascript\" language=\"JavaScript\" src=\"" + dbtw_action +
                  "?AC=APPLET_STRINGS" + actMsgFile + "\"></" + "script>");
   }

// UTIL CODE
function strRemoveLeadingTrailingSpaces(s)
   {
	s = s.replace(/^(\s)+/, "");
	s = s.replace(/(\s)+$/, "");
	return s;
   }

function escapeEx(sz)
   {
	return ('z' + sz.replace(/[{$,%,',`,@,{,},~,!,#,(,),&,^,+,\,,=,\[,\], ]/g,"_"));
   }

function getCookie(sCookieName, defaultValue)
   {
   if (!navigator.cookieEnabled)
      {
      if (arguments.length > 1)
         return defaultValue;
      else
         return '';
      }

   var sDocumentCookie = document.cookie;
   sCookieName = escape(sCookieName);
   if (sDocumentCookie.length > 0)
      {
      sCookieNameToFind = sCookieName + "=";
      cStart = sDocumentCookie.indexOf(sCookieNameToFind);
      if (cStart != -1)
         {
         cStart += sCookieNameToFind.length;
         cEnd   = sDocumentCookie.indexOf(";", cStart);
         if (cEnd == -1)
            cEnd = sDocumentCookie.length;
         return unescape(sDocumentCookie.substring(cStart, cEnd));
         }
      else
         {
         if (arguments.length > 1)
            return defaultValue;
         else
            return '';
         }
      }
   else
      {
      if (arguments.length > 1)
         return defaultValue;
      else
         return '';
      }
   }

function getCookieEx(sCookieName)
   {
   if (!navigator.cookieEnabled)
      return '';

   if (!gsb_browserIsIE)
      return getCookie(sCookieName);
   else if (!document.all.uData)
      return getCookie(sCookieName);
   else
      {
      var sValue = '';
      sCookieName = escapeEx(sCookieName);
      uData.load("uData");
      sValue = uData.getAttribute(sCookieName);
      if (sValue == null || sValue == "null" || sValue == "" || sValue.indexOf("undefined") >= 0 || sValue.lastIndexOf("=") == sValue.length - 1)
         sValue = "";
      else
         sValue = unescape(sValue);
      // alert('Egetting "' + sCookieName + '" with "' + sValue + '"');
      return sValue;
      }
   }

function setCookie(sCookieName, sValue, iMinutesToSave)
   {
   if (!navigator.cookieEnabled)
      return;

   sCookieName = escape(sCookieName);
   sValue = escape(sValue);

   var sExpires = "";
   var sCookie  = "";

   if (iMinutesToSave == -1)
      return;
   else if (iMinutesToSave > 0)
      {
      var exp = new Date();
      var newExpTime = exp.getTime() + ( iMinutesToSave * 60 * 1000 );
      exp.setTime(newExpTime);
      sExpires = "; expires=" + exp.toGMTString();
      }
   else if (iMinutesToSave == -2)
      {
      var nextYear = new Date();
      nextYear.setFullYear(nextYear.getFullYear() + 1);
      sExpires = "; expires=" + nextYear.toGMTString();
      }
   sNewCookie = sCookieName + "=" + sValue + sExpires + "; path=/";
   document.cookie = sNewCookie;
   }

function setCookieEx(sCookieName, sValue)
   {
   if (!navigator.cookieEnabled)
      return;
   if (!gsb_browserIsIE)
      setCookie(sCookieName, sValue, 0)
   else if (!document.all.uData)
      setCookie(sCookieName, sValue, 0)
   else
      {
      sValue = escape(sValue);
      if (sValue.length > 65000)
         return;
      sCookieName = escapeEx(sCookieName);
   	uData.setAttribute(sCookieName,sValue);
   	uData.save("uData");
      }
   }

function editRecordCancel(back)
   {
   setCookieEx('erc_state','');
   if (back == 0)
      window.close();
   else
      history.go(back);
   }

// FORM INIT CODE
function setFocusToFirstTabBox()
   { // FF
   if (!gsb_setFocusToFirstTabBox)
      return;

   var formObj     = document.edit_form;  if (!formObj) return
   var formLength  = formObj.elements.length;
   var tabIndex    = -1;

   // set the focus to the first box in the tab order
   if ((gform_AC == 'DELETE') && (gform_nFirstPwBox > -1))
      tabIndex = gform_nFirstPwBox;
   else if (gform_nFirstTabOrderBox > -1)
      tabIndex = gform_nFirstTabOrderBox;

   if (tabIndex > -1)
      {
      formObj.elements[tabIndex].focus();
      gsb_setFocusToFirstTabBox = false;
      }
   }

function editFormSetPassword()
   {
   if (!navigator.cookieEnabled)
      return;

   var sPassword     = '';
   var sPwCookieName = '';

   sPwCookieName = gform_CookieNamePrefix + 'pw';

   // does the form have a INPUT type=PASSWORD box?
   // if so, save it; if not, create a fake PW for the form to save
   // which is a flag for editFormGetText()
   if (gform_nFirstPwBox > -1)
      {
      var formObj       = document.edit_form;  if (!formObj) return
      var formLength    = formObj.elements.length;

      formObj.elements[gform_nFirstPwBox].value = strRemoveLeadingTrailingSpaces(formObj.elements[gform_nFirstPwBox].value);
      sPassword = formObj.elements[gform_nFirstPwBox].value;
      }

   // to know whether or not we should restore the text we must ALWAYS save a password
   // so if the user didn't enter one, or there is none on the form, save a fake one
   if (sPassword == '')
      {
      if (gform_Password > '')
         sPassword = gform_Password
      else
         sPassword = 'mvilyf'; // pw cannot be ''
      }

   // always store PW in real cookie (not .SetAttribute)
   // this will ensure that PW (and therefor by design, record text, and qbe search criteria)
   // will expire when browser session ends
   setCookie(sPwCookieName, sPassword, 0);
   }

function editFormSetText()
   {
   if (!navigator.cookieEnabled)
      return;

   var formObj     = document.edit_form;  if (!formObj) return
   var formLength  = formObj.elements.length;
   var sText = '';
   var sTxCookieName = '';

   for (var i=0; i<formLength; i++)
      if (formObj.elements[i].type)
         if (formObj.elements[i].type.substring(0,4) == "text")
            if (formObj.elements[i].name.toUpperCase().substring(0,2) == "EI")
               sText += formObj.elements[i].name.toUpperCase() + 'r&m:[' + formObj.elements[i].value + ']:r&m';

   sTxCookieName = gform_CookieNamePrefix + 'txe';
   setCookieEx(sTxCookieName, sText);
   setCookieEx('erc_state', gform_MV);
   }

function editFormSetData()
   { // FF
   editFormSetPassword();
   editFormSetText();
   }

function editFormGetVariables()
   {
   var   formObj    = document.edit_form;  if (!formObj) return
   var   formLength = formObj.elements.length;

   // these help us stop looking once we found the setting
   var   bFoundBoxAutoFormat    = false;
   var   bFoundBoxHighlighting  = false;
   var   bFoundSingleRecordView = false;

   // helps find the first pw box
   var   sPassword             = '';
   var   firstPasswordBox      = -1;
   var   bFoundPassword        = false;
   var   bFoundHiddenPassword  = false;
   var   bFoundBMX             = false;
   var   bFoundOEH             = false;
   var   bFoundOEX             = false;

   // helps find the first box in tab order
   var   tabIndex             = -1; // help the find the lowest formObj.elements[i].tabIndex
   var   firstTabOrderBox     = -1; // once the loop if complete, the lowest formObj.elements[i].tabIndex

   // local variables
   var   sElementName      = '';
   var   sElementValule    = '';
   var   sElementValuleEx  = '';
   var   sElementType      = '';

   // this is what we hope to find by looping through this form
   //    the first box in the tab order
   //    the name of the cookie to read (in the "QS" name/value pair)
   //    the location of the password input, and it's value (in the "ID" name/value pair)
   //
   for (var i=0; i<formLength; i++)
      {
      if (formObj.elements[i].type)
         {
         sElementName    = formObj.elements[i].name.toUpperCase();
         sElementNameEx  = formObj.elements[i].name.toUpperCase().substring(0,2);
         sElementValue   = formObj.elements[i].value;
         sElementType    = formObj.elements[i].type.toLowerCase().substring(0,4);

         if (sElementType == "text")
            {
            if (sElementNameEx == "EI")
               {
               if (formObj.elements[i].tabIndex > 0)
                  if ((formObj.elements[i].tabIndex < tabIndex) || (tabIndex == -1))
                     {
                     tabIndex = formObj.elements[i].tabIndex;
                     firstTabOrderBox = i;
                     }
               }
            } // if (sElementType == "text")
         else if (sElementType == "hidd")
            {
            if ((sElementName == "AC") && (gform_AC == ''))
               gform_AC = sElementValue.toUpperCase();

            else if ((sElementName == "TN") && (gform_TN == ''))
               gform_TN = sElementValue.toUpperCase();

            else if (sElementName == "BG")
               gform_BG = sElementValue;
            else if (sElementName == "FG")
               gform_FG = sElementValue;

            else if (sElementName == "MV")
               {
               gform_MV = sElementValue;
               }

            else if ((gform_CookieNamePrefix == '') && (sElementName == "QS"))
               gform_CookieNamePrefix = escapeEx(sElementValue.toLowerCase());

            else if ((sElementName == "ID") && (!(bFoundPassword || bFoundHiddenPassword)))
               {
               sPassword = sElementValue;
               bFoundHiddenPassword = true;
               }

            else if ((sElementName == "BAF") && (!bFoundBoxAutoFormat))
               {
               gform_bBoxAutoFormat = (sElementValue == '1');
               bFoundBoxAutoFormat  = true;
               }
            else if ((sElementName == "BHL") && (!bFoundBoxHighlighting))
               {
               gform_bBoxHighlighting = (sElementValue == '1');
               bFoundBoxHighlighting  = true;
               }
            else if ((sElementName == "BMX") && (!bFoundBMX))
               {
               gform_BMX = sElementValue;
               bFoundBMX  = true;
               }

            else if ((sElementName == "OEH") && (!bFoundOEH))
               {
               gform_OEH = sElementValue;
               bFoundOEH  = true;
               }
            else if ((sElementName == "OEX") && (!bFoundOEX))
               {
               gform_OEX = sElementValue;
               bFoundOEX  = true;
               }

            else if ((sElementName == "BEK") && (gform_sBoxEntrySeparatorKey == ''))
               gform_sBoxEntrySeparatorKey = sElementValue;
            else if ((sElementName == "AEC") && (gform_cAlternateEntryChar == ''))
               gform_cAlternateEntryChar = sElementValue;

            else if ((sElementName == "SV") && (!bFoundSingleRecordView))
               {
               gform_bFromSingleRecordView = (sElementValue == '1');
               bFoundSingleRecordView  = true;
               }
            else if (sElementName == "XC")
               {
               formObj.elements[i].value = dbtw_action;
               }
            } // if (sElementType == "hidd")
         else if ((sElementType == "pass") && (!(bFoundPassword || bFoundHiddenPassword)))
            {
            if (firstPasswordBox == -1)
               if (sElementName == "ID")
                  {
                  sPassword = sElementValue;
                  firstPasswordBox = i;
                  bFoundPassword = true;
                  if (formObj.elements[i].tabIndex > 0)
                     if ((formObj.elements[i].tabIndex < tabIndex) || (tabIndex == -1))
                        {
                        tabIndex = formObj.elements[i].tabIndex;
                        firstTabOrderBox = i;
                        }
                  }
            } // if (sElementType == "pass")
         } // if (formObj.elements[i].type)
      } // for (var i=0; i<formLength; i++)

   // the values for the pw box
   if (bFoundPassword || bFoundHiddenPassword)
      {
      gform_Password = sPassword;
      if (firstPasswordBox > -1)
         gform_nFirstPwBox = firstPasswordBox;
      }

   // the first box in the tab order
   if (firstTabOrderBox > -1)
      gform_nFirstTabOrderBox = firstTabOrderBox;

   // if "QS" is not found, use the name of the form.
   if (gform_CookieNamePrefix == '')
      {
      gform_CookieNamePrefix = escapeEx(formObj.name.toLowerCase());
      gsb_cookieNameIsFormName = true;
      }

   if (gform_sBoxEntrySeparatorKey == '')
      gform_sBoxEntrySeparatorKey = '|';

   if (gform_cAlternateEntryChar == '')
      gform_cAlternateEntryChar = gform_sBoxEntrySeparatorKey;

   // over-ride this setting for DELETE
   // if (gform_AC == 'DELETE')
   //   gform_bBoxHighlightingEnabled = false;

   // if we got here from a report window, then we want to clear/purge the record text/data cache.
   // but when sEditRecordCacheState and gform_MV match, then do NOT purge because that means we are coming
   // back to this edit page from a failed attempt to save a record. in that case we must re-load
   // any missing field values from the cache back into the form.
   // (IE will loose form values changes if you click on the choices browser before you submit the form.)

   // SPR 82: use getCookie instead of getCookieEx to retrieve a cookie set in query screen [v10.0, keb]
   var bNewRecordPurgeTextCache = (getCookie('new_rec') == '1'); 
   var bEditRecordPurgeTextCache = true;

   if (window.opener)
      window.opener.page_edata = 1;
   //
   sEditRecordCacheState = getCookieEx('erc_state');
   gform_MV = gform_AC + '-' + escapeEx(gform_TN) + '-' + gform_MV;
   //
   if (sEditRecordCacheState == gform_MV)
      bEditRecordPurgeTextCache = false;
   //
   if (bNewRecordPurgeTextCache || bEditRecordPurgeTextCache)
      {
      bEditFormTextCachePurged = true;
      editFormPurgeTextCache(4);
      setCookie('new_rec', '', 0);
      }
   }

function editFormGetPassword()
   {
   var formObj     = document.edit_form;  if (!formObj) return
   var formLength  = formObj.elements.length;

   // if the form already has a password set then no need to read the cookie
   if (gform_Password.length > 0)
      return;

   if (!navigator.cookieEnabled)
      {
      editFormPurgeTextCache(5);
      return;
      }

   var sPwCookieName = '';
   var sPassword     = '';

   // note that it's possible that we are going to read the a fake PW here
   sPwCookieName  = gform_CookieNamePrefix + 'pw';
   sPassword      = getCookie(sPwCookieName);


   // if there's a PW on the form and we are not reading the fake pw then set
   if (gform_nFirstPwBox > -1)
      if (sPassword != 'mvilyf')
         formObj.elements[gform_nFirstPwBox].value = sPassword;

   // if the pw has expired then the saved text should expire too
   if (sPassword == '')
      editFormPurgeTextCache(6);
   }

function editFormGetText()
   {
   if (gform_AC == 'DELETE')
      return;

   if (!navigator.cookieEnabled)
      return;

   var   formObj    = document.edit_form;  if (!formObj) return
   var   formLength = formObj.elements.length;
   var   fm_EIx     = new Array();

   for (var i=0; i<formLength; i++)
      if (formObj.elements[i].type)
         if (formObj.elements[i].type.substring(0,4) == "text")
            if (formObj.elements[i].name.toUpperCase().substring(0,2) == "EI")
               fm_EIx[fm_EIx.length] = formObj.elements[i].name.toUpperCase() + '|' + i;

   var sTxCookieName = '';
   var sText         = '';
   var sName         = '';
   var sValue        = '';
   var nBoxIndex     = 0;
   sTxCookieName  = gform_CookieNamePrefix + 'txe';
   sText = getCookieEx(sTxCookieName);
   aNameValuePairs = sText.split(']:r&m');
   for (var i=0; i<aNameValuePairs.length; i++)
      {
      aNameValuePair = aNameValuePairs[i].split('r&m:[');
      sName = aNameValuePair[0];
      if (aNameValuePair[1])
         sValue = aNameValuePair[1];
      else
         sValue = '';
      if (sName > '')
         {
         for (var j=0; j<fm_EIx.length; j++)
            {
            if (fm_EIx[j].indexOf(sName+'|') == 0)
               {
               nBoxIndex = Number(fm_EIx[j].split('|')[1]);
               formObj.elements[nBoxIndex].value = sValue;
               }
            }
         }
      }
   }

function editFormPurgeTextCache(callerID)
   {
   var sTxCookieName = '';

   sTxCookieName = gform_CookieNamePrefix + 'txe';
   setCookieEx(sTxCookieName, '');
   gsb_dataModified = false;
   }

function disableControls(bDisabled)
   {
   var formObjs = document.forms;  if (!formObjs) return

   if (formObjs["dbtw_ID_Toolbar_Top"])
      {
      toolbarObj = formObjs["dbtw_ID_Toolbar_Top"];
      for (var j=0; j<toolbarObj.length; j++)
         if (toolbarObj[j])
             toolbarObj[j].disabled = bDisabled;
      }

   if (formObjs["dbtw_ID_Toolbar_Bottom"])
      {
      toolbarObj = formObjs["dbtw_ID_Toolbar_Bottom"];
      for (var j=0; j<toolbarObj.length; j++)
         if (toolbarObj[j])
             toolbarObj[j].disabled = bDisabled;
      }
   }

function dbtw_terminate_page()
   {
   close_popUpWindow();
   }

var wtWindow = Object();

function close_popUpWindow()
   {
   if (wtWindow)
      if (wtWindow.close)
         wtWindow.close();
   }

function open_popUpWindow(text)
   {
   if (window)
		{	
		var screenHeight = window.screen.availHeight; // .height;
		var screenWidth  = window.screen.availWidth;  // .width;

		placementX = (screenWidth/2)-((300)/2)-50;
		placementY = (screenHeight/2)-((100)/2);

		var sFeatures = "dialogHeight:100px; " +
						"dialogWidth:300px; " +
						"dialogLeft:" + placementX.toString() + "px; " +
						"dialogTop:"  + placementY.toString() + "px; " +
						"center:yes;help:no;resizable:no;status:no;";

		wtWindow = window.open('','wtWindow', 'width=300,height=100,left='+placementX+',top='+placementY);
		wtWindow.document.write('<html><title>'+dbtw_prod+'</title>');
		wtWindow.document.write('<head></head>');
		wtWindow.document.write('<body style="border:0px"><br /><h2><center>'+text+'</center></h2></body>');
		wtWindow.document.write('</html>');
		}
   }

function formSubmit()
   {
   editFormSetData();
   disableControls(true);
   setTimeout('open_popUpWindow("Updating record...");', 1000);
   }

function newFormSubmit()
   {
   formSubmit();
   }

function editFormSubmit()
   {
   setCookieEx('rsST', '1'); // flag to indicate a refresh of the report page is now needed
   formSubmit();
   document.edit_form.submit();
   }

function editFormReset()
   {
   document.edit_form.reset();
   editFormGetPassword();
   editFormPurgeTextCache(0);
   }

/////
//
// BOX CONTENT CODE
//
function editBoxAutoFormat(value, bCancelAutoFormat)
   {
   if (gform_cAlternateEntryChar == '') // safety
      return value;

   var sv = value;

   if (gform_cAlternateEntryChar == '|')     //   \/.*+?|(){}[]
      eCharEscape = "\\" + gform_cAlternateEntryChar;
   else
      eCharEscape = gform_cAlternateEntryChar;

   var re2 = new RegExp("(\r\n" + eCharEscape + "){1,}","g");  // remove all line breaks before entry marks
   var re7 = new RegExp("["     + eCharEscape + "]{1}","g");   // restore line breaks before bullets
   var re8 = new RegExp("("     + eCharEscape + "\r\n)");      // insert space between bullet and line break (SPR 1315)

   sv = sv.replace(re2, gform_cAlternateEntryChar);
   if (gform_bBoxAutoFormat && (!bCancelAutoFormat))
      {
      sv = sv.replace(re7, "\r\n" + gform_cAlternateEntryChar);
      if (sv.length > 1)                                       // remove line break before first bullet if present
         if (sv.indexOf("\r\n") == 0)
            sv = sv.slice(2);
      }

   // put the first entry sep back back if we need one
   if (sv.length > 1)
      if (sv.charAt(0) != gform_cAlternateEntryChar)
         if (sv.indexOf(gform_cAlternateEntryChar,1) > 0)
            sv = gform_cAlternateEntryChar + sv;

   sv = sv.replace(re8, gform_cAlternateEntryChar + " \r\n");   // insert space between bullet and linebreak (SPR 1315)

   return sv;
   }

function formatBoxContents(element)
   {
   element.value = editBoxAutoFormat(element.value, false)
   }

// input/textarea box events

// onFocus
function bf(element, boxLineCount, boxMinLines, boxMaxLines)
   {
   var bDefaultGrowSettings = false;

   gbox_bAutoResize = false;
   gbox_bMaxResize  = false;

   gbox_nLineCount = boxLineCount;
   gbox_nMinLines  = boxMinLines;
   gbox_nMaxLines  = boxMaxLines;

   element.style.zIndex = 1;

   if (gform_bBoxHighlighting && gform_bBoxHighlightingEnabled)
      {
      gbox_styleBorderStyle = element.style.borderStyle;
      gbox_styleBorderWidth = element.style.borderWidth;
      element.style.borderStyle = "solid"; // "solid double"
      if (gbox_styleBorderWidth == "0px")
         element.style.borderWidth = "1px";
      else
         element.style.borderWidth = "2px";
      }

   if (!gsb_browserIsIE)
      return;

   if (gbox_nLineCount > gform_BMX)
      {
      bDefaultGrowSettings = false;
      gbox_styleHeight = element.style.height;
      }
   else if ((gbox_nMinLines == gbox_nMaxLines) && (gbox_nMinLines > 0))
      bDefaultGrowSettings = false;
   else if ((gbox_nLineCount < gbox_nMaxLines) || (gbox_nMaxLines == 0))
      bDefaultGrowSettings = true;
   // else if ((gbox_nMinLines == gbox_nMaxLines) && (gbox_nMinLines > 0))
   //    bDefaultGrowSettings = false;
   // else if (gbox_nLineCount >= gbox_nMaxLines)
   //    bDefaultGrowSettings = false;

   if (bDefaultGrowSettings == true)
      {
      gbox_bAutoResize = true;
      gbox_styleHeight = element.style.height;
      if (gsb_browserIsIE55orLater)
        element.style.posHeight = 0;
      }
   }

// onBlur
function bb(element)
   {
   element.style.zIndex = 0;

   if (!gsb_browserIsIE)
      return;

   if (gform_bBoxHighlighting && gform_bBoxHighlightingEnabled)
      {
      element.style.borderStyle = gbox_styleBorderStyle;
      element.style.borderWidth = gbox_styleBorderWidth;
      }
   if ((gbox_bAutoResize || gbox_bMaxResize) && gsb_browserIsIE55orLater)
      element.style.height = gbox_styleHeight;
   if (!gsb_AutoFormat_inProgress)
      if (gform_bBoxAutoFormat)
         formatBoxContents(element);
   }

// onChange
function bc()
   {
   gsb_dataModified = true;
   }

// onKeyUp
function ku(element)
   {
   if (gsb_entrySepKeyPressed)
      {
      if (gform_bBoxAutoFormat)
         {
         formatBoxContents(element);
         
         // select space found immediately after a bullet (SPR 1315, v10.0, keb)
         // this ensures that text typed by the user will appear next to the new bullet
         if (element.createTextRange)
            {
            var txtRange = element.createTextRange();
            if (txtRange.findText(gform_cAlternateEntryChar + " "))
               {
               txtRange.moveStart("character", 1);
               txtRange.select();
               }
            txtRange.collapse();
            }
         }
      gsb_entrySepKeyPressed = false;
      }
   }

// onKeyPress
function kp(element)
   {
   var keyChar = String.fromCharCode(event.keyCode);

   if (keyChar == gform_sBoxEntrySeparatorKey)
      {
      event.keyCode          = gform_cAlternateEntryChar.charCodeAt(0);
      gsb_entrySepKeyPressed = true;
      }
   else
      gsb_entrySepKeyPressed = false;
   }

var icWindow = Object();

// choices list
var today      = new Date();
var OpenerName = today.getTime();
var win        = null;

function NewWindow(mypage,myname,w,h,pos,infocus)
{
   if (pos == "random")
      {
      myleft = (screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
      mytop = (screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
      }
   if (pos == "center")
      {
      myleft = (screen.width)?(screen.width-w)/2:100;
      mytop = (screen.height)?(screen.height-h)/2:100;
      }
   else if((pos!='center' && pos!="random") || pos==null)
      {
      myleft = 0;
      mytop = 20;
      }
	
   settings = "width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft +             ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes,dependent=no";
   if (win)
      win.close();
   win = window.open(mypage,myname,settings);
   win.focus();
//   win.opener.name = OpenerName;	
}

function ClosePopup()
{
   if (win != null)
      win.close();
}
// choices list
function ibc(inputBoxIx, fieldNameXML, fieldNameNonXML, listType, maxListLength, bINPF, sFormBgColor, sFormFgColor)
   {
   editFormSetText();

   // get pw from non-hidden pw input on form
   if (gform_nFirstPwBox > -1)
      {
      var formObj       = document.edit_form;  if (!formObj) return
      formObj.elements[gform_nFirstPwBox].value = strRemoveLeadingTrailingSpaces(formObj.elements[gform_nFirstPwBox].value);
      gform_Password = formObj.elements[gform_nFirstPwBox].value;
      }

   var sColors = '';
   if (gform_BG > '')
      sColors += '&BG=' + gform_BG;
   if (gform_FG > '')
      sColors += '&FG=' + gform_FG;

   gbox_inputIx         = inputBoxIx;
   gbox_choicesListType = listType;
   gbox_inputFieldNameSelected   = 0;
   gbox_maxListLength            = maxListLength;
   gbox_inputFieldNameListXML    = fieldNameXML;
   gbox_inputFieldNameListNonXML = fieldNameNonXML;
     
   var   bNewBrowser = true;
   if (listType == 3)
      bNewBrowser = false;
   var   sURL;
   
   // new index browsers (v8), incl validation lists (v9), pass display name(s) (v11)
   if (bNewBrowser)
      {
      sURL =  "/InmagicBrowse/Index_browse.aspx" +
                  '?TN=' + gform_TN +
                  '&ID=' + gform_Password +
                  '&QF=' + fieldNameXML.split('|')[0] +
                  '&QFS=' + fieldNameXML +
                  '&QDS=' + fieldNameNonXML +
                  '&IdxType=' + listType +
                  '&EI=' + inputBoxIx +
                  '&XC=' + dbtw_action +
                  sColors +
                  '&Root=' + wp_server +
                  '&Opener=' + OpenerName +
                  '&XM=1&ES=1&SV=1';
      icWindow = NewWindow(sURL,'ichoices', '450','300','center','front');
      }
   else
      {
      var sAC  = '';
      var sIC  = '';

	   // bINPF not used, retained in parameter list for backwards compatibility
   	
      if ((arguments.length > 4) && (maxListLength > 0))
         sIC = '&IC=' + maxListLength;
      if (arguments.length > 6)
         ichoices_bgColor = sFormBgColor;
      if (arguments.length > 7)
         ichoices_fgColor = sFormFgColor;

      window.status = '';

      if (listType == 2)
         {
         sAC = 'VALIDATION_LISTS';
         gbox_includeNonPreferredTerms = 0;
         }
      else
         {
         sAC = 'VALIDATION_LISTS_THES';
         gbox_includeNonPreferredTerms = 1;
         }

      var sEncoding = '';
      if (gform_OEH > '')
         sEncoding += '&OEH=' + gform_OEH;
      if (gform_OEX > '')
         sEncoding += '&OEX=' + gform_OEX;

      var sURL = dbtw_action +
                     '?TN=' + gform_TN +
                     '&ID=' + gform_Password +
                     '&FN=' + fieldNameXML +
                     '&XM=1&ES=1&SV=1' + // '&ES=1&SV=1' needed if there's a WP error
                     //'&XS=' + wp_server + dbtw_xsl + 'ichoices.xsl' + sIC +
                     '&XS=ichoices' + sIC +
                     '&AC=' + sAC +
                     sEncoding +
                     sColors;

      var   screenWidth    = window.screen.availWidth;
      var   screenHeight   = window.screen.availHeight;
      var   placementX     = (screenWidth/2)-((400)/2);
      var   placementY     = (screenHeight/2)-((350)/2);

      icWindow = window.open(sURL,'ichoices', 'resizable,width=400,height=370,left='+placementX+',top='+placementY);
      icWindow.focus();
      }
   gbox_choicesListURL  = sURL;
   }

