// Copyright © 2005 Cuadra Associates, Inc. All rights reserved.
// ca2.js
/* 
6/27/03  6:30 PM
   changed select.appendChild to select.options.add in caMakeSelections
   changed to use new Option instead of Document.get...
   changed caInitSelections to use t.options.add
7/2/03  2:30 PM
   MacIE version 1.4
10/13/03 11:50 AM
   changed caCheckDuplicates so that the word "checked" doesn't 
   appear in the function call--APB
12/9/03 3:15 PM
   merged APB change into master, instead of faulty 6/27/03 version
5/6/04 5:00 PM
   added function caResetImageCheckboxes
5/11/04 1:00 PM
  Fixed up function caResetImageCheckboxes
5/11/04 4:30 PM
  Added functions:
  caSetBlockNone
  caGetBlockNone
  caOnReturn
  caDsp  - was formerly in .htm files with name dsp
09/27/2004 - hlw modified caonReturn
10/11/2004 3:10 PM
  dab  --  replaced function caSubmit to handle locating a "Response" Iframe.  Now rely on starweb to mark
  the first window of a session to be "Main" 
10/11/2004 6:20 PM
  hlw  -- preccache buttons: picklist, minus ,plus 
10/22/2004 3:00 PM dab -- added function caSubmitIndirect 
10/25/2004 5:15 PM dab -- added function caClearFields
10/28/2004 11:00 AM hlw -- Ability to close all open windows on exit.
10/30/04 3:45 PM dab
  Modified caClearFields to make Select lists revert to default selected 
11/03/2004 9:00PM hlw Fix the closing of all open windows and fix picklist not opened
if subfield empty. This later error happens if an empty subfield picklist is clicked after a 
previous picklist has been displayed.
11/05/2004 4:30PM hlw Stops focus from leaving a subfield with an invalid value. 
11/08/2004 5:00PM hlw Use close == 'exit' and allow for exit from any window.
11/10/2004 1:20PM hlw Fix caClearFields to handle radio options and also to use default for checkbox.
11/10/2004 7:00PM dab Replace function caSubmitIndirect, add function caSubmitIndirectButton
11/30/2004 2:45PM hlw Replace caLimitLength with caLimitLengthX which works globally and only needs
					  Behavior to distinguish long text in TextArea fro regulrar text. 
12/02/2004 5:45PM  hlw 11/30/2004 comment changed to:
					  Replace caLimitLength with caLimitLengthX which works globally and only needs
					  StarWeb_Component "Field is long text field" checkbox checked to distinguish long text in TextArea fro regular text. 
					  This checkbox only appears for "Text Field" Type entry. 
		Also starweb_longfield is checked for in caLimitLengthX and 4 is added to length of each non main subfield.					  	
12/03/2004 12:50PM  hlw refocus case of paste > max. length then tab or click elsewhere.
12/09/2004 12:00PM hlw Keep lookup error values with focus until fixed  or cleared.
				       caIsSTARField moved to here from caHLWDB.js to prevent error case. 
					   Check for max length has been improved.
01/13/2005 2:30PM hlw STARWebRepeatingFieldPart move to here from caHLWDB.js
		              topFrame button clicks should be suppressed while a "rejected" value exists
					  Open windows shoudl be closed if the exit button hit in the "Main" window.
					  However at this time this is only true if the exit button is on the initially
					  launched window and in fact that window is not replaced by another "Main" window.
					  All for statements now begin with "var".
					  Field length check for long text fields can be suppresed by setting starweb_length=true.
					  This can be done using Starweb Component.
01/13/2005 5:30PM hlw interim not in STARTEAM
01/14/2005 2:45PM hlw interim not in STARTEAM
01/17/2005 3:45PM hlw interim in STARTEAM (include fix of caSetFocus to overcome purple picklist not working)
01/17/2005 3:50PM dab add boxing of focused element: caSetOnFocus caInitOnFocus caIsFocusable.  Mod
					  function caOnLoad to call caInitOnFocus.
01/18/2005 8:30PM hlw interim in STARTEAM 
01/19/2005 12:30PM hlw manually added DB's changes which were done while I was updating this .js
01/19/2005 12:30PM hlw interim in STARTEAM
01/20/2005 5:45PM hlw interim in STARTEAM fixes problems in Subjects & Thesaurus reported by DB on 01/19/2005
				and  Moved caxSaveCurrentElement from caDE.js to ca2.js
01/21/2005 2:00PM Fixed bug in checking for dirty records in which a canceled record was considered to be 
clean(with confirmation message).
01/25/2005 10:30AM hlw  Only reedit by message action will allow picklist to come up if on change is caused 
						by pressing the picklist button and an error is discovered. 
						Having  the picklist button and a subfield both be framed at the same time should be fixed,
						but this was done in a kluge manner.
						(This problem, seemingly caused by alert messages in the execute stream may be revisited.)
02/05/2005        hlw New Controlled Field Design						
02/07/2005 1:00PM hlw Moved caEstablishElement from caHLWDB.js to ca2.js
02/11/2005        hlw Improved length check by reducing the text exceeding the max. to be reduced by the excess and not to 1000 chars.
02/11/2005        hlw caCheckForDirt uses window reference for input argument and returns "Dirty" aor null.
02/13/2005        hlw If listbox, checkbox or radio button causes max. length limit to be exceeded then the prior setting is used with a message.						
02/16/2005        hlw use db's new caWaitAndCopy, comment out but keep for now paste handlers.
02/23/2005        hlw Pre submit check of uppercase and numeric fields. Remove caLimitLengthAll, caLimitLengthY, caPasting and caBeforePasting.
02/24/2005        hlw Remove commented out caValidate
03/04/2005        hlw Added caGetMessage calls
03/09/2005        hlw Added caLimitLength fn. Does nothing but allows existing .htm's which have this call to work without error
03/10/2005        hlw caCheckInsDelOcc is called globally. Function sees if user wants to insert/delete occurrences.
03/14/2005        hlw Add docevent4: var ret = caDateValidateKey(event);
					  Also set "ERROR" return for caLimitLengthX and check for this return code.
03/16/2005		  dab Changes to make Item List selection propagate to all windows. 
03/29/2005        hlw Comment out __XBACK and STOP_MULTIPLE_ERRORS 
04/22/2005        hlw Add caImageCheckX which is caImageCheck from caDE.js but is needed to
					  accommadate the new object which calls caImageCheckX. Note for some unknown
					  reason Dreamweaver would not allow the additional arguments (4 & 5) for caImageCheck
					  in the new object (caAddRemoveFromList).
06/22/2005		  hlw Note that record is dirty if a non-blank row is deleted.
06/23/2005		  hlw Redundant caImageCheckX functions removed.
					  Note that whatever the reason for renaming caImageCheck to caImageCheckX no longer applies,
					  so even though both functions are retained the extension object now use caImageCheck.
					  All references to caImageCheckbox have been removed as this behaviot is to be deleted.
06/29/2005        hlw Drop use of caGetBlockDisplayType.
                      Add caMultiExpandContract(namex) to handle checkbox that opens/closes blocks
07/08/2005		  dab Changes to allow multiple session per pc.  Revision 55.
					  *Must* be used with starweb 5.0.53 or later.
*/

// NN6 document.all equalizer
if (!document.all) {
	Node.prototype.__defineGetter__("all", function() {
		if (document.getElementsByTagName("*").length) {
			switch (this.nodeType) {
				case 9:
					return document.getElementsByTagName("*")
					break
				case 1:
					return this.getElementsByTagName("*")
					break
			}
		}
		return ""
	})
	Node.prototype.__defineSetter__("all", function() {})
}

// NN6 innerText and outerHTML equalizer
if ( typeof HTMLElement != "undefined" ) {
	HTMLElement.prototype.__defineSetter__("innerText", function (txt) {
		var rng = document.createRange()
		rng.selectNodeContents(this)
		rng.deleteContents()
		var newText = document.createTextNode(txt)
		this.appendChild(newText)
		return txt
	})
	HTMLElement.prototype.__defineGetter__("innerText", function () {
		var rng = document.createRange()
		rng.selectNode(this)
		return rng.toString()
	})
	HTMLElement.prototype.__defineSetter__("outerHTML", function (html) {
		var rng = document.createRange()
		rng.selectNode(this)
		var newHTML = rng.createContextualFragment(html)
		this.parentNode.replaceChild(newHTML,this)
		return html
	})
	HTMLElement.prototype.__defineGetter__("outerHTML", function() {return ''})
}


var lcount = 0;
//var STOP_MULTIPLE_ERRORS = 0;
var SAVE_EVENT;
var SAVE_INITIAL_LIST_BOX_INDEX = -1;
var focus_elementx;
var save_picklist = "";
//var __XBACK;
function caSubmit(fn,act,a1,a2,a3,tar,close,checker,op)  {
	//alert ("In caSubmit") ;
	if(window.name == "topFrame")
	{
 		if (top.NOBUTTONCLICKS)  // topFrame buttons effectively disabled
 		{ 
 			return;
 		}
	}
	if ( ! top.caWindows ) top.caWindows = [top] ;  ///////////////// in case we're all alone in the world.
	///////////////  reformated to make more readable, + check for null
	if ( close == 'exit' ) {
	// loop thru and find loaded (data entry windows)
	  for ( var ix = 0 ; ix < top.caWindows.length ; ix++) {
		var curWindow = top.caWindows[ix] ;
		if ( ! curWindow || curWindow.closed ) continue ;
		//if ( curWindow.caDataEntryState != "Loaded") continue ;
		if ( typeof curWindow.caDataEntryState == 'undefined' ) continue ;  // No edit record
		if ( curWindow.caDataEntryState == "None" ) continue ;		 		// No edit record
		if (caCheckForDirt(curWindow) == "Dirty") curWindow.caDataEntryState = "Dirty";	
		if (curWindow.caDataEntryState == "Dirty") {
		  if (confirm("Do you want to Cancel changes to record already opened?")) {
			curWindow.caIsAuthorizedUnload = true ;
			curWindow.close();
			// Worry about what effect this has if Exit on this window later
		  }
		  else {
			curWindow.focus();			
			return;
		  }
		}
		else {  // caDataEntryState != "Dirty"
		  // Users must do Done or Save themselves.
		  if (confirm("Do you want to continue editing a clean record?")) {
			curWindow.focus();
			return;
		  }
		  else {
			curWindow.caIsAuthorizedUnload = true ;
			curWindow.close();
		    // Worry about what effect this has if Exit on this window later
		  }
		}  // else caDataEntryState != "Dirty"
	  } // for all windows
	  // Close any remaining windows
 	  caCloser(top.caWindows);
	}
	else { // not close=exit
	  // If window being submitted is a Loaded Data Entry Window then set its dirty flag
	  if ( top.caDataEntryState == "Loaded" && caCheckForDirt(top) == "Dirty" ) {
		top.caDataEntryState = "Dirty";			
	  }
	  // If target is Data Entry Window (from another page)
	  if ( caSubmit.arguments.length > 8 ) {
		// Find tar.name in caWindows
		for ( var ix = 0 ; ix < top.caWindows.length ; ix++) {
		  var curWindow = top.caWindows[ix] ;
		  if ( ! curWindow ) continue ; ////////////////////////////
		  if ( curWindow.closed ) continue ;
		  if ( curWindow.name != tar ) continue ;
		  var des = curWindow.caDataEntryState ;
		  if ( des == "Loaded" || des == "Dirty" || des == "Clean" ) {  // which already has a document
			alert(caGetMessage("caDataEntryWindowInUse")) ;
			curWindow.focus() ;
			return ;
		  }
		  curWindow.caIsAuthorizedUnload = true ;
		  break ;  // found our window, and it's ok
		} // loop through windows
	  } // target DE Window from another page
	} // else close = exit
	
  if ( checker == true && ! caValidate(fn) ) return ; ///////////// note added argument(fn) !!!
  //////////// end reformatting
  
  if ( arguments.length > 8 ) {
    var wx = window.open('',tar,op) ;
	caUpdateWindowLists(wx) ;
  }
  //if ( tar == 'Main' ) {	// dat 3/16/05 'Main' doesn't get options, must test explicitly
  if ( isMainName(tar) ) {  // Main now of form MainNNN
	var wx = window.open('',tar) ;
	caUpdateWindowLists(wx) ;
  }
  
  if ( close == 'only' ) {
	top.caIsAuthorizedUnload = true ;  //////////////// turn off questions.
    top.window.close ; return ;
  }
  fn.document.__form.__action.value = act;
  fn.document.__form.__a1.value = a1;
  fn.document.__form.__a2.value = a2;
  fn.document.__form.__a3.value = a3;
  fn.document.__form.__dirtyFlag.value = top.caDataEntryState ;  ///////////////////////////
  if ( tar == "Response" ) {  // Paste from picklist
	var foo = top.opener.frames["Response"] ;
	var tempTar = "Response12345" ;
	foo.name = tempTar ;
	//window.opener.name = tempTar ;
	fn.document.__form.target = tempTar ;
	/* This code not needed:  we're keeping the current window. ////////////////////
  	var otherWindow = caFindFriendlyWindow() ;
  	top.isloaded = false ;
  	if ( otherWindow != null ) otherWindow.caCopyList(top) ;
	*/
	//top.caIsAuthorizedUnload = true ;  //////////////// turn off questions.
    fn.document.__form.submit() ;
	foo.name = "Response" ;
  }
  else {  // not a Paste from picklist
    fn.document.__form.target = tar;
	if (caSubmit.arguments.length < 9) {
  	  var otherWindow = caFindFriendlyWindow() ;
  	  top.isloaded = false ;
  	  if ( otherWindow != null ) {
		otherWindow.caCopyList(top) ;
	  }
	}
	top.caIsAuthorizedUnload = true ;  //////////////// turn off questions.
    fn.document.__form.submit() ;
	top.caDataEntryState = "None" ;   ///////////// Clear for the next document in
  }
  if ( close.toLowerCase() == 'true' ) {
    top.window.close();
  }
  
} 
// get actual button to submit from selectlist value.
// The first argument should be 'this' (no quotes) 
// The 2nd argument is optional, if present, must be of form 'parent.frameName' (no quotes)
function caSubmitIndirect(selectList,frameAddr) {
  if ( selectList.tagName != 'SELECT' ) {
    //alert("Submit Indirect not in SELECT element!") ;
	alert(caGetMessage("caSubmitIndirectFails"));	
	return ;
  }
  if ( arguments.length < 2 ) frameAddr = self ;
  var button = frameAddr.document.all[selectList.value] ;
  if ( ! button ) alert("button for "+selectList.value+" not found!") ;
  button.click() ;
}


// Execute a remote button
// The 1st argument is the name (in quotes) of the button to be clicked.
// The 2nd argument is optional, if present, must be of form 'parent.frameName' (no quotes)
function caSubmitIndirectButton(target,frameAddr) {
  if ( arguments.length < 2 ) frameAddr = self ;
  var button = frameAddr.document.all[target] ;
  if ( ! button ) alert("button for "+target+" not found!") ;
  else button.click() ;
  return ;
}
// clear a list of fields on the page -- variable number of arguments
function caClearFields(frameName,fieldName1,fieldName2) { //...
var bradio;
  for ( var i = 1 ; i < arguments.length ; i++ ) {
    var fieldName = arguments[i] ;
	var target = frameName.document.all[fieldName] ;
	bradio = false;
	if (target.length > 0)
	{
		if (target[0].type == "radio")
		{
			bradio = true;
		}
	
	}
	if ( ! target ) alert(caGetMessage("caDataClearFields") + '"' + fieldName + '"') ;
	else {
	  if (target.type == "checkbox")
	  {
	  	target.checked = target.defaultChecked;
	  }
	  else if  (bradio)
	  {
	  	for (var y = 0; y <= target.length - 1; y++)
		{
			target[y].checked = target[y].defaultChecked
		}
	  }
	  else if ( target.tagName == 'SELECT' ) {
	  	//target.selectedIndex = -1 ;
		var optionList = target.options ;
		for ( var j = 0 ; j < optionList.length ; j++ ) {
		  optionList[j].selected = optionList[j].defaultSelected ;
		}
	  }
	  else if ( target.value ) target.value = "" ;
	}
  }
}
function caCompose(document,fieldName) {
  document.open() ;
  caDEDisplayField(document,fieldName) ;
  document.close() ;
}
function caDEDisplayField(document,fieldName) {
  var firstsf = "" ;
  var field = __Record[fieldName] ;
  document.write(field.head) ;
  var b = field.body ;
  for (var i = 0 ; i < field.occs.length ; i++ ) {
    var occ = field.occs[i] ;
    for (var j = 0 ; j < b.length ; j++ ) {
	  document.write(b[j]) ;
	  if ( j == b.length-1 ) break ;
	  var sf = b[++j] ;
	  if ( sf == "insert" ) {
	    document.write("parent.caInsert(document,'" + fieldName + "'," + i + ");") ;
		continue ;
	  }
	  if ( firstsf == "" ) firstsf = sf ;
	  document.write(" onChange=\"parent.caChange(this,'" + fieldName + "'," + i + ",'" + sf + "');\" ") ;
	  document.write(" name=\"_" + fieldName + "_" + i + "_" + sf + '"') ;
	  var subfield = occ[sf] ;
	  if ( typeof subfield != "undefined" ) {
	    document.write(" value=\"" + subfield + '"') ;
	  }
	}
  }
  document.write(field.tail) ;
  return firstsf ;
}
function caInsert(doc,fieldName,occn) {
  doc.open() ;
  var field = __Record[fieldName] ;
  for ( var i = field.occs.length ; i > occn ; i-- ) {
    field.occs[i] = field.occs[i-1] ;
	}
  field.occs[occn] = {_:""} ;
  var firstsf = caDEDisplayField(doc,fieldName) ;
  var foo = "doc.all._"+fieldName+"_"+occn+"_"+firstsf+".focus()" ;
  eval(foo) ;
  doc.close() ;
}
function caChange(fld,fieldName,occn,sf) {
  var field = __Record[fieldName] ;
  var occ = field.occs[occn] ;
  occ[sf] = fld.value ;
}
function caUpdate(fn,act,a1,a2,a3,tar,close,op)  {
  var doc = fn.document._hiddenFrame.document ;
  doc.open() ;
  doc.write(__Record.updateForm) ; // <form + <... hidden
  for ( i in __Record ) {
    if ( i == "updateForm" ) continue ;
    var field = __Record[i] ;
	for ( j = 0 ; j < field.occs.length ; j++ ) {
      var occ = field.occs[j] ;
	  for ( k in occ ) {
	    doc.write('<input type="hidden" name="') ;
		doc.write("_"+i+"_"+j+"_"+k) ;
		doc.write('" value="') ;
		doc.write(occ[k]) ;
		doc.write('">\n') ;
	  }
    }
  }
  doc.write("</form>") ;
  caSubmit(fn.document._hiddenFrame,act,a1,a2,a3,tar,close,op) ;
}
function caCheckEnter (evt,buttonName) {
  var whichCode = (window.Event) ? evt.which : evt.keyCode;
  var elem = evt.target ? evt.target : evt.srcElement ;
  if (whichCode == 13) {
    if ( buttonName.length != 0 ) {
	  if ( elem.onchange ) elem.onchange() ;	// get other events first
	  if ( elem.onblur ) elem.onblur() ;
	  document.all[buttonName].onclick() ;
	}
	if ( window.Event ) evt.which = 0 ; else evt.keyCode = 0 ;
  }
}


//following for custom report defintion pages
function isMacIE() {
	return (navigator.appName == "Microsoft Internet Explorer") && (navigator.appVersion.indexOf("Mac") != -1)
}


// initialize the selection list from (previous) remember value
function caInitSelections(target,remember) {
  var t = document.getElementsByName(target)[0] ;
  //var len = document.getElementsByName(target)[0].length;
  var r = String(document.getElementsByName(remember)[0].value) ;
  var values = r.split(";") ;
  var newItem;
  for ( var i = 0 ; i < values.length ; i++ ) {
    var curval = values[i] ;
    if ( curval != null && curval != "null" && curval.length > 0 ) {
	  newItem=caNewOption(curval,curval,false);
	  //document.getElementsByName(target)[0].appendChild(newItem);
	  //t.options.add(newItem) ;
	  if( ! isMacIE() ) document.getElementsByName(target)[0].appendChild(newItem) ;
      else t.options.add(newItem) ;
    }
  }
}

function caMakeSelections(source,target,remember) {
  var s = document.getElementsByName(source)[0] ;
  var t = document.getElementsByName(target)[0] ;
  //var len = t.length;

  var top = s.length ;
  for ( var i = 0 ; i < top ; i++ ) {
    var opt = s.options[i] ;
    if ( opt.selected != true ) continue ;
    // try .options for mac ie
	if ( ! isMacIE() ) t.appendChild(caNewOption(opt.text,opt.value,false)) ;
	else t.options.add(caNewOption(opt.text,opt.value,false)) ;
    opt.text = '>' + opt.text ;
    opt.selected = false ;
  }
  caRemember(t,remember) ;
}

function caRemoveSelections(source,target,remember) {
  var s = document.getElementsByName(source)[0] ;
  var t = document.getElementsByName(target)[0] ;
  for ( var i = t.length-1 ; i >= 1 ; i-- ) {
    if ( t.options[i].selected ) {
	  var tvalue = caStrip(t.options[i].value) ;
	  for ( var j = 0 ; j < s.length ; j++ ) {
	    if ( s.options[j].value == tvalue ) {
		  var foo = String(s.options[j].text) ;
		// Changed by CL to check for > before removing first char.
		// was:   s.options[j].text = foo.substr(1,foo.length-1);
		  if (foo.substr(0,1) == ">") s.options[j].text = foo.substr(1,foo.length-1) ;
		  else s.options[j].text = foo;
                //... end.
		  break ;
	    }
	  } 
	  if ( ! isMacIE() ) t.removeChild(t.childNodes[i]) ;
	  else t.options.remove(i) ;
	} // if selected
  }
  caRemember(t,remember) ;
}

function caNewOption(text,value,selected) {
  if ( ! isMacIE() ) {
    var newOption = document.createElement("Option") ;
    var newText = document.createTextNode(text);
    newOption.appendChild(newText);
    if(newOption.attributes.length>0){
      // For IE
      newOption.setAttribute("value",value);
	  newOption.selected=selected;
      //newOption.setAttribute("selected",selected);
    } else {
	  // For Netscape
	  newOption.value=value;
	  newOption.selected=selected;
	}
	return newOption ;
  }
  else {  // Mac IE
    var newOption = new Option(value) ;
    newOption.text = text ;
    newOption.value = value ;
    newOption.selected = selected ;
    return newOption ;
  }
}


function caMoveSelections(target,direction,remember) {
  var t = document.getElementsByName(target)[0] ;
  var index = t.selectedIndex ;
  if ( direction == 'up' ) {
    if ( index <= 1 ) return ;
    for ( var i = index ; i < t.length ; i++ ) {
      var opt = t.options[i] ;
	  if ( opt.selected ) caExchangeOption(t.options[i-1],opt) ;
	}
  }
  else if ( direction == 'down' ) {
    var top = t.length - 1 ;
    if ( t.options[top].selected ) return ;
    for ( var i = top-1 ; i >= index ; i-- ) {
      var opt = t.options[i] ;
	  if ( opt.selected ) caExchangeOption(t.options[i+1],opt) ;
	}
  }
  else if ( direction == 'top' ) {
    index=1;
    for ( var i = 1 ; i < t.length ; i++ ) {
      var opt = t.options[i] ;
      if ( ! opt.selected ) continue ;
	  if ( index < t.length - 1 ) {
	    if ( ! isMacIE() ) {
          var topOpt = t.removeChild(t.childNodes[i]);
	      t.insertBefore(topOpt,t.childNodes[index]) ; 
		}
		else {
		  t.options.remove(i) ;
		  t.options.add(opt,index) ;
		}
	  }
      index++;
    }  // for
  }
  else if ( direction == 'bottom' ) {
    bottom = t.length;
    i = 1 ;
    while ( i < bottom ) {
      var opt = t.options[i] ;
      if ( ! opt.selected ) {
	    i++ ;
	    continue ;
	  }
	  if ( ! isMacIE() ) {
	    var topOpt = t.removeChild(t.childNodes[i]) ;
        t.appendChild(topOpt) ;
        bottom-- ;
	  }
	  else {
	    t.options.remove(i) ;
	    t.options.add(opt) ;
	    bottom-- ;
	  }
    } // while
  } // direction == bottom

  caRemember(t,remember) ;
}

  
function caExchangeOption(option1,option2) {
  var ttext = option1.text ;
  var tvalue = option1.value ;
  var tselected = option1.selected ;
  option1.text = option2.text ;
  option1.value = option2.value ;
  option1.selected = option2.selected ;
  option2.text = ttext ;
  option2.value = tvalue ;
  option2.selected = tselected ;
}

function caModifySelections(target,text,remember) {
  var t = document.getElementsByName(target)[0] ;
  var index = t.selectedIndex ;
  for (var i = 0 ; i < t.length ; i++ ) {
    var opt = t.options[i] ;
	if ( ! opt.selected ) continue ;
	opt.text = caStrip(opt.text) + text ;
	opt.value = caStrip(opt.value) + text ;
	opt.selected = true;
  }
  caRemember(t,remember) ;
}

function caStrip(text) {
  var x = String(text) ;

  // Changed by CL to accomodate Field Name containing a slash.
  // was:  var ix = x.indexOf('/') ;
  var ix = x.indexOf('/Ascending') ;
  if(ix<0) ix = x.indexOf('/Descending') ;
  // ... end.

  if ( ix >= 0 ) x = x.substr(0,ix) ;
  return x ;
}

function caRemember(source,remember) {
  var x = "" ;
  for ( var i = 1 ; i < source.length ; i++ ) {
    x = x + source.options[i].text + ';' ;
  }
  //document.all[remember].value = x ;
  document.getElementsByName(remember)[0].value = x ;
}

//function caCheckDuplicates(name,value,checked) { //changes for apb
function caCheckDuplicates(elem) {
  var name, value, checked ;
  if ( arguments.length == 3 ) {
    name = arguments[0] ;
	value = arguments[1] ;
	checked = arguments[2] ;
  }
  else {
    name = elem.name ;
	value = elem.value ;
	checked = elem.checked ;
  }

  var len = document.forms[0].elements.length ;
  var i ;
  for ( var i = 0 ; i < len ; i++ ) {
    var thisElem = document.forms[0].elements[i] ;
	if ( thisElem.name == name && thisElem.value == value ) {
	  thisElem.checked = checked ;
	}
  }
}
function docEvent1() {
	var ret = caLimitLengthX(1014, event);
		if (ret == "ERROR") return;
	var ret = caCheckInsDelOcc(event);
}
function docEvent2() {
	var ret=caLimitLengthX(1014, event);
}
function docEvent3()
{
	caStartDrag();
}
function docEvent4()
{
	var ret = caDateValidateKey(event);
}

function caOnLoad() {
	//if (top.name != "Main")
	if ( ! isMainName(top.name) )
	{
		//__XBACK = top.opener.__XBACK;  // regressively revert back
		top.NOBUTTONCLICKS = false;  
	}
	else
	{
		//__XBACK = top
	}
	top.caIsAuthorizedUnload = false ;		////////////////  turn on checks for X, Next, Prev...
	if ( window.frames["Response"] ) {		////////////////
	  //alert("IsDataEntryWindow") ;
	  top.caIsDataEntryWindow = true ;
	}										///////////////
	/** no longer needed, and doesn't work if edit page not the last frame loaded
	if(top.caDataEntryStateSave)
	{
		top.caDataEntryState = top.caDataEntryStateSave;
		top.caDataEntryStateSave = "None";
	}
	else
	{
		top.caDataEntryState = "None";		
	}
	**/
	if (top.caDataEntryState == "Loaded")
	{
		image1 = new Image(12,12);
		image1.src = "Images/plus.gif"
		image2 = new Image(12,12);
		image2.src = "Images/minus.gif"
		image3 = new Image(12,12);
		image3.src = "Images/picklist.gif"
		document.onkeyup= docEvent1; // for text types elements and list boxes via keypress
		document.onclick= docEvent2;  // for radio buttons checkboxes and list boxes
		document.ondragstart = docEvent3;
		document.onkeypress = docEvent4;
	}

	if(document.getElementsByName('caRemember')[0] && document.getElementsByName('caSelections')[0]) caInitSelections('caSelections','caRemember');
	/*
	//alert("MacIE version 1.3") ;
	caInitOnFocus() ; // new 1/17/05
	caSetFocus() ;
	top.window.focus();
	top.isloaded = true ;
	*/
  if ( ! top.caIsFocused ) {  // Just do this once per window
	top.caIsFocused = true ;
	top.window.focus() ;
  }
  top.isloaded = true ;
  caInitOnFocus() ;
  caSetFocusNowait() ;  // and do the window focus *before* the field focus
}


/** old
function caSetHiddenValues(name,value,checked) {
  var len = document.forms[0].elements.length ;
  var i ;
  for ( var i = 0 ; i < len ; i++ ) {
    var thisElem = document.forms[0].elements[i] ;
	if ( thisElem.name != name || thisElem.type != 'hidden' ) continue ;
	var isChecked = false ; var compareValue ;
	if ( thisElem.value.substr(0,2) == '__' ) {
	  isChecked = false ; compareValue = thisElem.value.substring(2) ;
	}
	else {
	  isChecked = true ; compareValue = thisElem.value ;
	}
	//alert("cvalue='" + compareValue + "' isChecked=" + isChecked + " value=" + value) ;
	if ( compareValue != value || checked == isChecked ) continue ;
	if ( checked ) thisElem.value = compareValue ;
	else thisElem.value = '__' + compareValue ;
  }
}

function caSetImageCheckboxes(name,testValue,newValue,image,alt) {
  //alert("name=" + name + " value='" + value + "' image=" + image) ;
  var len = document.images.length ;
  var i ;
  for ( i = 0 ; i < len ; i++ ) {
    var thisElem = document.images[i] ;
	if ( thisElem.name != name || thisElem.type == 'hidden' ) continue ;
	if ( thisElem.value != testValue ) continue ;
	thisElem.src = image ;
	thisElem.value = newValue ;
	thisElem.alt = alt ;
  }
}
**/
/**
 * Set all image checkboxes to checked or unchecked
 **/ 
function caResetImageCheckboxes(name,image,checked) {
  var len = document.forms[0].elements.length ;
  for ( var i = 0 ; i < len ; i++ ) {
    var thisElem = document.forms[0].elements[i] ;
	if ( thisElem.name != name) continue ;
	var isChecked = thisElem.value.substr(0,2) != '__' ;
	if ( isChecked == checked ) continue ;
	if ( ! isChecked ) thisElem.value = thisElem.value.substring(2) ;
	else thisElem.value = '__' + thisElem.value ;
  }
  for ( var i = document.images.length ; --i >= 0 ; ) {
    var thisElem = document.images[i] ;
	if ( thisElem.name != name) continue ;
	thisElem.src = image ;
  }
}

function caSetHiddenValuesAndImageCheckboxes(name,value,checked,testValue,newValue,image,alt) {
  if ( ! top.caWindows ) top.caWindows = [top] ;  ///////////////// in case we're all alone in the world.
  for ( var ix = 0 ; ix < top.caWindows.length ; ix++) {
	var curWindow = top.caWindows[ix] ;
	try { if ( curWindow == null || curWindow.closed ) continue ; }
	catch (e) { continue ; }
	if ( ! curWindow.frames || curWindow.frames.length == 0 ) {
	  //alert("No frames in" + curWindow.name) ;
	  caSetHiddenValuesInDoc(curWindow.document,name,value,checked) ;
	  caSetImageCheckboxesInDoc(curWindow.document,name,testValue,newValue,image,alt) ;
	  continue ;
	}
	for ( var fix = 0 ; fix < curWindow.frames.length ; fix++ ) {
	  //alert("Frame "+fix+" in "+curWindow.name) ;
	  var curFrame = curWindow.frames[fix] ;
	  caSetHiddenValuesInDoc(curFrame.document,name,value,checked) ;
	  caSetImageCheckboxesInDoc(curFrame.document,name,testValue,newValue,image,alt) ;
	}
  }
}


function caSetHiddenValuesInDoc(doc,name,value,checked) {
  var len = 0 ;
  if ( doc.forms[0] ) len = doc.forms[0].elements.length ;
  //alert("forms[0].len = "+len) ;

  for ( var i = 0 ; i < len ; i++ ) {
    var thisElem = doc.forms[0].elements[i] ;
	if ( thisElem.name != name || thisElem.type != 'hidden' ) continue ;
	var isChecked = false ; var compareValue ;
	if ( thisElem.value.substr(0,2) == '__' ) {
	  isChecked = false ; compareValue = thisElem.value.substring(2) ;
	}
	else {
	  isChecked = true ; compareValue = thisElem.value ;
	}
	//alert("cvalue='" + compareValue + "' isChecked=" + isChecked + " value=" + value) ;
	//if ( compareValue != value || checked == isChecked ) continue ;
	if ( ! caCompareSelectionListValues(compareValue,value) || checked == isChecked ) continue ;
	if ( checked ) thisElem.value = compareValue ;
	else thisElem.value = '__' + compareValue ;
  }
}

function caSetImageCheckboxesInDoc(doc,name,testValue,newValue,image,alt) {
  var len = 0 ;
  if ( doc.images ) len = doc.images.length ;
  //alert("images.len = " + doc.images.length) ;
  for ( var i = 0 ; i < len ; i++ ) {
    var thisElem = doc.images[i] ;
	if ( thisElem.name != name || thisElem.type == 'hidden' ) continue ;
	//if ( thisElem.value != testValue ) continue ;
	if ( ! caCompareSelectionListValues(thisElem.value,testValue) ) continue ;
	thisElem.src = image ;
	thisElem.value = newValue ;
	thisElem.alt = alt ;
  }
}

function caCompareSelectionListValues(value1,value2) {
  //var re=/(.*);;*::(.*)/
  var re = new RegExp("^(.*);;.*::(.*)$") ;
  var v1 = re.exec(value1) ;
  var v2 = re.exec(value2) ;
  if ( v1 == null || v2 == null ) return v1 == v2 ;
  return v1[1] == v2[1] && v1[2] == v2[2] ;
}

function caImageCheck(obj,imChecked,imUnchecked,altChecked,altUnchecked) {
  if ( arguments.length < 5 ) {
    altChecked = "Record Selected" ;
	altUnchecked = "Record Not Selected" ;
  }
  
  var value = obj.value ;
  if ( value.substr(0,2) != '__' ) {  // currently checked
    caSetHiddenValuesAndImageCheckboxes(obj.name,value,false,value,"__" + value,imUnchecked,altUnchecked) ;
  }
  else {
	caSetHiddenValuesAndImageCheckboxes(obj.name,value.substring(2),true,value,value.substring(2),imChecked,altChecked) ;
  }
  return true ;
}
function caImageCheckX(obj,imChecked,imUnchecked,altChecked,altUnchecked) {
  if ( arguments.length < 5 ) {
    altChecked = "Record Selected" ;
	altUnchecked = "Record Not Selected" ;
  }
  var value = obj.value ;
  if ( value.substr(0,2) != '__' ) {  // currently checked
    caSetHiddenValuesAndImageCheckboxes(obj.name,value,false,value,"__" + value,imUnchecked,altUnchecked) ;
  }
  else {
	caSetHiddenValuesAndImageCheckboxes(obj.name,value.substring(2),true,value,value.substring(2),imChecked,altChecked) ;
  }
  return true ;
}

function caOnUnload() {
  //alert("top.name on unload = '" + top.name + "'") ;
}


function caSetFocus() {
  if ( document.forms.length <= 0 ) return ;
  var fe = document.forms[0].elements ;
  for ( var i = 0 ; i < fe.length ; i++ ) {
    var thisfe = fe[i] ;
    if ( thisfe.starweb_focus ) {
	  focus_elementx = thisfe;
	  setTimeout("doSelectionX()", 50);
	  break ;
	}
  }
  return ;
}

function caSetFocusNowait() {
  if ( document.forms.length <= 0 ) return ;
  var fe = document.forms[0].elements ;
  for ( var i = 0 ; i < fe.length ; i++ ) {
    var thisfe = fe[i] ;
    if ( thisfe.starweb_focus ) {
	  thisfe.focus() ;
	  break ;
	}
  }
  return ;
}

function caSetCheckboxes(name,checked) {  // checked = true/false
  //alert("name='"+name+"' checked="+checked) ;
  var fe = document.forms[0].elements ;
  for ( var i = 0 ; i < fe.length ; i++ ) {
    var thisfe = fe[i] ;
    if ( thisfe.name == name && thisfe.type == 'checkbox' ) {
	  thisfe.checked = checked ;
	}
  }
  return ;
}

function caSetChecks(checked,name) {
  caSetCheckboxes(name,checked) ;
}

function caSetChecks(checked,name) {
  caSetCheckboxes(name,checked) ;
}

function caSetBlockNone(valx, anchorname) {
  // Assumes name is unique
  var hiddenglobal = document.getElementsByName(anchorname + "_hidden_value");
  hiddenglobal[0].value = valx;
}

function caGetBlockNone(anchorname) {
  var hiddenglobal = document.getElementsByName(anchorname + "_hidden_value");
  var curValue = hiddenglobal[0].value ;
  return curValue == null ? "none" : curValue ;
}

function caOnReturn(anchorname) {
  // assumes name is unique
  var focarray = document.getElementsByName(anchorname);
  if (focarray.length == 0) return;  // hlw 09/27/2004 See Archives expand/contract

  var foc = focarray[0];
  // first get +/-   
  var  fplusminus = foc.firstChild;

  foc = document.getElementById(anchorname + '_plus_minus_list') ;	
  var curDisplayType = caGetBlockNone(anchorname) ;
  foc.style.display = curDisplayType ;
  fplusminus.innerHTML = curDisplayType == 'none' ? '+' : '-' ;
}


function caDsp(loc){
  if ( document.getElementById ) {
	var anchorname = loc.getAttribute("name") ;
    var foc = loc.firstChild ;
    foc.innerHTML = (foc.innerHTML == '+') ? '-' : '+' ;
	foc = document.getElementById(anchorname + '_plus_minus_list') ;
	//var displayType = caGetBlockDisplayType(foc) ;
	foc.style.display = (foc.style.display == 'block') ? 'none' : 'block' ;
	caSetBlockNone(foc.style.display, anchorname) ;
  }
} 

function caGetBlockDisplayType(foc) {
  return window.event ? 'block' : foc.tagName == 'TBODY' ? 'table-row-group' : 'block' ;
}

function caCloser(XWINDS) {
  for (var y = 0 ; y <= XWINDS.length - 1; y++ ) {
	if ( XWINDS[y] != null && ! XWINDS[y].closed ) {  //////////////////////////////////
	  //if (XWINDS[y].name != "Main")	{
	  if ( ! isMainName(XWINDS[y].name) ) {
		XWINDS[y].caIsAuthorizedUnload = true ; /////////////////////////////////
		XWINDS[y].close();
	  }
	}
  }
}  

function caLimitLengthX(maxLength, evt)
{
	var FIELDDATA = new  FIELDDATAX;
	evt= (evt) ? evt : (window.event) ? window.event : ""
	element = (evt.target) ? evt.target : evt.srcElement
	if (element.getAttribute("starweb_longfield") == "True") return -1;  // -1 means not valid data entry field
	if (!element.getAttribute("starweb_type")) return -1;
	/*
	if(STOP_MULTIPLE_ERRORS == 1) //Lookup started if == 1
	{
		if (caIsSTARFieldTypeClick(element)) return -1;
	
	}
	*/
	FIELDDATA.FIELDNAME = STARWebRepeatingFieldPart(element.name, "inputfieldname");
	if (FIELDDATA.FIELDNAME == "") return;
	var LGTH = caTotalLengthX(element, "WITH FLAGS", FIELDDATA);
	switch(element.getAttribute("starweb_type"))
	{
		case "Checkbox/Radio Button":
		    switch (element.type)
			{
				case "checkbox":
					break;
				case "radio":
					var buttons = new Array();
					buttons = document.getElementsByName(element.name);
					priorindex = -1;
					// Is there a prior index?
					for (var y = 0; y <= buttons.length - 1; y++)
					{
						if (buttons[y].getAttribute("PRIORINDEX") && buttons[y].getAttribute("PRIORINDEX") > -1)
						{
							var priorindex = y;
							break;
						}
					}
					if (priorindex == -1)
					{
						// No, use default as prior index
						for (var y = 0; y <= buttons.length - 1; y++)
						{
							if (buttons[y].defaultSelected)
							{
								priorindex = y;
								break;
							}
						}
					}
					break;					
			}
			break;
		case "List Box":
		    var priorindex = -1;
			if(!element.getAttribute("PRIORINDEX") )
			{
				// Set default as priorindex
				for (var jx = 0; jx < element.length; jx++)
				{
					if(element.options[jx].defaultSelected)
					{
						priorindex = jx;
						break;
					}
				}				
			}
			else
			{
				priorindex = element.getAttribute("PRIORINDEX");
			}
			break;
	}
			if (evt.type == "click" && LGTH > maxLength)
			{
					alert(caGetMessage("caListBoxMaxLengthExceeded")) ;
					//alert("Clicking this entry caused the maximum field length of " + maxLength + ", to be exceeded. Previous value will be reverted to.") ;
					switch(element.getAttribute("starweb_type"))
					{
						case "Checkbox/Radio Button":
		    				switch (element.type)
							{
								case "checkbox":
									// Revert to prior value
									element.checked = !element.checked
									break;
								case "radio":
									// set button with that index
									if (priorindex == -1)
									{
										// There was no default or prior setting
										// so undo the botton in question
										element.checked = false;
									}
									else
									{
										buttons[priorindex].checked = true;
									}
									break;
							}
							break;	
						case "List Box":
								element.selectedIndex = priorindex;
							break;
					}
					return "ERROR";
			} 
			else if (LGTH > maxLength)
			{
				if(element.getAttribute("starweb_type") == "List Box")
				{
					//alert("Selecting this entry caused the maximum field length of " + maxLength + ", to be exceeded. Previous value will be reverted to.") ;
					alert(caGetMessage("caListBoxMaxLengthExceeded")) ;
					element.setAttribute("PRIORINDEX", priorindex);
					element.selectedIndex = priorindex;
					evt.keyCode = 0;
					return "ERROR";
				}
				else if(element.type == "checkbox")
				{
					//alert("Selecting this entry caused the maximum field length of " + maxLength + ", to be exceeded. Previous value will be reverted to.") ;
					alert(caGetMessage("caListBoxMaxLengthExceeded")) ;
					element.checked = false;					
					evt.keyCode = 0;
					return "ERROR";
				}
				else
				{
					//alert("Maximum field length of " + maxLength + ", exceeded, text truncated accordingly.");
					alert(caGetMessage("caTextFieldMaxLengthExceeded")) ;
					evt.keyCode = 0;
					var delta = LGTH - maxLength;
					element.value = element.value.substr(0, element.value.length - delta);
					focus_elementx = element;
					setTimeout("doSelectionX()", 50);
					return "ERROR";

				}	
			}
			else
			{
					switch(element.getAttribute("starweb_type"))
					{
						case "Checkbox/Radio Button":
		    				switch (element.type)
							{
								case "checkbox":
									break;
								case "radio":
									// Set the "new" prior index
	  								for (var y = 0; y <= buttons.length - 1; y++)
									{
										if(buttons[y].checked) 
										{
											buttons[y].setAttribute("PRIORINDEX", y);
										}
										else
										{
											buttons[y].setAttribute("PRIORINDEX", -1);
											
										}
									}
									break;
							}
							break;
						case "List Box":
							// Set the "new" internal prior index	
							element.setAttribute("PRIORINDEX", element.selectedIndex);
							break;			
					}
			}
	return LGTH;	


} 
function caLimitLength(element, dummymaxlength)
{
// does nothing but allows existing .htm which have this call to work without error
return;
}

function caTotalLengthX(element, withflags, FIELDDATA)
{
	var SFCorOFRx = new SFCorOFR;
	var FIELDLIST_NAME = new Array();
	var FIELDLIST_LENGTH = new Array();
	var bNOTFOUND = false;
	var LGTH = 0;
	var xnm = "";
	var index;
	FIELDLIST_LENGTH[0] = 0;  // so that if nothing found it will be passed back	
  	// Now decide if this is an occurrence or a field
  	// Back up to starweb_fieldcontainer or Output Field repeater
	
	var container = caFindContainerorOutputFieldRepeater(element, SFCorOFRx);
  	if (SFCorOFRx.type == "SFC" || SFCorOFRx.type  == "OFR")
	{
		// Now search thru all children of this node
		// Search for starweb_type's which contain data
		var elems = new Array() ;
		elems[0] = container;
  		for ( var i = 0 ; i < elems.length ; i++ )
		{
    		var elem = elems[i] ;
			if (FIELDDATA.FIELDNAME == "")
			{
				// This can happen when caLimitLengthAll() is called. 
				// Because OFR's are preceded by SFC's.
				// That is we have found a SFC in the call list
				// but find that the first element is in an OFR.
				// This means that the call list will continue
				// and come to the same OFR (call list from calling function).
				if (SFCorOFRx.type == "SFC" && elem.getAttribute("starweb_type")=="Output Field Repeater")
				{
					return 0;
				}
			}
			if ( caIsSTARField(elem) )
			{
	 			// Get length of data and acumulate
				// Handle option buttons and check boxes
				if (elem.value)
				{
					// Following should only occur for SFC
					// Problem is that different fields can exist in same SFC
					if (FIELDDATA.FIELDNAME != "")  
					{
						// This takes care of name supplied case
						if (FIELDLIST_NAME.length == 0)
						{
							FIELDLIST_NAME[0] = FIELDDATA.FIELDNAME; 
							FIELDLIST_LENGTH[0] = 0;
							index = 0;
						}
					}
					else
					{
						if (FIELDLIST_NAME.length == 0)
						{
							// Initialize arrays
							FIELDLIST_NAME[0] = elem.name
							FIELDLIST_LENGTH[0] = 0;
							index = 0;
						}
						else
						{
							// Has name been previously found?
							index = -1;
							for ( var yx = 0; yx < FIELDLIST_NAME.length; yx++)
							{
								if (FIELDLIST_NAME[yx] == elem.name)
								{
									index = yx;
									break;
								}		
							}
							if (index == -1)
							{
								FIELDLIST_NAME[FIELDLIST_NAME.length] = elem.name;	
								FIELDLIST_LENGTH[FIELDLIST_NAME.length] = 0;
								index = FIELDLIST_NAME.length - 1;						
							}
								
						}
							
					}
					if ( elem.getAttribute("starweb_type") == "Checkbox/Radio Button")
					{
						{
							if (elem.checked)
							{
								FIELDLIST_LENGTH[index] = FIELDLIST_LENGTH[index] + elem.value.length;
								var subid = STARWebRepeatingFieldPart(elem.name, "subfieldid");
								if (withflags == "WITH FLAGS")
								{
									if (subid != "|" && subid != "_") FIELDLIST_LENGTH[index] = FIELDLIST_LENGTH[index] + 4;
								}
							}
								
						}
					}
					else
					{
						// For list boxes multiple selections are possible but ignore this for now.
						FIELDLIST_LENGTH[index] = FIELDLIST_LENGTH[index]  + elem.value.length;
						var subid = STARWebRepeatingFieldPart(elem.name, "subfieldid");
						if (withflags == "WITH FLAGS")
						{
							if (subid != "|" && subid != "_") FIELDLIST_LENGTH[index] = FIELDLIST_LENGTH[index] + 4;
						}	
					}
				}
			}
			var children = elem.childNodes ;
			if ( children  )
	 		{
	  			for ( var j = 0 ; j < children.length ; j++ )
	   			{
	    			var child = children[j] ;
					if ( child.nodeType == 1 ) elems[elems.length] = child ;
	  			}
			}
  		}
	}
	if (FIELDDATA.FIELDNAME != "")  
	{
		// Supplied name (call was from caLimitLengthX)
		return FIELDLIST_LENGTH[0];
	}
	else
	{
		// Call was from caLimitLengthAll
		var maxlen = 0;
		var maxelemname;
		for (var yx = 0; yx < FIELDLIST_NAME.length; yx++)
		{
			if (FIELDLIST_LENGTH[yx] > maxlen)
			{
				maxlen = FIELDLIST_LENGTH[yx];
				maxelemname = FIELDLIST_NAME[yx]
			}
		}
		FIELDDATA.FIELDNAME = maxelemname;  
		return maxlen;
		
	}	
}


function caIsSTARField(elem) {
  if ( ! elem ) return false ; /////////////////////////////
  var swt = elem.getAttribute("starweb_type") ;
  return swt == "List Box" || swt == "Text Field" || swt == "Text" || swt == "Checkbox/Radio Button" || swt == "STAR Field" ;
}

function caIsSTARFieldTypeText(elem) {
  var swt = elem.getAttribute("starweb_type") ;
  return swt == "Text Field"  || swt == "Text" || swt == "List Box";
}
function caIsSTARFieldTypeTextNoList(elem) {  // HLW 02/18/2005
  var swt = elem.getAttribute("starweb_type") ;
  return swt == "Text Field"  || swt == "Text" ;
}

function caIsSTARFieldTypeClick(elem) {
  var swt = elem.getAttribute("starweb_type") ;
  return swt == "Checkbox/Radio Button"  || swt == "ListBox";
}
function caIsSTARFieldTypeListBox(elem)
{
  var swt = elem.getAttribute("starweb_type") ;
  return swt == "ListBox";
}

function InternalTrace (msg)
{

return;  // undo //'s for production
	//"TRACETEXTAREA"
	// "_TI_1_|_TI|___IF_TI"
	var x = document.getElementsByName("TRACETEXTAREA");  // for "local" window
	//var x = __XBACK.document.getElementsByName("TRACETEXTAREA"); // for "main" window
	if(x.length == 0) return;
	lcount = lcount + 1;
    
	x[0].value =  x[0].value + top.name + " " + lcount.toString() + " " + msg + "\n";	
}
function doSelectionX()
{
	focus_elementx.focus()
	var range = focus_elementx.createTextRange();
	range.move("textedit");
	range.select();	
}
function doSelectionY()
{
	focus_elementx.focus()
}

function FIELDDATAX(FIELDNAME)
{
	this.FIELDNAME = FIELDNAME;

}
function STARWebRepeatingFieldPart(strin, part)
{
// Subfield can be | or letter
// OutputFieldName can be abcd or abcd|x
//  letter and abcd
var re11 = /_([A-Za-z0-9]{1,5})_(\d*)_([A-Za-z0-9]{1})_([A-Za-z0-9]{1,6})__([A-Za-z0-9_]+)$/
// | and abcd
var re12 = /_([A-Za-z0-9]{1,5})_(\d*)_(\|)_([A-Za-z0-9]{1,6})__([A-Za-z0-9_]+)$/
// letter and abcd|x
var re21 =  /_([A-Za-z0-9]{1,5})_(\d*)_([A-Za-z0-9]{1})_([A-Za-z0-9]{1,6}\|[A-Za-z0-9_]{1})__([A-Za-z0-9_]+)$/
// | and abcd|x
var re22 =  /_([A-Za-z0-9]{1,5})_(\d*)_(\|)_([A-Za-z0-9]{1,6}\|[A-Za-z0-9_]{1})__([A-Za-z0-9_]+)$/


var ix;
ix=0;

if (re11.test(strin))
{
	ix=11;
}
if (re12.test(strin))
{
	ix=12;
}
if (re21.test(strin))
{
	ix=21;
}
if (re22.test(strin))
{
	ix=22;
}
if (ix == 0)
{
	//alert("Internally generated name is not well formed." + " (" + strin + ")");
	return "";
}
var matchArray;

switch (ix)
{
	case 11:
		matchArray = re11.exec(strin);
		break;
	case 12:
		matchArray = re12.exec(strin);
		break;
		
	case 21:
		matchArray = re21.exec(strin);
		break;
	case 22:
		matchArray = re22.exec(strin);
		break;

}

			switch (part.toLowerCase())
			{
				case "inputfieldname": 
					return matchArray[1];
				case "occurrencenumber":
					return matchArray[2];
			    case "subfieldid":
			  		return matchArray[3];
				case "outputfieldname":
					return matchArray[4];
				case "originalname":
					return matchArray[5];		
			}	
}
function caCheckForDirt(top)
{
	var elem;
	var ax = new Array();
	if (top.caDataEntryState == "Dirty")return ; 
	if (top.DIRTY_DELETE == "Dirty")
	{
		return "Dirty";
	}
	// Find the proper frame
	for (var ty = 0; ty < top.frames.length ; ty++)
	{
		var FX = top.frames[ty].document.getElementsByTagName("IFRAME")					
		if(FX.length > 0 )
		{
			//var frame = parent.mainFrame ;
    		//var ax = frame.document.all ; 
			// or
			//ax = fn.document.all;  // works
			// or
			var fn = top.frames[ty];
			ax = fn.document.forms[0].elements;  // this is faster
			for (var ix = 0 ; ix < ax.length; ix++)
			{
				if (ax[ix].nodeType == 1)
				{
					elem = ax[ix];
					if ( caIsSTARField(elem) )
					{
						if ( elem.getAttribute("starweb_type") == "Checkbox/Radio Button")
						{
							if (elem.defaultChecked != elem.checked)
							{
								return "Dirty";;
							}
						}
						else if (elem.getAttribute("starweb_type") == "List Box")
						{
							for (var lx = 0; lx < elem.length; lx++)
							{
								if (elem.options[lx].defaultSelected != elem.options[lx].selected)
								{
									return "Dirty";;
								}
					
							}
						}
						else
						{
							if (elem.defaultValue != elem.value)
							{
								return "Dirty";;
							}
						}
					}
				}
			}
			break;  // HLW 02/17/2005
		}
	}
}


function SFCorOFR(type)
{
	this.type = type;
}
function caFindContainerorOutputFieldRepeater(element, SFCorOFRx)
{
// HLW MODIFIED 01/29/2005
	var bNOTFOUND = false;
	if ( caIsSTARField(element) ||  element.getAttribute("starweb_type") == "Output Field Repeater" || element.getAttribute("starweb_fieldcontainer"))
	{
  		// Back up to starweb_fieldcontainer or Output Field repeater
		var x = element;
 		while (x && !bNOTFOUND)
  		{
			if (x.nodeType == 1)
			{
  				if (x.getAttribute("starweb_type") == "Output Field Repeater" )
				{
					var typex = "OFR";
					bNOTFOUND = true;
					break;
				}
  				if (x.getAttribute("starweb_fieldcontainer") )
				{
					var typex = "SFC";
					bNOTFOUND = true;
					break;
				}
			}
  			x=x.parentNode;
  		}
  		if (typex == "SFC" || typex == "OFR")
		{
			SFCorOFRx.type = typex;
			return x;
		}
		SFCorOFR.type = "";
		return;
	}
}
function caStartDrag()
{
	event.dataTransfer.effectAllowed = "move";  // or "copy"
}

function caDrop(thisx)
{
	// is thisx in same field as EstablishedOutputFieldRepeaterOcc
	var name1 = thisx.getAttribute("name");
	if (EstablishedOutputFieldRepeaterOcc)
	{
		var name2 = EstablishedOutputFieldRepeaterOcc.getAttribute("name");
		var name1x = STARWebRepeatingFieldPart(name1, "inputfieldname");
		var name2x = STARWebRepeatingFieldPart(name2, "inputfieldname");
		if (name1x == name2x)
		{
			// Are we dragging up or down
			var occ1 = STARWebRepeatingFieldPart(name1, "occurrencenumber");
			var occ2 = STARWebRepeatingFieldPart(name2, "occurrencenumber");

			if (parseInt(occ1) != parseInt(occ2))
			{
				if (parseInt(occ1) > parseInt(occ2))
				{
					// downward drag, so insert after the drop row
					// Need initial row and index of row to be inserted 
					initialrow = FindOccurrenceFromElem(EstablishedOutputFieldRepeaterOcc);
					droprow = FindOccurrenceFromElem(thisx);
					// copy original row to insert
					var newrow = caxInitializeRowOcc(initialrow, droprow.sectionRowIndex + 1, true);  // don't set defaults
					caSetProps(initialrow);
					var index = parseInt(occ1);
					caSetMultiRowPart1(newrow, "renumber", index + 1); // HLW 02/21/2005
					var ret = caxDelete(initialrow);  
					caResetProps(newrow);					
					event.returnValue = false;
				}
				else
				{
					// upward drag, so insert before the drop row
					// Need initial row and index of row to be inserted 
					initialrow = FindOccurrenceFromElem(EstablishedOutputFieldRepeaterOcc);
					droprow = FindOccurrenceFromElem(thisx);
					// copy original row to insert
					var newrow = caxInitializeRowOcc(initialrow, droprow.sectionRowIndex, true );  // don't set defaults
					caSetProps(initialrow);
					var index = parseInt(occ1);
					caSetMultiRowPart1(newrow, "renumber", index );
					caResetProps(newrow);					
	   			    var ret = caxDelete(initialrow);
					caResetProps(newrow);					
					event.returnValue = false;	
				}
			}
		}
	}
}

function caSetOnFocus(elem) {
  //alert(caShowProps(elem,'x')) ;
  elem.saveOnfocus = elem.onfocus ;
  elem.saveOnblur = elem.onblur ;

    elem.onfocus = function()
 	{
 		if (this.className.indexOf(" caFocused") == -1)
		{
			if(this.tagName == "A")
			{
				if (this.outerHTML.indexOf("caExecPicklist") != -1)  // HLW 01/24/2005
				{
					if(save_picklist != "")return;
				}
			}
		
  			this.className += " caFocused" ;
			if ( this.saveOnfocus )
			{
				this.saveOnfocus() ;
			}	

			save_picklist = this;
  		}
	}
  		elem.onblur = function()
		{
		
 			if (this.className.indexOf(" caFocused") != -1)
	 		{
    			var len = this.className.length - 10 ;
				if ( len >= 0 ) this.className = this.className.substr(0,len) ;
				save_picklist = "";
 			}	
			if ( this.saveOnblur ) this.saveOnblur() ;
  		}
}

function caSetOnDrop(elem) {
  	elem.saveOndrop = elem.ondrop ;
    elem.ondrop = function()
 	{
		caDrop(this);
		if ( this.saveOndrop ) this.saveOndrop() ;
	}
}

function caInitOnFocus() {
  	var all = document.all ;
  	var len = all.length ;
  	for ( var i = 0 ; i < len ; i++ )
	{
    	var elem = all[i] ;
	 	if ( caIsFocusable(elem) ) 
	 	{
	 		caSetOnFocus(elem) ;
			{
				var attr = elem.getAttribute("starweb_type");
				if (attr)
				{
					if (attr == "Text" || attr == "Text Field")
					{
						caSetOnDrop(elem);
					}
				}
			}
  		}
	}		
}

function caIsFocusable(elem) {
  var t = elem.tagName.toUpperCase() ;
  var x = ((t == 'INPUT' && elem.type != 'hidden') || t == 'TEXTAREA' || t == 'SELECT') && ! elem.readOnly && ! elem.isDisabled ;
  if ( ! x ) x = t == 'A' || t == 'IMG' ;
  //alert("return="+x+" tag="+t+" readOnly="+elem.readOnly+" isDisabled="+elem.isDisabled+" type="+elem.type) ;
  return x ;
}
function caxSaveCurrentElement(elem)
{
	current_source = elem;
}


// Create a new window, and add it to caWindows.
function caCreateWindow(loc,name) {
  var newwin = window.open(loc,name,'width=450,height=250,menubar=yes,toolbar=yes,status=yes,scrollbars=yes,resizable=yes,dependent=yes') ;
  caUpdateWindowLists(newwin) ;
}

// Add a window to the window list, unless it's already on the list.
// If the list changes, update all windows on the list with the new list.
// Whether or not the newWindow is new, its window list must be rebuilt after it is loaded
function caUpdateWindowLists(newWindow) {
  var nextix = top.caWindows.length ;
  var listChanged = true ;
  for ( var i = 0 ; i < top.caWindows.length ; i++ ) {
    var curWindow = top.caWindows[i] ;
	if ( curWindow == top ) continue ;
	if ( curWindow && curWindow.closed ) {
	  curWindow = null ; top.caWindows[i] = null ;
	}
	if ( ! curWindow ) nextix = i ;
	if ( curWindow == newWindow ) listChanged = false ;  // Window already in list
  }
  if (listChanged) 
  {
  	top.caWindows[nextix] = newWindow ;  // our list updated.  Send to other windows.
  } 	
  caUpdateWhenLoaded(newWindow) ; // Must update new window, which has lost its list
  if ( ! listChanged )
  { 
  	return ;	  // List hasn't changed--no need to update everyone
  }
  for ( var i = 0 ; i < top.caWindows.length ; i++ ) {
    var curWindow = top.caWindows[i] ;
	if ( ! curWindow || curWindow == top || curWindow == newWindow || curWindow.closed ) continue ; 
	curWindow.caWindows = top.caWindows ;
  }
}

function caFindFriendlyWindow() {
  if ( ! top.caWindows ) top.caWindows = [top] ;	// In case we're alone...
  for ( var i = 0 ; i < top.caWindows.length ; i++ ) {
    var curWindow = top.caWindows[i] ;
	try { if ( curWindow == top || curWindow == null || curWindow.closed ) continue ; } // dab 3/11/05
	catch (e) { continue ; }
	if ( curWindow.caCopyList ) return curWindow ;  // dab 3/11/05
  }
  return null ;
}

var __oldwin ;  // need global to avoid passing argument to setTimeout.
function caWaitAndCopy() {
  if ( ! __oldwin || __oldwin.closed ) 
  {
    return ;
  }
  try {   
    if ( __oldwin.isloaded )
	 {
      __oldwin.caWindows = top.caWindows ;
      return ;
     }
	 }
  catch (e)
   {
  	//alert("Wait for change") ;
  }
  setTimeout(caWaitAndCopy,50) ;
}


// Wait 'till window is loaded, then update its caWindows.
function caUpdateWhenLoaded(windowRef) {
  __oldwin = windowRef ;
  __oldwin.isloaded = false ;   // Make sure we wait 'till a new document is loaded
  caWaitAndCopy() ;
}
// expose UpdateWhenLoaded to other windows
top.caCopyList = caUpdateWhenLoaded ;

function caShowWindows() {
  var result = "" ;
  var len = top.caWindows.length ;
  for ( var i = 0 ; i < len ; i++ ) {
    var win = top.caWindows[i] ;
	if ( win && ! win.closed ) result += " " + win.name ;
  }
  alert("Open windows are: "+result) ;
}

// Just let anyone who's interested know we're loaded
/*
function caOnload() {
  top.isloaded = true ;
}
*/

// load a new page in the current window
function caRefresh(loc) {
  //var subwin = top.caWindows[1] ;
  var otherWindow = caFindFriendlyWindow() ;
  top.isloaded = false ;
  if ( otherWindow != null ) otherWindow.caCopyList(top) ;
  location = loc ;
}

function caEstablishElement(elem)
{
	EstablishedOutputFieldRepeaterOcc = elem;
	// get to buttons
	//var x = parent.parent.topFrame.document.getElementById("InsertBefore") ;
	var parentx = parent;
	var x;
	var ix;
	for (var iy = 0; iy <= 11; iy++)
	{
		x = parentx.topFrame.document.getElementById(buttonids[iy]) ;
		ix = 0;
		while (x == null && ix < 10)   // 10 is max. no. of search levels
		{
			parentx = parentx.parent;
			x = parentx.topFrame.document.getElementById(buttonids[iy]) ;
			ix = ix + 1;

		}
		if (x )
		{
			if (elem )
			{
			
				switch(x.tagName)
				{
					case "INPUT":
						x.disabled = false
						break;
					case "A":
					    // switch to enabled button
						// if not already enabled
						if (insdel_buttons[iy % 6] == "disabled")
						{
							x.disabled = false
						}
						break;
				    case "IMG":
						if (insdel_buttons[iy % 6] == "disabled")
						{
							var fname = x.src;
							var searchfor = /gray/
							x.src = fname.replace(searchfor, "");
							// Also enable other 5 buttons to integrate code if this is a usemap case
							if (x.getAttribute("usemap") != "")
							{
								for (var iz = 0; iz <= 4; iz++)
								{
									insdel_buttons[iz] = "enabled";	
								}
							}
						}					
					    break;		
						
				}
				insdel_buttons[iy % 6] = "enabled";
			}
			else
			{
				switch(x.tagName)
				{
					case "INPUT":
						x.disabled = true
						break;
					case "A":
					    // switch to disabled button
						// if not already disabled
						if (insdel_buttons[iy % 6] == "enabled")
						{						
							//////x = x.firstChild;
							//////var fname = x.src;
							//////var searchfor = /(\..+$)/
							//////x.src = fname.replace(searchfor, "gray" + "$1");
							x.disabled = true
							
						}
						break;
					case "IMG":
						if (insdel_buttons[iy % 6] == "enabled")
						{					
							var fname = x.src;
							var searchfor = /(\..+$)/
							x.src = fname.replace(searchfor, "gray" + "$1");
							// Also disable other 5 buttons to integrate code if this is a usemap case
							if (x.getAttribute("usemap") != "")
							{
								for (var iz = 0; iz <= 4; iz++)
								{
									insdel_buttons[iz] = "disabled";	
								}
							}							
						}	
					   	break;		
				}
				insdel_buttons[iy % 6] = "disabled";
			}
		}
	}	
}	
//////////////////////////////  beginning of new code + moved caValidate(fn)
// for testing only
function caDumpElements() {
  var elems = document.forms[0].elements ;
  var result = "" ;
  for ( var i = 0 ; i < elems.length ; i++ ) {
	var elem = elems[i] ;
	result += elem.name + "; " ;
  }
  alert(result) ;
}

// Get length of data in an editable field
function caGetFieldLength(elem) {
  if ( elem.getAttribute("starweb_longfield") == "True" ) return 0 ; // no length for long fields
  var t = elem.tagName.toUpperCase() ;
  if ( t != 'INPUT' && t != 'TEXTAREA' && t != 'SELECT' || elem.isDisabled ) return 0 ; 
  if ( t == 'INPUT' && elem.type == 'button' ) return 0 ;
  if ( elem.tagName == "SELECT" ) {
	return elem.selectedIndex >= 0 ? elem.options[elem.selectedIndex].value.length : 0 ;
  }
  return elem.value.length ;
}
function caValidateLengths(fn) {
  if ( ! fn.frames["Response"] ) return null ;  // not DE form
  var form = fn.document.__form ;
  var namePattern = /(_[a-zA-Z0-9]+)_(\d+)_(.)_(.+)/;
  var curField = "" ;  // Current field in form FIELDNAME_occ#
  var curLen = 0 ;
  //alert ( "formlen="+form.elements.length ) ;
  for ( var i = 0 ; i < form.elements.length ; i++ ) {
	var elem = form.elements[i] ;
	var parts = namePattern.exec(elem.name) ;
	if ( ! parts ) continue ;
	//if ( ! namePattern.test(elem.name) ) continue ;
	var thisLen = caGetFieldLength(elem) ;
	if ( thisLen == 0 ) continue ;
	var thisField = parts[1] + '_' + parts[2] ;  //elem.name.replace(namePattern,"$1_$2") ; 
	if ( thisField != curField ) {
	  curField = thisField ;
	  curLen = 0 ;
	}
	curLen += thisLen ;
	var subfield = parts[3] ;  // elem.name.replace(namePattern,"$3")  ;
	if ( thisLen > 0 && subfield != "|" ) curLen += 4 ;
	//if ( curLen > 0 ) alert("Field="+thisField+" len="+thisLen+" tot="+curLen+" sf="+subfield) ;
	if ( curLen > 1014 ) return elem ;
  }
  return null ;
}
function caValidate(fn) {
  var rc = caValidateRequired(fn) ;
  if ( rc ) {
    rc = caValidateLengths(fn) ;
	if ( rc != null ) {
	  alert(caGetMessage("caOccurrenceTooLong")) ; 
	  rc.focus() ;
	  rc = false ;
	  return rc;
	}
	rc = caValidateTextNumeric(fn); // HLW 02/18/2005
	if ( rc != null ) {
	  //alert("numeric field = " + " contains " + '"' + rc.value + '"');
	  alert(caGetMessage("caDataEntryWindowBadNumeric")) 
	  rc.focus() ;
	  rc = false ;
	  return rc;
	}
	rc = caValidateTextUpperCase(fn); // HLW 02/18/2005
	if ( rc != null ) {
	  //alert("upper case field = " + " contains " + '"' + rc.value + '"'); 
	  alert(caGetMessage("caDataEntryTextUpperCase"));
	  rc.focus() ;
	  rc = false ;
	  return rc;
	}
	rc = true;
  }
  return rc ;
}

function caValidateRequired(fn) {
  var form = fn.document.__form ;
  var fe = form.elements ;
  for ( var i = 0 ; i < fe.length ; i++ ) {
    var thisfe = fe[i] ;
    if ( thisfe.starweb_required && ( ! thisfe.value || thisfe.value == "" ) ) {
	  alert(thisfe.starweb_required) ;
	  thisfe.focus() ;
	  return false ;
	}
  }
  return true ;
}


// Confirm a submit action
function caConfirmSubmit(cleanMessage,dirtyMessage) {
  //return true ;
  if (top.caDataEntryState == "Loaded") {
	if ( caCheckForDirt(top) ) top.caDataEntryState = "Dirty";	
  }
  if ( top.caDataEntryState == "Loaded") {
	if ( cleanMessage && cleanMessage != '' ) return confirm(cleanMessage) ;
	return true ;
  }
  if ( top.caDataEntryState == "Dirty") {
	if ( dirtyMessage && dirtyMessage != '' ) return confirm(dirtyMessage) ;
	return true ;
  }
  return true ;
}

// Get a message with the name MessageVariableName (a string)
// Returns the associated string, or the name if the string is not defined.
function caGetMessage(messageVariableName) {
  try {
    var msg = eval(messageVariableName) ;
	return msg ;
  }
  catch (e) {  }
  return messageVariableName ;
}
// invoked by any browser button (X, Next, Previous, or GoTo) that will unload the current
// document.  We must do two things:
// 1) In any case, preserve caWindows.
// 2) If we're in a Data Entry window, warn the user that his action may be lethal.
function caOnBeforeUnload() {
  if ( top.caIsAuthorizedUnload ) return ;
  if ( window.name == "Response" ) return ;
  if ( window != top ) return ; // in multi-frame environments, just do this once.

  //alert("caOnBeforeUnload in"+window.name) ;
  var otherWindow = caFindFriendlyWindow() ;
  top.isloaded = false ;
  if ( otherWindow != null ) {
	otherWindow.caCopyList(top) ;
  }

  if ( top.caIsDataEntryWindow ) {
	var foo = caGetMessage("caDataEntryUnauthorizedNavigation") ;
	if ( foo.length > 0 ) event.returnValue = foo ;
  }
}
window.onbeforeunload = caOnBeforeUnload ;
function caValidateTextNumeric(fn)
{

  if ( ! fn.frames["Response"] ) return null ;  // not DE form
  var form = fn.document.__form ;
  //alert ( "formlen="+form.elements.length ) ;
  for ( var i = 0 ; i < form.elements.length ; i++ ) 
  {
	var elem = form.elements[i] ;
	if (!caIsSTARFieldTypeTextNoList(elem)) continue;
	// Is this a numeric field?
	//onKeyPress="caTextFields(event, 'numeric')"	
	var attrx = elem.outerHTML;
	var matchPattern = /.*caTextFields.*,\s*\'numeric\'/
	var parts = matchPattern.exec(attrx) ;
	if (!parts)continue;
		if (isNaN(elem.value))
		{
			return elem;
		}
  }
  return;	
}	
function caValidateTextUpperCase(fn)
{
  if ( ! fn.frames["Response"] ) return null ;  // not DE form
  var form = fn.document.__form ;
  //alert ( "formlen="+form.elements.length ) ;
  for ( var i = 0 ; i < form.elements.length ; i++ ) 
  {
  		var elem = form.elements[i] ;
		if (!caIsSTARFieldTypeTextNoList(elem)) continue;
		var attrx = elem.outerHTML;
		var matchPattern = /.*caTextFields.*,\s*\'uppercase\'/
		var parts = matchPattern.exec(attrx) ;
		if (!parts)continue;
		
		var UC = elem.value.toLocaleUpperCase();
		if (UC != elem.value)return elem;

  }
	return;
}

function caMultiExpandContract(namex)
{
  	var locx = document.getElementsByName(namex);
  	if (locx.length == 0) return;  

  	var loc = locx[0];
	var args = caMultiExpandContract.arguments;
		if (loc.checked)
		{
			// expand
			for (var ix = 1; ix < args.length; ix ++)
			{
				foc = document.getElementById(args[ix]) ;
				foc.style.display = 'block' ;
			}		
		}	
		else
		{
			// contract
			for (var ix = 1; ix < args.length; ix ++)
			{

				foc = document.getElementById(args[ix]) ;
				foc.style.display = 'none' ;
			}
	
			
		}

}

// Check whether a string could be the name of the Main window
function isMainName(str) {
  return ( str.substr(0,4) == "Main" ) ;
}

