//---------------------------------------------
//
//	Application Specific Functions Section
//
//---------------------------------------------
/*
searchColumn
searchSort
searchCriteria
batchIndex
batchSize
categorizedColumn
PrimaryValue
EXP
CMD

editRow
requiredFields
expandAllList
PageName
printing
*/


//---------------------------------------------
// constants
//---------------------------------------------
var DIR_SITES              = '/metaframe/sites'
var DIR_WEB                = '/metaframe/shared'
var URL_SITESTAT_SERVLET   = '/metaframe/servlet/SiteStat'
var URL_UPLOAD_SERVLET     = '/metaframe/servlet/UploadServlet'
var URL_METAFRAME_SERVLET  = '/metaframe/servlet/MetaFrame'
var DIR_IMG 					= DIR_WEB + '/images'
var URL_CALENDAR 			= DIR_WEB + '/calendarNew.html'
var URL_CALCULATOR 		= DIR_WEB + '/calculator.html'
var URL_COLORS 			  = DIR_WEB + '/colors.html'
var URL_EXPORT				= DIR_WEB + '/exportDbTable.jsp'
var URL_SEARCH				= DIR_WEB + '/searchAdvanced.jsp'
var URL_LOOKUP				= DIR_WEB + '/lookup.jsp'
var URL_UPLOAD				= DIR_WEB + '/upload.jsp'
var URL_SELECTOR			= DIR_WEB + '/selector.jsp'
var URL_TEXTEDITOR		= DIR_WEB + '/textEditor.html'
var URL_VIEWER				= DIR_WEB + '/viewer.jsp'
var URL_NEWITEM				= DIR_WEB + '/addNewItem.jsp'
var URL_DIRECTORY			= DIR_WEB + '/directory.jsp'

//---------------------------------------------
//---------------------------------------------
//---------------------------------------------
//---------------------------------------------

//---------------------------------------------
// Generic methods
//---------------------------------------------

function getForm () {
  
  return document.forms[0]
}

//---------------------------------------------
function getFormElement (name) {
  
  return getForm ().elements[name]
}

//---------------------------------------------
function getTop () {
  
  if (self.parent) {
    return self.parent
  }
  return top
}
//---------------------------------------------
function doSubmit () {

  if (document.body && getTop().doScrolling) {
    getTop().scrollTop = document.body.scrollTop
    getTop().scrollLeft = document.body.scrollLeft
  }
  
  document.forms[0].submit()
}	

//--------------------------------
// This has been tested with
// - Mozilla 0.9.7
// - Opera 5.11
// - IE 5.0+  
//
function getClientRect (obj) {

  var toReturn    = new Object ()
  
  toReturn.left   = 0
  toReturn.top    = 0
  toReturn.bottom = 0
  toReturn.right  = 0
  
  if (obj) {
/*  	
    if (obj.getBoundingClientRect) {
      var rect    = obj.getBoundingClientRect ()
      rect.top    += document.body.scrollTop
      rect.bottom += document.body.scrollTop
      rect.left   += document.body.scrollLeft
      rect.right  += document.body.scrollLeft
      return rect
    }
*/    
    if (obj.offsetTop != null) {
      var parent = obj
      var msg = ''
      while (parent && parent.tagName) {
        msg += '\n' + parent.tagName + ':' + parent.offsetTop + ':' + parent.offsetHeight
        if (parent.tagName != 'SPAN'
         && parent.tagName != 'FORM'
        ) {
        	toReturn.left += Math.abs(parent.offsetLeft)
        }
//        alert (parent.tagName + ":"+ parent.offsetLeft)
        if (parent.tagName != 'TD' 
         && parent.tagName != 'TH'
         && parent.tagName != 'CENTER'
         && parent.tagName != 'SPAN'
         && parent.tagName != 'FORM'
        ) {
//        alert (parent.tagName + ":"+ parent.offsetTop)
          toReturn.top += Math.abs(parent.offsetTop)
        }
        parent = parent.parentNode
      }
      toReturn.bottom = toReturn.top
      toReturn.right = toReturn.left
      
      if (obj.offsetHeight != null) {
        toReturn.bottom += Math.abs(obj.offsetHeight)
      } else {
        toReturn.bottom += obj.style.pixelHeight
      }
      if (obj.offsetWidth != null) {
        toReturn.right += Math.abs(obj.offsetWidth)
      } else {
        toReturn.right += obj.style.pixelWidth
      }
    }
  }
//  alert (msg)
  return toReturn  
}

//---------------------------------------------
function setFormValueOrCreate (name, value) {
	var form = document.forms[0]
	if (form.elements[name]) {
		form.elements[name].value = value
	} else {
		if (canCreate) {
			if (name) {
				if (value) {
					var inp = document.createElement('input')
					inp.setAttribute('type', 'hidden')
					inp.setAttribute('name', name)
					inp.setAttribute('value', value)
					form.appendChild(inp)
				}

				// ensure that the action does not define the 
				// name-value pair, if so, remove ite
				var action = form.getAttribute('action')
				if (action) {
					if (typeof(action) == 'object') {
						action = action.nodeValue; // IE specific
					}
				}
				if (!action) {
					action = document.location.search
				}
				//action = String_remove_pair(action, name) //TODO: implement this method
				form.setAttribute('action', action)
			}
		}
		//alert ('Could not XMF_setValue("' + name + '")')
	}
}

//---------------------------------------------
function setFormValue (frame, name, value) {

	if (frame && name) {
		var element = frame.document.forms[0].elements[name]
		if (element) {
			if (element.type == 'select-one') {
				var options = element.options
				element.selectedIndex = 0
				for (var i=0;i<options.length;i++) {
				  var optVal = options[i].value.toLowerCase ()
				  var optTxt = options[i].text.toLowerCase ()
				  var toComp = value.toLowerCase ()
//				  alert (optVal + ":" + optTxt)
//				  alert (optVal +":"+optTxt+":"+value)
					if (optVal == toComp || optTxt == toComp) {
						element.selectedIndex = i;
						break
					}
				}
				
			} else if (element.length > 0) {
			  if (element[0].type == 'checkbox'
			   || element[0].type == 'radio'
			  ) {
			    for (var i=0;i<element.length;i++) {
  				  var optVal = element[i].value.toLowerCase ()
  				  var toComp = value.toLowerCase ()
//  				  alert (optVal +":"+value)
			      if (optVal == toComp) {
			        element[i].checked = true
			      } 
			    }
			  } else {
				  element.checked = value ? true : false;
				}
				
			} else if (element.type == 'checkbox') {
			  if (element.value == value) {
			    element.checked = true
			  } else {
			    element.checked = false
			  }
//				element.checked = value ? true : false
			 
			} else {
				element.value = value
			}
		}
	}
}
//---------------------------------------------
function getFormValue (frame, name, index, isLabelRequested) {

	if (frame && name) {
		var element = null
		if (frame.document.forms[0]) {
			if (frame.document.forms[0].elements) {
				element = frame.document.forms[0].elements[name]
				if (!element) {
					alert ('1 Frame_getFormValue returned null: name, index -> ' + name + ":"+ index)
					return null
				}
				if (index >= 0 && element.length) {
					if (element[index].type == 'checkbox' || element[index].type == 'radio') {
						//do not handle individual elements for checkbox and radio
					} else {
						if (element.type != 'select-one') {
							element = element[index]
						}
					}
				}
			}
		}
		if (element) {
			if (element.type == 'checkbox') {
			  if (element.checked) {
				  return element.value
				} else {
				  return ''
				}
				
			} else if (element.type == 'radio') {
			  if (element.checked) {
				  return element.value
				} else {
				  return ''
				}
				
			} else if (element.type == 'select-one' || element.type == 'select') {
				if (element.selectedIndex >= 0) {
					var soption = element.options[element.selectedIndex]
					var toReturn = soption.text
					if (soption.value != '') {
						toReturn = soption.value
						if (isLabelRequested) {
							toReturn = soption.text
						}
					}
					return toReturn;
				}
			} else if (element.length && (element[0].type == 'checkbox' || element[0].type == 'radio')) {
			  var toReturn = new String ()
				for (var i=0;i<element.length;i++) {
					if (element[i].checked) {
					  if (toReturn.length > 0) {
					    toReturn += ','
					  }
						if (isLabelRequested && document.all) {
						  toReturn += element[i].parentElement.innerText
						} else {
						  toReturn += element[i].value
						}
					}
				}
				if (toReturn.length > 0) {
  				return toReturn
  			}
				
			} else {
				//showAtts(element)
				return element.value
			}
		} else {
			alert ('Frame_getFormValue returned null: name, index -> ' + name + ":"+ index)
		}
	}
	return null
}

//-------------------
function getQueryString (ignoreCmd) {
  
  var hasCMD = true
  if (ignoreCmd && ignoreCmd == true) {
    hasCMD = false
  }
  
  var objs = document.forms[0].elements
  var toReturn = document.location.pathname
  var queryString = new String ()
  for (var i=0 ; i < objs.length ; i++) {
    var obj = objs[i]
    var name = obj.name
    var value = ''
    if (obj.type == 'button') {
    } else if (obj.type == 'select-one') {
      if (obj.selectedIndex >= 0) {
        value = obj.options[obj.selectedIndex].value
      } else {
        name = null
      }
    } else if (obj.type == 'checkbox') {
      if (obj.checked) {
        value = obj.value
      } else {
        name = null
      }
    } else if (obj.type == 'radio') {
      if (obj.checked) {
        value = obj.value
      } else {
        name = null
      }
    } else if (obj.type == 'text') {
      value = obj.value
    } else if (obj.type == 'textarea') {
      value = escape (obj.value)
    } else if (obj.type == 'hidden') {
      value = obj.value
    }
    if (name && value) {
      if (hasCMD == false && name == 'CMD') {
        continue
      } 
      if (name == 'ViewParams') { 
      	// this is to ensure that the url is not larger the 518 characters
      	// TEST: This can be reproduced by doing a search on a xolumn and pressing Print
      	continue;
      }
      if (queryString.length > 0) {
        queryString += '&'
      }
      queryString += name + '=' + escape (value)
    }
  }
  toReturn = queryString
  
  return toReturn
}

//---------------------------------------------
function isUrl (val) {
  
  if (val) {
    if (val.indexOf ('/') == 0
     || val.indexOf (':') > 0
     || val.indexOf ('.asp') > 0
     || val.indexOf ('.jsp') > 0
     || val.indexOf ('.html') > 0
    ) {
      return true
    }
  }
  return false
}

//-------------------
function getUrl () {
  
  var objs = document.forms[0].elements
  var toReturn = document.location.pathname
  var actionStr = document.forms[0].action
  
  var pos0 = actionStr.indexOf ('?')
  if (pos0 != -1) {
    actionStr = actionStr.substring (pos0+1)
  }
  var queryString = actionStr
  for (var i=0 ; i < objs.length ; i++) {
    var obj = objs[i]
    var name = obj.name
    var value = ''
    if (obj.type == 'select-one') {
      if (obj.selectedIndex > 0) {
        value = obj.options[obj.selectedIndex].value
      } else {
        name = null
      }
    } else if (obj.type == 'checkbox') {
      if (obj.checked) {
        value = obj.value
      } else {
        name = null
      }
    } else if (obj.type == 'radio') {
      if (obj.checked) {
        value = obj.value
      } else {
        name = null
      }
    } else if (obj.type == 'text') {
      value = obj.value
    } else if (obj.type == 'textarea') {
      value = escape (obj.value)
    } else if (obj.type == 'hidden') {
      value = obj.value
    }
    if (name && value) {
      if (queryString.length > 0) {
        queryString += '&'
      }
      queryString += name + '=' + value 
    }
  }
  toReturn += '?' + queryString
//  alert (toReturn)
  return toReturn
}

//---------------------------------------------
function getActionValue (name) {

	var action = document.forms[0].action
	var pos = action.indexOf ('?')
	var qs = ''
	var value = ''
	if (pos != -1) {
	  qs = action.substring (pos+1)
	  var p0 = qs.indexOf (name + '=')
	  if (p0 != -1) {
	    var p1 = qs.indexOf ('&', p0)
	    if (p1 == -1) {
	      value = qs.substring (p0 + name.length + 1)
	    } else {
	      value = qs.substring (p0 + name.length + 1, p1)
	    }
/*	    
	    if (p1 == -1) {
	      value = qs.substring (p1 + name.length + 2)
	    } else {
	      value = qs.substring (p1 + name.length + 2)
	    }
*/	    
	  }
  }
  
  return value
}

//---------------------------------------------
function openSimpleWindow (isModal, loc, strTitle) {

  var props = new Object ()
  props.height    = 1
  props.width     = 1
  props.left      = 1
  props.top       = 1
  props.scrollbars = false
  props.status    = false
  props.location  = false
  props.menubar   = false
  props.toolbar   = false
  props.resizable = false
  props.help      = false
  
  return openWindow (isModal, loc, null, props, strTitle)
/*  
	var featsStr1 = 'scrollbars=0,resizable=1,status=0,help=0,location=0,toolbar=0,titlebar=0,width=1,height=1'
  var toReturn = null
  if (isModal) {
    toReturn = window.showModalDialog (loc, null, '')
    return false;
    
  } else {
  	if (loc.length > 518) {
  		alert ('Sorry for the inconvience the IE browser cannot handle urls that are longer than 518 characters')
  		return null
  	} else {
	    toReturn = window.open (loc, strTitle, featsStr1)
  	}
  	
    toReturn.owner = self;
    self.currWindow = toReturn
    focusWindow ()
  }
  
  return toReturn
*/  
}

//---------------------------------------------
function openWindow (isModal, loc, arg, featsObj, strTitle) {

  var featsStr0 = '';//new String ()
  var featsStr1 = '';//new String ()
  
  if (featsObj) {
    if (featsObj.height) {
      featsStr0 += 'dialogHeight:' + featsObj.height + 'px;'
      featsStr1 += 'height=' + featsObj.height + ','
    }
    if (featsObj.width) {
      featsStr0 += 'dialogWidth:' + featsObj.width + 'px;'
      featsStr1 += 'width=' + featsObj.width + ','
    }
    if (featsObj.left) {
      featsStr0 += 'dialogLeft:' + featsObj.left + 'px;'
      featsStr1 += 'left=' + featsObj.left + ','
    }
    if (featsObj.top) {
      featsStr0 += 'dialogTop:' + featsObj.top + 'px;'
      featsStr1 += 'top=' + featsObj.top + ','
    }
    if (featsObj.resizable) {
      featsStr0 += 'resizable:1;'
      featsStr1 += 'resizable=1,'
    }
    if (! featsObj.status) {
      featsStr0 += 'status:0;'
      featsStr1 += 'status=0,'
    } else {
      featsStr1 += 'status=1,'
    }
    if (! featsObj.help) {
      featsStr0 += 'help:0;'
    }
    if (! featsObj.location) {
      featsStr1 += 'location=0,'
    } else {
      featsStr1 += 'location=1,'
    }
    if (! featsObj.menubar) {
      featsStr1 += 'menubar=0,'
    } else {
      featsStr1 += 'menubar=1,'
    }
    if (! featsObj.scrollbars ) {
      featsStr0 += 'scroll:0;'
      featsStr1 += 'scrollbars=0,'
    } else {
      featsStr1 += 'scrollbars=1,'
    }
    if (! featsObj.titlebar ) {
      featsStr1 += 'titlebar=0,'
    } else {
      featsStr1 += 'titlebar=1,'
    }
    if (! featsObj.toolbar ) {
      featsStr1 += 'toolbar=0,'
    } else {
      featsStr1 += 'toolbar=1,'
    }
  }
  var toReturn = null
  if (isModal) {
    toReturn = window.showModalDialog (loc, arg, featsStr0)
    
  } else {
  	if (false && loc.length > 518) {
  		alert ('Sorry for the inconvience the IE browser cannot handle urls that are longer than 518 characters. The url length given is ' + loc.length + '\nUrl:\n' + loc)
  		return null
//  		loc = unescape (loc)
//  		document.location = loc
//  		return 
  		return openWindow(true, loc, strTitle,featsStr1)
  	} else {
	    toReturn = window.open (loc, strTitle, featsStr1)
  	}
  	
    toReturn.owner = self;
    self.currWindow = toReturn
    focusWindow ()
  }
  
  return toReturn
}

String.prototype.replaceAll  			= String_replaceAll  // (toReplace, toInsert)

// --------------------------------------------------
function String_replaceAll (repStr, insStr) {

	var toReturn = new String () ;

	var currPos = 0
	var extrPos  = repStr.length
	var nextPos	 = this.indexOf (repStr, 0)
	while (nextPos != -1) {
		toReturn	 += this.substring (currPos, nextPos) ;
		toReturn	 += insStr ;
		currPos			= nextPos + extrPos
		nextPos			= this.indexOf (repStr, currPos)
	}
	toReturn += this.substring (currPos) ;
	return toReturn ;
}


//---------------------------------------------
function doReload () {
  
  var form = document.forms[0];
  var loc = new String (form.action);
  if (loc.indexOf ('?') == -1) {
    loc += '?'
  }
  if (loc.lastIndexOf ('&') != loc.length - 1) {
    loc += '&'
  }
  if (form.PrimaryValue && form.PrimaryValue.value) {
  	loc += 'PrimaryKey=' + form.PrimaryKey.value;
  	loc += '&';
  	loc += 'PrimaryValue=' + form.PrimaryValue.value;
  	loc += '&';
  	if (form.CMD.value == 'Edit') {
  		loc += 'CMD=Edit';
  	}
  } else {
	  loc += getQueryString (true)
	}

  document.location = loc
}

//---------------------------------------------
function doUrl (url, target) {
  
  if (target) {
    if (self.parent.frames && self.parent.frames[target]) {
      self.parent.frames[target].document.location = url
    } else {
      window.open (url)
    }
  } else {
    document.location = url
  }
  return true
}



//--------------------------------------------------
function setLabels (name, labels) {

  var obj = document.forms[0].elements[name]
  if (obj) {
    var slen = obj.options.length
    for (var i = 0 ; i < labels.length ; i++) {
      if (i < slen) {
        obj.options[i].text = labels[i]
      } else {
        obj.options[i] = new Option (labels[i], labels[i])
      }
    }
    obj.size = labels.length + 1
    for (var i = i ; i < slen ; i++) {
      obj.options[i].text = ''
    }
  }
}

//--------------------------------------------------
function showAtts (obj) {

	if (!obj) obj = this
  var lines = 1;
  var display = new String ()
  
  for (prop in obj) {
    if (lines%30==0) {
      display = 'Page ' + (lines/40) + '\n\n'+display
      alert (display)
      display = ''
    }
    display += prop+" : "+obj[prop]+'\n'
    lines++
  }
  display = 'Page ' + Math.ceil(lines/40) + '\n\n'+display
  alert (display)
}

//---------------------------------------------
//---------------------------------------------
//---------------------------------------------
//---------------------------------------------
//---------------------------------------------
//---------------------------------------------

var menu = null
var menuView = null
var isSilentMode = false

//---------------------------------------------
function init () { // can be overridden
  commonInit ();
}

//---------------------------------------------
function commonInit () {

	try {
		if (self.serverRestart) {
			document.body.innerHTML = 'Server has been restarted. Reloading...';
			var loc = self.parent.document.location.pathname;
			var ref = document.location.pathname + document.location.search;
			var url = loc + '?restart=1&ref=' + escape(ref);
			self.parent.document.location = url;
			return;
		}
	} catch (e) {
		alert('Server was restarted. Please reload site.');
	}
	
	try {
		if (top.disableSync == null) {
			if (!self.isLoginFrame) {
				if (top.isLoggedIn && self.isUserGuest) {
					document.body.innerHTML = 'Frames are out of sync. Refreshing site...';
					var url = top.location.toString();
					setTimeout('top.location="' + url  + '"', 1000);
					return;
				}
			}
		}
		//alert (top.isLoggedIn);
		//var isLoggedIn = (document.forms[0].usrid == null);
	} catch (e) {
	}
	
	var mt = document.getElementById('mainTable')
	if (mt) {
		if (window.ActiveXobject) {
			mt.onmouseover = XMF_onrowhover;
		}
		mt.onmousedown = XMF_onrowselect;
	}
	var inputs = document.getElementsByTagName('input')
	for (var i = 0 ; i < inputs.length ; i++) {
		var input = inputs[i]
		if (input.type == 'checkbox') {
			var par = input.parentNode;
			while (par) {
				if (par.className == 'controlColumn') {
					input.onmousedown = rowCheckbox;
					break;
				}
				par = par.parentNode;
			}
		}
	}
	if (getTop().checkSessionTimeout) {
		getTop().checkSessionTimeout(self)
	}
  if (getTop().frameToggler) {
    if (self.parent.name != 'toggler') {
      if (getTop().frameToggler.init) {
        getTop().frameToggler.init ()
      }
    }
  }
  
  try {
	  if (document.forms[0].MaxSessionTime) {
	  	var val = document.forms[0].MaxSessionTime.value;
	  	val = parseInt(val, 10);
	  	if (isNaN(val)) {
	  		val = 0;
	  	}
	  	top.maxSessionTime = val;
	  }
	} catch (e) {
	}
	  
  try {
  	top.srcUrl = getUrl ()
  } catch (e) {
  }
  
  window.status = ''
  if (document.forms[0].Message) {
    var msg = document.forms[0].Message.value
    if (msg) {
    	var msgTD = document.getElementById('messageBar')
    	var sep = msgTD ? '<br/>' : '\n'
    	msg = msg.replace('~~', '~')
      if (msg.indexOf ('~') != -1) {
	    	if (msg.indexOf('~') == 0) {
	    		msg = msg.substring(1) // trim the ~ character
	    	}
        var msgList = msg.split ('~')
        msg = msgList.join (sep);
      }
    	if (msgTD) {
    		msgTD.innerHTML = msg
    		msgTD.parentNode.style.display = ''
    	} else {
	      window.status = msg
	      if (!isSilentMode) {
	        alert (msg)
	      }
	    }
      // todo this is hardcoded bah!
      if (msg.indexOf ('not authorized') != -1) {
//        self.history.go (-1)
      }
    }
    document.forms[0].Message.value = ''
  }
  
  if (getTop().scrollTop || getTop().scrollLeft) {
    document.body.scrollTop = getTop().scrollTop
    document.body.scrollLeft = getTop().scrollLeft
    getTop().scrollTop = 0
    getTop().scrollLeft = 0
  } else {

    var elems = document.forms [0]
    for (var i = 0 ; i < elems.length ; i++) {
      if (elems [i].type == 'text') {
//        elems [i].focus ()
        break
      }
    }
  }

  if (document.getElementById) {
    menu = document.getElementById ('menu')
  }
  
  if (top.doPresentation) {
    var url = getUrl ();
    document.location = DIR_WEB + '/presentation.jsp?CMD=SetUrl&presurl=' + escape (url)
  }  
  
  if (window.ActiveXObject) {
	  var cfr = document.getElementById('columnFilterRow');
	  if (cfr) {
	  	var objs = cfr.getElementsByTagName('select');
	  	for (var i = 0 ; i < objs.length ; i++) {
	  		objs[i].onmousedown = selectBoxExpand;
	  	}
	  }
	}
	
	initEvents();
}

//----------------------------
function initEvents () {

	if (document.addEventListener) {
		document.addEventListener("keydown", keypress, true);
	} else {
	  document.onkeydown = keypress;
	}
}

//----------------------------
function keypress (e) {

	var evt = e ? e : window.event;

	var keyChar = String.fromCharCode(evt.keyCode).toLowerCase();
	if (evt.keyCode == 13) { // return
		var elem = e ? evt.target : evt.srcElement;
		if (elem) {
			if (elem.name == 'FullTextSearch') {
				if (self.doFullTextSearch) {
					doFullTextSearch();
				}
				return false;
			}
		}
		
	} else if (keyChar == 's' && evt.ctrlKey) {
    var cmd = getFormValue(self, 'CMD')
    if (cmd == 'Edit' || cmd == 'New') {
      doCommand ('Save')
    }
	}

  return true;
}


//------------
function selectBoxExpand (e) {
	e = e ? e : window.event;
	var obj = e.srcElement ? e.srcElement : e.target
	if (obj.style.width) {
		obj.style.width=null;
	}
	return true;
}
/*
//------------
function checkKeyPress () {

  if (window.event) {
    if (window.event.keyCode == 83 && window.event.ctrlKey) { // ctrl-s
      var cmd = getFormValue(self, 'CMD')
      if (cmd == 'Edit' || cmd == 'New') {
        doCommand ('Save')
      }
    }
  }
  return true
}
*/
//---------------------------------------------
function doBack () {

  var currPN    = self.parent.histPages[self.parent.histIndex]
  var currIndex = self.parent.histIndex
  
  while (self.parent.histIndex-- > 0) {
    var pn = self.parent.histPages[self.parent.histIndex]
    if (currPN != pn) {
      break
    }
  }
  var back = currIndex - self.parent.histIndex
  self.parent.histIndex++
  if (self.parent.backUrl) {
    var url = self.parent.backUrl
    self.parent.backUrl = null
    document.location = url
  } else {
    self.history.go (-back)
  }
}

//---------------------------------------------
saveBack ()
//---------------------------------------------
function saveBack () {
  
  if (!self.parent.histPages) {
    self.parent.histPages = new Array ()
    self.parent.histUrls = new Array ()
    self.parent.histIndex = -1
  }
  if (self.name == 'content') {
    var loc = new String (document.location)
    var pageName = 'PageName='
    var i0 = loc.indexOf (pageName)
    if (i0 != -1) {
      var i1 = loc.indexOf ('&', i0+1)
      if (i1 == -1) {
        i1 = loc.length
      }
      pn = loc.substring (i0 + pageName.length, i1)
      self.parent.histIndex++
      self.parent.histPages[self.parent.histIndex] = pn
    }
//    alert (pn + ":"+ self.parent.histIndex)
  }
}

function setBackUrl (url) {
  self.parent.backUrl = new String (url)
}

//---------------------------------------------
function noResponseTimeout (msg) {
  if (confirm (msg)) {
    document.location.reload()
  }
}

//---------------------------------------------
function noResponseConfirm  (msg) {
  
  if (! msg) {
    msg = 'Deleted. Refresh display?'
  }
  setTimeout ('noResponseTimeout("'+msg+'")', 1000)
}

//---------------------------------------------
function confirmPassword (obj) {
  
  if (obj) {
    var newPassword = prompt ('Re-enter password', '')
    if (newPassword != obj.value) {
      alert ('Password is incorrect')
      doBack ()
      return false
    }
  }
  return true
}
//---------------------------------------------
function doEmail(emailColumn) { 
	var url = DIR_WEB + '/email.jsp'
	url += '?ProjectName=' + getProject()
	url += '&Column=' + emailColumn
	url += '&chbSendCopy=1'
	url += '&chbSendBCC=1'
	
	document.location = url
}
//---------------------------------------------
function email (name) {

  if (name == null) {
    name = 'Email'
  }
  var addresses = document.forms[0].elements [name]

  var email = ''
  for (var i = 0 ; i < addresses.length ; i++) {
    if (addresses [i].checked) {
      if (email.length > 0) {
        email += ';'
      }
      email += addresses [i].value
    }
  }
  
  setFormValue (self, 'Message', email)
  textEditor ('Message')
  //alert ('mailto:' + email)
  document.location = 'mailto:' + email
}


var requiredFields = new Array ()

//---------------------------------------------
function colors (id, useNames) {
	
	var obj = document.forms[0].elements[id]
	
	var isModal = false;
	var feats = new Object ()
	feats.width   = 250
	feats.height  = 250
	
	if (obj) {
  	if (obj.length) {
  		obj = obj[0]
  	}	
  	var rect    = obj.getBoundingClientRect ? obj.getBoundingClientRect () : null
  	feats.left    = rect ? rect.left : 100
  	feats.top     = rect ? rect.top : 100
  }
  
	var arg = new Array ()

	var loc = URL_COLORS;
	if (useNames) {
		loc += '?useNames=1';
	}
	var win = openWindow (isModal, loc, arg, feats, "Colors")
	if (win) {
	  win.copyTo = obj
	  self.copyTo = obj
	}	
}

//---------------------------------------------
function calendar (id, includeTime) {
	
	var obj = document.forms[0].elements[id]
	
	if (obj && obj.length && self.activeObj) {
	  var parObj = self.activeObj.parentNode.parentNode.parentNode.parentNode
//	  alert (self.activeObj.parentElement.parentElement.parentElement.parentElement.tagName)
	  obj = parObj.getElementsByTagName ('INPUT')[0]
//	  alert(obj)
	}
	var isModal = window.ActiveXObject;
	
	var feats = new Object ()
	
	feats.width   = 300
	feats.height  = 300
	
	var arg = new Array ()
	arg[0] = window
	arg[1] = obj
	arg[2] = includeTime
	
	var loc = URL_CALENDAR + '?'
	if (includeTime) {
	  loc += "includeTime=true"
	  feats.width += 75
	}
	
	if (obj) {
  	if (obj.length) {
  		obj = obj[0]
  	}	
  	var rect    = obj.getBoundingClientRect ? obj.getBoundingClientRect () : null
  	feats.left    = rect ? rect.left : 100
  	feats.top     = rect ? rect.top : 100
  }

	var win = openWindow (isModal, loc, arg, feats, "Calendar")
	if (win) {
	  win.copyTo = obj
	  self.copyTo = obj
	}
}

//---------------------------------------------
function link (id) {
	var obj = document.forms[0].elements[id] ;
	
	var isModal = window.ActiveXObject;
	
	var feats = new Object ()
	
	feats.width   = 500
	feats.height  = 200
	
	var rect    = obj.getBoundingClientRect ? obj.getBoundingClientRect () : null
	feats.left    = rect ? rect.left : 100
	feats.top     = rect ? rect.top : 100
	
	var arg = new Array ()
	arg[0] = window
	arg[1] = obj
	
	
	var loc = DIR_WEB + '/linkMaker.html'
//	var feats = 'help:0;status:0;scroll:0;dialogHeight:165px;dialogWidth:400px;dialogLeft:'+left+';dialogTop:'+top+';'
	var win = openWindow (isModal, loc, arg, feats, "Calendar")
}

//---------------------------------------------
function calculator (id) {
	
	var obj = document.forms[0].elements[id]
	var isModal = window.ActiveXObject;
	
	var feats = new Object ()
	
	feats.width   = 300
	feats.height  = 250
	feats.resizable  = 1
	
	var arg = new Array ()
	arg[0] = window
	arg[1] = obj
	
	var loc = URL_CALCULATOR
	
	if (obj) {
  	if (obj.length) {
  		obj = obj[0]
  	}	
  	var rect    = obj.getBoundingClientRect ? obj.getBoundingClientRect () : null
  	feats.left    = rect ? rect.left : 100
  	feats.top     = rect ? rect.top : 100
  }

	var win = openWindow (isModal, loc, arg, feats, "Calculator")
	if (win) {
	  win.copyTo = obj
	}
}

//---------------------------------------------
function textEditor (columnName) {

  var isModal = window.ActiveXObject;
  var loc     = URL_TEXTEDITOR + '?ColumnName=' + columnName
  var arg     = new Array ()
  var feats   = new Object ()

  feats.resizable = 1
  feats.width   = 500
  feats.height  = 350
  feats.left    = 100
  feats.top     = 100

  arg[0] = window
  arg[1] = columnName

  openWindow (isModal, loc, arg, feats)
}
//---------------------------------------------
function doExport (type) {
	var action = document.forms[0].action
//	document.forms[0].target = '_blank'
	document.forms[0].action = action + '&Export=' + type
	document.forms[0].submit();
//	document.forms[0].target = ''
	document.forms[0].action = action
}
//---------------------------------------------
function exportDbTable (table, file, columns, whereClause) {

  if (!table) {
    if (document.forms[0].ViewParams) {
      table = document.forms[0].ViewParams.value
      table = escape (table)
    }
  }
  if (!columns) {
    columns = getFormValue (self, 'showColumn')
  }
  
//  alert (table)
  var isModal = false;
  var pageName = getActionValue('PageName')
  var tableName = getFormValue (self, 'Collection_Name')
  
  var loc     = URL_EXPORT + '?CMD=export&table=' + table + '&file=' + file
  
  if (pageName) {
    loc += '&PageName=' + pageName
  }
  
	loc += '&ProjectName=' + getProject() 
  
  if (columns) {
    loc += '&columns=' + columns
  }
  if (columns) {
    loc += '&Collection_Name=' + tableName
  }
  if (whereClause) {
    loc += '&whereClause=' + whereClause
  }
  
  var arg     = new Array ()
  var feats   = new Object ()
  
  feats.resizable = 1
  feats.width   = 400
  feats.height  = 100
  feats.left    = 100
  feats.top     = 100

  openWindow (isModal, loc, arg, feats)
}

//---------------------------------------------
function lookup (lookupMetaId, lookupView, isMultiSelect, criteria, w, h) {

  var isModal = false;
  var loc     = ''
  var arg     = new Array ()
  var feats   = new Object ()

  feats.scrollbars = 1
  feats.resizable = 1
  
  feats.width   = 600
  feats.height  = 450
  feats.left    = 100
  feats.top     = 100
  feats.status  = 1

	if (w) {
		feats.width = w;
	}
	if (h) {
		feats.height = h;
	}
  arg[0] = window

  if (lookupView || isMultiSelect == false) {
    //feats.width   = 600
    //feats.height  = 450
    loc = URL_LOOKUP
		loc += '?ProjectName=' + getProject() 
    loc += '&isMultiSelect='+isMultiSelect
    loc += '&batchSize=10'
    loc += '&LookupViewId=' + lookupView
	  loc += '&HtmlElementId=' + lookupMetaId
	  loc += '&PrimaryValue=' + document.forms[0].PrimaryValue.value
	  
  } else {
    //feats.width   = 500
    //feats.height  = 350
    loc = URL_SELECTOR
		loc += '?ProjectName=' + getProject() 
	  loc += '&HtmlElementId=' + lookupMetaId
	  loc += '&PrimaryValue=' + document.forms[0].PrimaryValue.value
  }
  if (criteria) {
  	loc += criteria
	}

	var is_ie6 = (
		window.external &&
		typeof window.XMLHttpRequest == "undefined"
	)

isModal = false;
  openWindow (isModal, loc, arg, feats, 'Lookup')
}



//---------------------------------------------
function setBatchSize (sz) {

  var obj = document.forms[0].batchSize
	if (sz) {
    obj.value = sz
	  doSubmit ()
	  
	} else {
	  var value = prompt ('Enter number of records displayed (<= 200)', obj.value)
	  if (value) {
	    if (value == -1) {
	      // allow the admin who knows about the special
	      // value to view all records in one go
		    obj.value = value
	  	  doSubmit ()
	  	  
	    } else if (value > 200) {
	  		alert ('You must enter a value less than or equal to 200')
	  		
	  	} else {
		    obj.value = value
	  	  doSubmit ()
	  	}
	  }
	}
}
//---------------------------------------------
function setBatchIndex (index) {
  
  document.forms[0].batchIndex.value = index
  doSubmit ()
}
//---------------------------------------------
function categorize () {

  if (document.forms[0].categorizedColumn.value == currentColumn) {
    document.forms[0].categorizedColumn.value = ''
  } else {
    document.forms[0].categorizedColumn.value = currentColumn
  }
  setBatchIndex(0)
}
//---------------------------------------------
function doSelected (isSelectOnly) {
  
  if (isSelectOnly) {
    document.forms[0].SelectedRows.value = 'SelectedOnly'
  } else {
    document.forms[0].SelectedRows.value = ''
  }
/*  
  if (isSelectOnly) {
    document.forms[0].searchCriteria.value = 'SelectedOnly'
  } else {
    document.forms[0].searchCriteria.value = ''
  }
*/  
  setBatchIndex(0)
}

//---------------------------------------------
function doSearchOnFirstLetter (column, letter) {
  
  setFormValue (self, 'searchColumn', column)
  document.forms[0].searchCriteria.value  = letter + '*'
  doSearch (true)
}

//---------------------------------------------
function Date_addMonths (months) {
	
	
	var day = this.getDate () 
	var month = this.getMonth () + parseInt (months,10)
	var year	= this.getYYYY () + Math.floor (month/12)
	month	%= 12
	if (month < 0) {
		month += 12
	}

	this.setYear (year) 
	this.setMonth (month) 
	if (day > this.numberOfDays ()) {
		day = this.numberOfDays ()
	}
	this.setDate (day) 
//	alert (this + ":" + this.getYYYY () + ":" + this.getYYYY () + ":" + year + ":" + this.getMonth () + ":" + month)
}

//---------------------------------------------
function setWeek (w,offset) {
  if (offset) {
  	var wo = parseInt(document.forms[0].calWeek.value);
  	wo = wo + offset;
  	if (wo == 0) {
  	//	wo = 53;
  	}
  	w = wo;
	}
  document.forms[0].calWeek.value = w
  doSubmit ()
}


//---------------------------------------------
function show2WeekView (weekNum, e) {

  if (!weekNum) {
		e = e ? e : window.event;
		var td = null;
		if (e) {
			td = e.srcElement ? e.srcElement : e.target;
		}

    // this section retrieves the week number info
    // by stepping back a day until a week number is 
    // found.
    if (td && td.tagName.toLowerCase() != 'td') {
      td = td.parentNode;
    }
    if (td) {
	    for (var i = 0 ; i < 14 ; i++) {
	    	var txt = td.textContent ? td.textContent : td.innerText;
	      var num = parseInt (txt,10)
	      if (isNaN (num) == false) {
	        weekNum = num - 1
	        break
	      }
	      td = td.previousSibling;
	      if (!td) {
	        return
	      }
	    }
	  }    
    if (!weekNum) {
      return
    }
  }
  getForm().calWeek.value = weekNum
  getForm().CalendarViewType.value = 'week'

  doSubmit (); 
}

//---------------------------------------------
function doTableArchive (obj) {
	var value = obj.options[obj.selectedIndex].value

	if (getForm().yearBar) {
		var pos = value.search (/[0..9]/);
		if (pos != -1) {
		 var year = parseInt (value.substring (pos-1), 10)
		 getForm().yearBar.value = year
		 getForm().yearBar.onchange()
		 return;
		}
	}
	doSubmit ();	
}

//---------------------------------------------
function doSearchDate (column, yearOffset, monthOffset) {
  
  var mObj  = document.forms[0].monthBar
  var yObj  = document.forms[0].yearBar
  var dObj  = document.forms[0].durationBar
  var wObj  = document.forms[0].calWeek
  
  var month = mObj ? parseInt (mObj.options [mObj.selectedIndex].value, 10) : 0
  var year  = parseInt (yObj.options [yObj.selectedIndex].value, 10)
  var durInDays = 30;
  if (dObj) {
    durInDays  = parseInt (getFormValue(self,dObj.name), 10)
  }
  if (wObj != null) {
    wObj.value = ''
  }
  month += monthOffset
  year  += yearOffset
  
  if (mObj) {
  	if (mObj.selectedIndex == 0 && monthOffset == -1) {
  		yObj.selectedIndex -= 1;
  		mObj.selectedIndex = 11
  		year--;
  		month = 11;
  	} else if (mObj.selectedIndex == 11 && monthOffset == 1) {
  		yObj.selectedIndex += 1;
  		mObj.selectedIndex = 0
  		year++;
  		month = 0;
  	} else {
	    mObj.selectedIndex += monthOffset
  	}
  }
  yObj.selectedIndex += yearOffset
  
  var date = new Date ()
  date.setSeconds (0)
  date.setHours (0)
  date.setMinutes (0)
  date.setYear (year)
  date.setMonth (month)
  date.setDate (1)
  var months = Math.round (durInDays / 30)
	var month2 = month + parseInt (months,10)
//	alert (month +":"+month2+":"+months)
	var year2	= date.getFullYear () + Math.floor (month2/12)
	month2	%= 12
	if (month2 < 0) {
		month2 += 12
	}
	var date2 = new Date ()
	date2.setTime (date.getTime ())
	date2.setYear (year2) 
	date2.setMonth (month2) 
  year2   = date2.getFullYear ()
  month2  = date2.getMonth ()
  
  var crit    = ''
  crit += column + '>='
  crit += '1-' + (month +1) + '-' + year
  crit += ' and '
  crit += column + '<'
  crit += '1-' + (month2+1) + '-' + year2
  
  if (dObj == null || isNaN (year2)) {
    
  } else {
    document.forms[0].sortColumn.value = column
    document.forms[0].searchColumn2.value = column
    document.forms[0].searchCriteria2.value  = crit
  }
  currentColumn  = column
  setBatchIndex(0)
  
//  doSort (document.forms[0].searchSort.value == 1)
}

//---------------------------------------------
function doSearchDateReset () {
  document.forms[0].searchColumn2.value = ''
  document.forms[0].searchCriteria2.value  = ''
  setBatchIndex(0)
}

//---------------------------------------------
function doSearch2 (column) {

  var promptText = 'Enter ' + column + 'criteria'
  var prevcrit = document.forms[0].searchCriteria2.value
  prevcrit = prevcrit?prevcrit:''
 	var crit = prompt (promptText, prevcrit)
 	
 	document.forms[0].searchColumn.value = column
 	document.forms[0].searchCriteria.value = crit
 	
  setBatchIndex(0)
}

//---------------------------------------------
function doSearchUsingElement (elem) {

	if (elem) {
		if (elem.tagName.toLowerCase() == 'select') {
			var tr = elem.parentNode.parentNode
			if (tr) {
				var filters = tr.getElementsByTagName('select')
				if (filters.length > 1) {
					var useFirst = true
//					var searchColN = document.forms[0].searchColumn
//					var searchCrtN = document.forms[0].searchCriteria
					
					document.forms[0].searchColumn.value = ''
					document.forms[0].searchCriteria.value = ''
					document.forms[0].searchColumn2.value = ''
					document.forms[0].searchCriteria2.value = ''
					
					for (var i = 0 ; i < filters.length ; i++) {
						var filter = filters[i]
						var str = new String(filters[i].onchange)
							//alert (filter.name+":"+filter.value)
						if (str.indexOf('doSearchUsingElement') != -1) {
							if (filter.value) {
								if (useFirst) {
									document.forms[0].searchColumn.value = filter.name
									document.forms[0].searchCriteria.value = filter.value
									useFirst = false
								} else {
									document.forms[0].searchColumn2.value = filter.name
									document.forms[0].searchCriteria2.value = filter.value
									break
								}
/*								
							} else {
								if (useFirst) {
									document.forms[0].searchColumn.value = ''
									document.forms[0].searchCriteria.value = ''
									useFirst = false
								} else {
									document.forms[0].searchColumn2.value = ''
									document.forms[0].searchCriteria2.value = filter.value
									break
								}
*/								
							}
						}
					}
				  document.forms[0].CMD.value = 'Read'
				  setBatchIndex(0)
				  return
				}
			}
		}
	}
	var name = elem.name
  var value = getFormValue (self, elem.name)
  if (value == '*') {
  	value = ''
  	name = ''
	}
  document.forms[0].searchColumn.value = elem.name
  document.forms[0].searchCriteria.value = value
  document.forms[0].CMD.value = 'Read'
  setBatchIndex(0)
}

//---------------------------------------------
function focusWindow () {
  
  if (self.currWindow && self.currWindow.focus) {
  	setTimeout ('self.currWindow.focus()', 1000)
  }
}

//---------------------------------------------
function doAdvancedSearch (pageName) {
  
  var isModal = false;//document.all
  var loc     = URL_SEARCH
  loc += '?ProjectName=' + getProject()
  loc += '&PageName=' + pageName
  loc += '&' + getQueryString ()
  
  var arg     = new Array ()
  var feats   = new Object ()
  
  feats.resizable = 1
  feats.width   = 500
  feats.height  = 300
  feats.left    = 100
  feats.top     = 100
  feats.status  = 1

  document.forms[0].searchColumn.value = currentColumn
  openWindow (isModal, loc, arg, feats)
}

//---------------------------------------------
function doFilter (isReset) {
	
	if (window.event) {
		// this is an IE6 fix for the onmousedown 
		// event which calls the selectBoxEvent function.
		if (window.event.srcElement) {
			if (window.event.srcElement.tagName.toLowerCase()=='select') {
				if (window.event.srcElement.selectedIndex == -1) {
					return false;
				}
			}
		}
	}
	
	var namesStr = getFormValue (self, 'viewfilters');
	var names = namesStr.split (',');
	var criteria = ''
	var form = document.forms[0]
	
	for (var i = 0 ; i < names.length ; i++) {
		var name = names[i]
		var value = getFormValue (self, name);
		if (isReset) {
			setFormValue (self, name, '');
			var obj = getFormElement(name);
		} else {
			if (value && name) {
			 	form.searchColumn.value = names[0]
				if (value != '*') {
					if (criteria != '') {
						criteria += ' and '
					}
					if (form.elements[name].type == 'text') {
						if (value.indexOf('*') == -1) {
							value = '*' + value + '*'
						}
					}
					if (value.indexOf('+') != -1) {
						//WARNING: for some reason '+' are not encoded and get interpreted at the server as a space character
						//while (value.indexOf('+') != -1) {
						//	value = value.replace('+', '%2b');
						//}
					}
					criteria += name + '=' + "'" + value + "'"
				}
			}
		}
	}
	
  form.searchCriteria.value = criteria

//  form.sortColumn.value = cols
//  form.searchSort.value = sort
	
  setBatchIndex(0)
	
//	doSubmit ();
//	alert (criteria)
}	

//---------------------------------------------
function doNewCalendarItem (e, dateColumn, dateEndColumn, currDate, url) {
	
	e = e ? e : window.event
	var obj = e.srcElement ? e.srcElement : e.target
	obj.parentNode.parentNode.style.backgroundColor = 'lightblue'
	if (!dateColumn) {
		obj.parentNode.parentNode.style.backgroundColor = ''
		top.selectedDate = null
		return false
	}

	if (dateEndColumn) {
		if (!top.selectedDate) {
			top.selectedDate = currDate
			var resetLink = document.createElement('a')
			resetLink.appendChild(document.createTextNode('reset'))
			resetLink.style.marginTop = '5px'
			resetLink.style.display = 'block'
			resetLink.href = '#'
			resetLink.onclick = function () {
				obj.parentNode.parentNode.style.backgroundColor = ''
				top.selectedDate = null
				resetLink.parentNode.removeChild(resetLink)
			}
			obj.parentNode.appendChild(resetLink)
			return false
		}

		url += '&CMD=New'
		if (top.selectedDate < currDate) {
			url += '&' + dateColumn + '=' + top.selectedDate
			url += '&' + dateEndColumn + '=' + currDate
		} else {
			url += '&' + dateColumn + '=' + currDate
			url += '&' + dateEndColumn + '=' + top.selectedDate
		}
		top.selectedDate = null
		
	} else {
		url += '&CMD=New' 
		url += '&' + dateColumn + '=' + currDate
	}
	
	document.location = url
}

//---------------------------------------------
function doSearch (noPrompt) {

//  promptText += '\nFor dates: dd-mm-yyy<op>, 06-09-1969>='
//  promptText += '\nFor strings: <*>criteria<*>'
//  promptText += '\nDates: dd-mm-yyyy[=|!=|>|<|>=|<=] [[and|or] [date][operator]'
//  promptText += '\nStrings: criteria[*|=|!=|>|<|>=|<=]  '
  
  var promptText = 'Enter search criteria'
  if (! noPrompt) {
  	var crit = prompt (promptText,document.forms[0].searchCriteria.value)
  	if (crit == null) {
  	  return;
  	}
  	
  	if (crit.indexOf ('*') == 0 || crit.indexOf ('*') == crit.length-1) {
  	} else if (crit.indexOf (' and ') != -1  || crit.indexOf (' or ') != -1) {
  	} else if (crit.indexOf ('=') != -1  || crit.indexOf ('!=') != -1) {
  	} else if (crit.indexOf ('>') != -1  || crit.indexOf ('<') != -1) {
  	} else if (crit.indexOf ('>=') != -1  || crit.indexOf ('<=') != -1) {
    } else {
//    	alert (currentColumn + ":"+currentType)
      if (document.forms[0].ExactMatch == null) {
        if (currentType == -1 || currentType == 12) {
//        if (currentType == 1 || currentType == 2) {
  //        if (! confirm ('Search for exact value?')) {
            crit = '*' + crit + '*'
  //        }
        } else {// if (currentType == 4 || currentType == 41) {
        }

      }
    }
    document.forms[0].searchColumn.value = currentColumn
    document.forms[0].searchCriteria.value = crit
  }
  setBatchIndex(0)
}

//---------------------------------------------
function doPredefinedFilter (obj) {

	if (obj.selectedIndex >= 0) {
		var value = obj.value
		var title = obj.options[obj.selectedIndex].text
		if (title == '*') {
			setFormValue(self, 'PageTitle', '')
			setFormValue(self, 'categorizedColumn', '')
			doSearchReset(true)
		} else {
			var url = value + '&PageTitle=' + escape(title)
			document.location=url;
		}
	}
}

//---------------------------------------------
function doSearchReset (noPrompt) {

  document.forms[0].searchColumn.value = ''
  document.forms[0].searchCriteria.value = ''
  setBatchIndex(0)
}
//---------------------------------------------
function doSearchFullText (noPrompt) {

  var promptText = 'Enter search criteria'
  var crit = ''
  if (! noPrompt) {
  	crit = prompt (promptText, document.forms[0].searchCriteria.value)
  	if (crit == null) {
  	  return;
  	}
  } else {
    crit = document.forms[0].searchCriteria.value
  }
	var parts = crit.split (' ')
	var norm = ''
	for (var i = 0 ; i < parts.length ; i++) {
		var part = parts[i].toLowerCase ();
		// ignore words less than 2 letters (probably words like 'in', 'an', 'on', etc)
		if (part == 'or'
		 || part == 'and'
		 || part.length <= 2
	  ) {
	  	continue;
		}
		if (norm != '') {
			norm += ' '
		}
		norm += parts[i]
	}
  document.forms[0].searchColumn.value = ''
  document.forms[0].searchCriteria.value = norm

  setBatchIndex(0)
}
//---------------------------------------------
function doSearchAll (noPrompt) {
  
  document.forms[0].searchColumn.value = ''
  
  doSearch (noPrompt)
}
//---------------------------------------------
function exactMatch (obj) {
  
  var crit = document.forms[0].searchCriteria.value
  if (crit) {
    if (!obj.checked) {
    	if (crit.indexOf ('*') != 0) {
        crit = '*' + crit
      }
    	if (crit.indexOf ('*',1) != (crit.length-1)) {
        crit = crit + '*'
      }
    } else {
    	if (crit.indexOf ('*') == 0) {
    	  crit = crit.substring (1)
    	}
    	if (crit.indexOf ('*') == (crit.length-1)) {
    	  crit = crit.substring (0, crit.length-1)
    	}
    }
    document.forms[0].searchCriteria.value = crit
  }
}

//---------------------------------------------
function doSort (isAsc) {
  document.forms[0].sortColumn.value = currentColumn
  document.forms[0].searchSort.value = isAsc?'1':'-1'
  document.forms[0].batchIndex.value = 0
	doSubmit()
}

//---------------------------------------------
function createNewFormValue (name, value) {
	if (document.forms[0].elements[name]) {
		document.forms[0].elements[name].value = value
	} else {
		if (name && value) {
			var inp = document.createElement('input')
			inp.setAttribute('type', 'hidden')
			inp.setAttribute('name', name)
			inp.setAttribute('value', value)
			document.forms[0].appendChild(inp)
		}
	}
}

//---------------------------------------------
function doSetColumnValue (column, value) {
	
	var val = null
	var col = null
	
	if (column && value) {
		col = column
		val = value
		
	} else {
		col = currentColumn
		val = prompt('Enter the value to set this column to:', '')
	}
	if (val != null) {
	  createNewFormValue('SetColumnName', col)
	  createNewFormValue('SetColumnValue', val)
	  document.forms[0].SCMD.value = 'SetColumn'
		doSubmit()
	}
}

//---------------------------------------------
function doSetColumnReplaceValue () {
	var toReplace = prompt('Enter the value to replace:', '')
	if (toReplace != null) {
		var val = prompt('Enter the value to insert:', '')
		if (val != null) {
		  createNewFormValue('SetReplace', toReplace)
		  createNewFormValue('SetColumnName', currentColumn)
		  createNewFormValue('SetColumnValue', val)
		  document.forms[0].SCMD.value = 'ReplaceColumn'
			doSubmit()
		}
	}
}

//---------------------------------------------
function showPrinter () {
  
//  var loc = new String (document.location)
  var loc = new String (document.forms[0].action)
  if (loc.indexOf ('?') == -1) {
    loc += '?'
  }
  if (loc.lastIndexOf ('&') != loc.length - 1) {
    loc += '&'
  }
  loc += getQueryString ()
  loc += '&printing=1'
	var isModal = false;//document.all
	
	var feats = new Object ()
	
	feats.width   = 600
	feats.height  = 650
	feats.menubar = 1
	feats.resizable = 1
	feats.scrollbars = 1
	feats.toolbar = 1
	var arg = new Array ()
	arg[0] = window
	
	openWindow (isModal, loc, arg, feats, "Viewer")
}

//---------------------------------------------
function getProject () {
	
	var url = document.forms[0].action
	var key1 = 'ProjectName='
	var p0 = url.indexOf(key1);
	if (p0 != -1) {
		var p1 = url.indexOf('&', p0+key1.length);
		if (p1 == -1) {
			p1 = url.length
		}
		var project = url.substring(p0+key1.length, p1)
		return project
	}
	url = document.location.toString()
	var p1 = url.indexOf('?')
	if (p1 != -1) {
		url = url.substring(0,p1)
	}
	var parts = url.split('/');
	var project = ''
	if (parts.length > 2) {
		project = parts[parts.length-1];
		if (project.indexOf('.') != -1) {
			project = parts[parts.length-2] 
		}
	}
	var p0 = url.lastIndexOf('/')
	if (!project) {
		project = url.substring(p0+1, p1)
	}
	if (!project) {
		if (top.frames) {
			var frm = top.frames.control
			if (frm) {
				project = frm.document.forms[0].project.value
			}
		}
	}
	return project
}

//---------------------------------------------
function showViewer () {
  
  
	var isModal = false;//window.ActiveXObject;
	
	var feats = new Object ()
	
	feats.width   = 400
	feats.height  = 500
	feats.resizable = 1
	var arg = new Array ()
	arg[0] = window
	
	var pageName = getActionValue ('PageName')
	var loc = URL_VIEWER
	loc += '?Collection_Name=' + document.forms[0].Collection_Name.value 
	loc += '&PageName=' + getActionValue('PageName') 
	loc += '&ViewId=' + getActionValue('ViewId') 
	loc += '&ProjectName=' + getProject() 
	loc += '&categorizedColumn=' + document.forms[0].categorizedColumn.value
	
  openWindow (isModal, loc, arg, feats, "Viewer")
}

var currentColumn = ''
var currentType = ''
var menu = null


//---------------------------------------------
function showMenuView () {

  if (menuView == null) {
    menuView = document.getElementById ('menuView')
  }
  if (menuView == null) {
    alert ('Sorry for the inconvience. Hey developer you forgot to place the menuView in the page!')
    return
  }
  
  if (menuView.style.visibility == 'visible') {
    menuView.style.visibility = 'hidden'
    return
  } else {
    menuView.style.visibility = 'visible'
  }
  
  var obj = document.getElementById ('controlColumn')
  if (obj.parentNode) {
//    obj = obj.parentNode
  }
  if (obj) {
    var rect = getClientRect (obj)
    menuView.style.left = '' + rect.left + 'px'
    menuView.style.top  = '' + rect.bottom + 'px'
  }
}

//---------------------------------------------
function showMenu (columnName, columnObj, isSortable, isSearchable, isCategorizable, isSelectable, typeNumber) {

  if (menu == null) {
    menu = document.getElementById ('menu')
  }

  if (menu == null) {
    alert ('Sorry for the inconvience. Hey developer you forgot to place the menu in the page!')
    return
  }
  
  var obj = document.getElementById (columnName)
  if (self.activeObj) {
    if (self.activeObj.parentNode) {
      obj = self.activeObj.parentNode
    }
  }
  if (obj) {
    var rect = getClientRect (obj)
    menu.style.left = '' + rect.left + 'px'
    menu.style.top  = '' + rect.bottom + 'px'
    var menuItem_sortRuler  = document.getElementById('MenuItem_RulerSort');
    var menuItem_sortAZ     = document.getElementById('MenuItem_sortAZ');
    var menuItem_sortZA     = document.getElementById('MenuItem_sortZA');
    var menuItem_search     = document.getElementById('MenuItem_search');
    var menuItem_categorize = document.getElementById('MenuItem_categorize');
//      var menuItem_selectShow = document.getElementById('MenuItem_selectShow');
//      var menuItem_selectAll  = document.getElementById('MenuItem_selectAll');
    var menuItem_advanced   = document.getElementById('MenuItem_advancedSearch');

		if (menuItem_categorize) {
			var catCol = getFormValue (self, 'categorizedColumn')
			var text = menuItem_categorize.firstChild.nodeValue
			var newText = 'Categorize'
			if (columnName == catCol) {
				newText = 'Un-categorize'
			}
			if (newText != text) {
				menuItem_categorize.firstChild.nodeValue = newText
			}
		}      
    
    if (menuItem_categorize)  menuItem_categorize.style.display = isCategorizable?'':'none';
    if (menuItem_sortRuler)   menuItem_sortRuler.style.display  = isSortable?'':'none';
    if (menuItem_sortAZ)      menuItem_sortAZ.style.display     = isSortable?'':'none';
    if (menuItem_sortZA)      menuItem_sortZA.style.display     = isSortable?'':'none';
    if (menuItem_search)      menuItem_search.style.display     = isSearchable?'':'none';
    if (menuItem_advanced)    menuItem_advanced.style.display     = isSearchable?'':'none';
      
//      if (menuItem_selectShow)  menuItem_selectShow.style.display = isSelectable?'':'none';
//      if (menuItem_selectAll)   menuItem_selectAll.style.display  = isSelectable?'':'none';
  }
  if (menu.style.visibility == 'visible') {
    menu.style.visibility = 'hidden'
    return
  } else {
    if (columnName) {
      currentColumn = columnName
    }
    currentType = typeNumber
    
    menu.style.visibility = 'visible'
  }  
}
//---------------------------------------------

//---------------------------------------------
//
//	Meta Specific Functions Section
//
//---------------------------------------------

//---------------------------------------------
function doSubRecordDelete(page, pkey, id) {

	var path = document.location.pathname;
	var pn = getActionValue('PageName');
  var mode = getFormValue(self, 'CMD')
  var key = getFormValue(self, 'PrimaryKey')
  var val = getFormValue(self, 'PrimaryValue')
  
	var redirect = path;
  redirect += '?PageName=' + pn;
  redirect += '&CMD=' + mode;
  redirect += '&PrimaryKey=' + key;
  redirect += '&PrimaryValue=' + val;

	var url = path;
  url += '?PageName=' + page
  url += '&' + pkey + '=' + id;
  url += '&' + 'CMD' + '=' + 'Delete';
  url += '&' + 'Redirect' + '=' + escape(redirect);
  //alert(url)
  document.location = url;
  //alert(url);
}

//---------------------------------------------
function doCommand (val, eventId, formAction, scmdVal) {
  
  if (isUrl (val)) {
    doUrl (val)
    return true
  }
	if (document.forms[0].CMD == null) {
		alert ('Sorry for the inconvience. Hey Developer You missed CMD Hidden Field!!')
	} else {
		if (eventId) {
			setFormValue (self, 'meta_event_id', eventId);
		}
	  if (formAction) {
	  	document.forms[0].action = formAction;
		}
		
	  if (val == 'Delete') {
	    var ok = confirm ('Are you sure you want to delete this record(s)?')
	    if (!ok) {
	      return 
	    }
	  }
	  if (val == 'Undo') {
	    var ok = confirm ('Reverting to a previous version cannot be undone.\nAre you sure you want to undo this record?')
	    if (!ok) {
	      return 
	    }
	  }
	  
	  if (scmdVal) {
	    if (document.forms[0].SCMD != null) {
	      document.forms[0].SCMD.value = scmdVal
	    }
	  }
		if (val == 'Next' || val == 'Insert' || val == 'Update' || val == 'Approve' || val == 'Disapprove') {
			if (!validateForm()) {
//				alert ('Form Validation failed client side')
				return ;
			}
		}
		document.forms[0].CMD.value = val
		doSubmit()
	}
}

//---------------------------------------------
/*
function doCommand (val, scmdVal, formAction) {
  
  if (isUrl (val)) {
    doUrl (val)
    return true
  }
	if (document.forms[0].CMD == null) {
		alert ('Sorry for the inconvience. Hey Developer You missed CMD Hidden Field!!')
	} else {
	  if (formAction) {
	  	document.forms[0].action = formAction;
		}
		
	  if (val == 'Delete') {
	    var ok = confirm ('Are youe sure you want to delete this record(s)?')
	    if (!ok) {
	      return 
	    }
	  }
	  
	  if (scmdVal) {
	    if (document.forms[0].SCMD != null) {
	      document.forms[0].SCMD.value = scmdVal
	    }
	  }
		document.forms[0].CMD.value = val
		if (val == 'Next' || val == 'Insert' || val == 'Update' || val == 'Approve' || val == 'Disapprove') {
			if (!validateForm()) {
//				alert ('Form Validation failed client side')
				return ;
			}
		}
		doSubmit()
	}
}
*/



//---------------------------------------------
// View methods
//---------------------------------------------
viewNumber = ''
//---------------------------------------------
function expandAll() {
//  alert (expandAllList)
	var elem = document.forms[0].elements['EXP' + viewNumber];
	elem.value = -1;
	setBatchIndex (0);
}
//---------------------------------------------
function collapseAll() {
	var elem = document.forms[0].elements['EXP' + viewNumber];
	elem.value = 0;
	setBatchIndex (0);
}
//---------------------------------------------
function expandTable(id) {
	
	var elem = document.forms[0].elements['EXP' + viewNumber];
	if (!id) {
	  alert ('Nothing to expand')
	  return
	}
	elem.value += ',' + id;
	doSubmit()
}
//---------------------------------------------
function collapseTable(id) {
	
	var elem = document.forms[0].elements['EXP' + viewNumber];
	var val = elem.value
	if (val.indexOf ('ExpandAll') > 0) {
		val = ''
	}
	var toFind = ',' + id
	if (val.indexOf (toFind) == -1) {
	  toFind = id
	}
	
	var valArr = val.split (toFind);
	val = valArr.join ('')
	elem.value = val
	doSubmit()
}

//---------------------------------------------
function toggleTable (id) {

	var elem = document.forms[0].elements['EXP' + viewNumber];
	if (elem.value == -1 && expandAllList) {
    elem.value = expandAllList
	}
	var val = elem.value
	if (val != null) {
    if (val.indexOf (','+id+',') != -1) {
      collapseTable (id)
  	} else if (val.indexOf (','+id) != -1) {
      collapseTable (id)  
  	} else if (val.indexOf (',') == -1 && val.indexOf (id) != -1) {
      collapseTable (id)  
    } else {
      expandTable (id)  
    }
  } else {
    alert (elem.name)
  }
}
//---------------------------------------------
function validateForm () {
	
	var form = document.forms[0]
  var toReturn = true
  
	for (var i=0 ; i < requiredFields.length ; i++) {
		var obj = form.elements[requiredFields[i]]
		if (obj.length && obj[0] && obj[0].type == 'checkbox') {
			var checkedVal = '';
			for (var j = 0 ; j < obj.length ; j++) {
				var objI = obj[j];
				if (objI.type == 'checkbox') {
					if (objI.checked) {
						checkedVal += objI.value;
					}
				}
			}
			if (!checkedVal) {
				toReturn = false;
			}
		}
		if (toReturn) {
			if (obj.type == 'text') {
				if (obj.value == '') {
				  toReturn = false
				}
			} else if (obj.type == 'hidden') {
				if (obj.value == '') {
				  // cannot focus hidden field
	  			alert (obj.name + ' is a required field.')
				  return false
				}
			  
			} else if (obj.type == 'select-one') {
			  if (obj.selectedIndex == -1) {
			    toReturn = false
			  } else {
			    var val = obj.options[obj.selectedIndex].value
			    if (! val || val == ' ') {
			      toReturn = false
			    }
			  }
			}
		}

    if (toReturn == false) {
			var name = obj.name;
    	if (!name && obj.length) {
				name = obj[0].name;				
			}
			alert(name + ' is a required field.');
			try {
				obj.focus()
			} catch(e) {
			}
			return toReturn;
    }		
	}
	return toReturn;
}

//---------------------------------------------
// This allows options to added to select boxes on the fly
// currently with a oncontextmenu event
var currSelector = null

function addNewSelectItem (obj, label, value) {

  if (obj == null) {
    obj = currSelector
  }
    
  if (obj == null) {
    alert ('Selector is null')
  }
  if (label && value) {
    obj.options [obj.options.length] = new Option (label, value)
    obj.options.selectedIndex = (obj.options.length - 1)
    if (obj.onchange) {
      obj.onchange ()
    }
  }
}

function addSelectItem (obj, pageName, metaDataId, w, h) {

  currSelector = obj
  if (pageName) {
    var isModal = false
    var loc = URL_NEWITEM
    loc += '?ProjectName=' + getProject()
    loc += '&PageName=' + pageName
    loc += '&CMD=New'
    if (metaDataId) { // Version 2.1.3
    	loc += '&HtmlElementId=' + metaDataId
    }
    var arg     = new Array (window, obj)
    var feats = new Object ()
    var title = 'NewItem'
  	feats.scrollbars  = 1
  	feats.status  = 1
  	feats.width   = 400
  	feats.height  = 300
  	if (w) {
	  	feats.width   = w
  	}
  	if (h) {
	  	feats.height   = h
  	}
  	feats.resizable  = 1
  	var win = openWindow (isModal, loc, arg, feats, title);
    return
  }

  if (obj.options) {
    var value = prompt ('Enter the selector value', obj.value)
    if (value) {
      obj.options [obj.options.length] = new Option (value,value)
      obj.options.selectedIndex = (obj.options.length - 1)
      if (obj.onchange) {
        obj.onchange ()
      }
    }
  }  
}

//--------------------------------------------------
function removeSelectItem (obj) {
	if (obj.selectedIndex >= 0) {
		var ok = confirm('Are you sure you wish to remove this item from the list?')
		if (ok) {
			for (var i = obj.options.length-1 ; i >= 0 ; i--) {
				var opt = obj.options[i];
				if (opt.selected) {
					if (opt.value) {
						obj.removeChild(opt)
						if (obj.name.indexOf('VIEWER') != -1) {
							var hiddenName = obj.name.replace('VIEWER', '')
							var hidObj = getForm().elements[hiddenName];
							if (hidObj) {
								hidObj.value = hidObj.value.replace(opt.value,'')
								hidObj.value = hidObj.value.replace(',,', ',')
								if (hidObj.value.indexOf(',') == 0) {
									hidObj.value = hidObj.value.substring(1);
								}
							}
						}
					}
				}
			}
		}
/*		//original code that only handles one item
		var opt = obj.options[obj.selectedIndex]
		if (opt.value) {
			obj.removeChild(opt)
			if (obj.name.indexOf('VIEWER') != -1) {
				var hiddenName = obj.name.replace('VIEWER', '')
				var hidObj = getForm().elements[hiddenName];
				if (hidObj) {
					hidObj.value = hidObj.value.replace(opt.value,'')
					hidObj.value = hidObj.value.replace(',,', ',')
					if (hidObj.value.indexOf(',') == 0) {
						hidObj.value = hidObj.value.substring(1);
					}
				}
			}
			}
		}
*/		
	}
}

//--------------------------------------------------
// Upload methods
//
var uploadDir = null
var uploadName = null
var uploader = null

function doUpload () {
  frames.uploader.document.forms[0].action = URL_UPLOAD_SERVLET + '/' + (uploadDir?uploadDir:'')
  frames.uploader.document.forms[0].submit()
}

function translateUrl (url) {
  
  var toReturn = url
  var p0 = toReturn.indexOf ('[', 0)
  while (p0 != -1) {
    var p1 = toReturn.indexOf (']', p0+1)
    if (p1 != -1) {
      var key = toReturn.substring (p0+1, p1)
      var value = getFormValue (self, key)
      toReturn = toReturn.substring (0, p0) + value + toReturn.substring (p1+1)
    }
    p0 = toReturn.indexOf ('[', p0+1);
  }
  
  return toReturn
}

function showBrowser (name, uploadToDir, props, noUnescape) {//allowedTypes, postUploadUrl, alertText, scale) {

  var isModal = false;
  var loc     = URL_UPLOAD
  loc += '?ProjectName=' + getProject()
  loc += '&dir=' + translateUrl(uploadToDir)
  loc += '&name=' + name
  if (props) {
  	if (noUnescape) {
  		loc += '&' + props
  	} else {
  		loc += '&' + unescape (props)
  	}
  }
/*  
  if (allowedTypes) {
    loc += '&allowedTypes=' + allowedTypes
  } else {
    loc += '&allowedTypes='
  }
  loc += '&name=' + name
  if (postUploadUrl) {
    loc += '&postUploadUrl=' + postUploadUrl
  } else {
    loc += '&postUploadUrl='
  }
  if (alertText) {
    loc += '&alertText=' + alertText
  } else {
    loc += '&alertText='
  }
  if (scale) {
    loc += '&scale=' + scale
  } else {
    loc += '&scale='
  }
*/  
//  alert (loc)
  var arg     = new Array ()
  var feats   = new Object ()

  feats.resizable = 1
  feats.titlebar = 0
  feats.width   = 320
  feats.height  = 100
  feats.left    = 300
  feats.top     = 300

  arg[0] = window
  arg[1] = name

  openWindow (isModal, loc, arg, feats)
}

function doBrowse (name, includeUploadButton, uploadToDir) {
  
  uploadDir = uploadToDir
  uploadName = name
  
  if (uploader == null) {
    uploader = frames.uploader
  }
  if (uploader == null) {
    alert ('Sorry for the inconvenience. Hey developer you forgot to include the uploader frame');
    return false
  }

  uploader.document.forms[0].file.click ();
//  alert (uploader.document.forms[0].file.mousedown)
  var fileInput = uploader.document.forms[0].file.value;
  
  var fileParts = null
  if (fileInput.indexOf ('\\') != -1) {
    fileParts = fileInput.split ('\\');
  } else {
    fileParts = fileInput.split ('/');
  }
  
  if (fileInput == '') {
  	return false
  }
  if (fileParts.length > 0) {
    fileName = fileParts[fileParts.length-1]
  }
  document.forms[0].elements[name].value = fileName
  
  if (! includeUploadButton) {
    doUpload ()
  }
  return true
}
function didUpload (error, file, frame) {
  
  uploader = frame
  
  if (error == '') {
  } else if (error == -1) {
    alert ('Upload failed.');
  } else if (error == 1) {
    alert ('Upload successful.');
  } else {
    window.status = file +":"+error
  }
}

function showDirectory (id) {
	
	var obj = document.forms[0].elements[id]
	var isModal = false;
	var title = "File_System"
	var feats = new Object ()
	
	feats.status  = 1
	feats.width   = 700
	feats.height  = 600
	feats.resizable  = 1
	
	var arg = new Array ()
	arg[0] = window
	arg[1] = obj
	
	var loc = URL_DIRECTORY + '?ElementId=' + id

	var win = openWindow (isModal, loc, arg, feats, title);
	if (win) {
		win.focusedItem = obj
	}
}

//---------------------------------------------
function updateSessionTimeout () {
	
	var now = new Date();
	if (top.maxSessionTime) {
		self.expireTime = now.getTime() + (top.maxSessionTime*1000);
		top.maxSessionTime = 0;
	}
	var interval = 5000;
	var obj = document.getElementById('sessionTimeout');
	
	if (obj && self.expireTime) {
		var dif = Math.floor((self.expireTime - now.getTime()) / 1000);
		if (dif > 0) {
			var hh = Math.floor(dif/3600);
			var mm = Math.floor((dif - hh*3600)/60); 
			var ss = dif%60;
			var tim = '';
			tim += ''  + (hh<10?'0':'') + hh;
			tim += ':' + (mm<10?'0':'') + mm;
			if (mm == 0) {
				tim += ':' + (ss<10?'0':'') + ss;
			}
			
			obj.innerText = 'Session timeout in ' + tim + ' hr';
			if (dif < 125) {
				interval = 1000;
			}
		} else {
			obj.innerText = 'Session timed out';
		}
		setTimeout ('updateSessionTimeout()', interval);
	}
}

function sessionTimeout () {
  var ok = confirm ('Session timed out. Press OK to reload site and login, or press Cancel to close this window.')
  if (ok) {
    top.location.reload ()
  } else {
    window.close ()
  }
  
}

function autofitIframe (id) {
	if (!window.opera && !document.mimeType && document.all && document.getElementById) {
		parent.document.getElementById(id).style.height = this.document.body.offsetHeight+"px";
		
	} else if (document.getElementById) {
		parent.document.getElementById(id).style.height=this.document.body.scrollHeight+"px"
	}
}

//----------------------------
// XML routines
//----------------------------
var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined'); 
if (moz) {
	// do not name any function in JS loadXML it will end up calling this prototype!
	Document.prototype.loadXML = MOZILLA_loadXML
	Node.prototype.__defineGetter__("xml", MOZILLA_getXml);
	Node.prototype.__defineGetter__("text", MOZILLA_getText);
	Node.prototype.__defineSetter__("text", MOZILLA_setText);
	Node.prototype.__defineGetter__("innerText", MOZILLA_getText);
	Node.prototype.__defineSetter__("innerText", MOZILLA_setText);
}
//----------------------------
function MOZILLA_loadXML (str) {

	if (str) {
		var xmlDoc = (new DOMParser()).parseFromString(str, 'text/xml')
	
		if (this.firstChild) {
			this.replaceChild (xmlDoc.firstChild, this.firstChild)
		} else {
			this.appendChild (xmlDoc.firstChild)
		}
	}
}

//----------------------------
function MOZILLA_getXml () {
    
    //create a new XMLSerializer
    var objXMLSerializer = new XMLSerializer;
    
    //get the XML string
    var strXML = objXMLSerializer.serializeToString(this);
    
    //return the XML string
    return strXML;
}
//----------------------------
function MOZILLA_getText () {
    
    var toReturn = ''
    for (var i = 0 ; i < this.childNodes.length ; i++) {
    	toReturn += this.childNodes[i].nodeValue
    }
    return toReturn
//    return this.firstChild ? this.firstChild.nodeValue : ''
}
//----------------------------
function MOZILLA_setText (str) {
    
  if (this.firstChild) {
  	this.firstChild.nodeValue = str
  } else {
  	var txtNode = this.ownerDocument.createTextNode (str)
  	this.appendChild (txtNode)
  }
}

//----------------------------
function createXML () {

	var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined'); 
	var ie = (typeof window.ActiveXObject != 'undefined'); 
	var xmlDoc = null
	
	if (moz) {
		xmlDoc = document.implementation.createDocument ("", "", null) 
		
	} else if (ie) { 
		xmlDoc = new ActiveXObject ("Microsoft.XMLDOM"); 
	}
	
	return xmlDoc
}


//----------------------------
function getElement (xmlDoc, name) {

  var elems = xmlDoc.getElementsByTagName (name)
  if (elems.length > 0) {
    return elems[0]
  }
  
  return null
}


//----------------------------
function doQuickLookupInsert(obj) {
	alert (obj.name)
}


//---------------------------------------------
function doFormRefresh () {
	document.forms[0].SCMD.value = 'Refresh'
	document.forms[0].submit()
}

//---------------------------------------------
function doBasketAdd (id) {
	var primkey = document.forms[0].PrimaryKey.value
	if (primkey) {
		var elem = document.forms[0].elements[primkey]
		if (!elem) {
			var hid = document.createElement('input')
			hid.name = primkey
			hid.value = id
			document.forms[0].appendChild(hid)
		}
	}
	doCommand('BasketAdd')
}
//---------------------------------------------
function doBasketRemove (id) {
	var primkey = document.forms[0].PrimaryKey.value
	if (primkey) {
		var elem = document.forms[0].elements[primkey]
		if (!elem) {
			var hid = document.createElement('input')
			hid.name = primkey
			hid.value = id
			document.forms[0].appendChild(hid)
		}
	}
	doCommand('BasketRemove')
}

//---------------------------------------------
function DOM_getParent(node, tag) {
	tag = tag.toLowerCase();
	while (node) {
		if (node.nodeType == 1) {
			if (node.tagName.toLowerCase() == tag) {
				break;
			}
		}
		node = node.parentNode;
	}
	return node;
}


//---------------------------------------------
function XMF_onrowselect(e) {
	
	e = e ? e : window.event;


	var obj = e.srcElement ? e.srcElement : e.target;
	
	obj = DOM_getParent(obj, 'tr');
	if (obj) {
		if (e.altKey) {
			var links = obj.getElementsByTagName('a');
			if (links && links.length) {
				document.location = links[0].href;
				return false;
				//alert(links[0].href)
			}
		}		
		if (obj.className == 'viewRowOdd' || obj.className == 'viewRow') {
  		var color = '#CDE8ED';
  		var styleObj = null;
	  	if (window.event) {
	  		self.lastRow = null;
	  		styleObj = obj.runtimeStyle;
	  	} else {
	  		styleObj = obj.style;
	  	}
	  	
  		if (styleObj.backgroundColor) {
	  		styleObj.backgroundColor = '';//'#D0F7FE'
  		} else {
	  		styleObj.backgroundColor = color;//'#D0F7FE'
  		}
	  	obj.onmouseout = null;
		}
	}	
}
	

//---------------------------------------------
function XMF_onrowhover() {
	
	if (!window.event) {
		return;
	}
	
	if (!self.viewRowHoverColor) {
		self.viewRowHoverColor = 'red'; // default
	  for (var j = 0 ; j < document.styleSheets.length ; j++) {
	  	var rules = document.styleSheets[j].rules;
	  	if (rules) {
			  for (var i = 0 ; i < rules.length ; i++) {
			    var rule = rules[i];
			    if (rule.selectorText.indexOf('.viewRowOdd:hover') != -1) {
			    	self.viewRowHoverColor = rule.style.backgroundColor;
			    }
			  }
			}
		}
	}

	var obj = event.srcElement;
	obj = DOM_getParent(obj, 'tr');
	if (obj) {
		if (obj.className == 'viewRowOdd' || obj.className == 'viewRow') {
	  	obj.runtimeStyle.backgroundColor = self.viewRowHoverColor;
			if (self.lastRow) {
				if (obj != self.lastRow) {
					self.lastRow.runtimeStyle.backgroundColor = '';
				}
			}	
	  	
	  	self.lastRow = obj;
	  	obj.onmouseout = function () {obj.runtimeStyle.backgroundColor = '';};
		}
	}
}


//---------------------------------------------
function rowClick (e) {
	
	e = e ? e : window.event;

	var obj = e.srcElement ? e.srcElement : e.target;
	
	obj = DOM_getParent(obj, 'tr');
	if (obj) {
		if (obj.className == 'viewRowOdd' || obj.className == 'viewRow') {
  		var color = '#CDE8ED';
	  	if (window.event) {
	  		self.lastRow = null;
	  		obj.runtimeStyle.backgroundColor = color;//'#D0F7FE'
	  	} else {
	  		if (obj.style.backgroundColor) {
		  		obj.style.backgroundColor = '';//'#D0F7FE'
	  		} else {
		  		obj.style.backgroundColor = color;//'#D0F7FE'
	  		}
	  	}
	  	obj.onmouseout = null;
		}
	}		
}

//---------------------------------------------
function rowHover() {
	
	if (window.event) {
		if (!self.viewRowHoverColor) {
			self.viewRowHoverColor = 'pink' // default
			for (var j = 0 ; j < document.styleSheets.length ; j++) {
			  for (var i = 0 ; i < document.styleSheets[j].rules.length ; i++) {
			    var rule = document.styleSheets[j].rules[i]
			    if (rule.selectorText.indexOf('.viewRowOdd:hover') != -1) {
			    	self.viewRowHoverColor = rule.style.backgroundColor
			    }
			  }
			}
		}
		var obj = event.srcElement
		while (obj) {
			if (obj.tagName == 'TR') {
				if (obj.className == 'viewRowOdd'
				 || obj.className == 'viewRowEven' || obj.className == 'viewRow'
			  ) {
			  	obj.runtimeStyle.backgroundColor = self.viewRowHoverColor
			  	obj.onmouseout = function () {obj.runtimeStyle.backgroundColor = '';}
				}
				break
			}
			obj = obj.parentNode
		}
	}
}

//------------
function rowCheckbox(e) {

	e = e ? e : window.event

	if (e.shiftKey) {
		var obj = e.srcElement ? e.srcElement : e.target
		var elements = document.forms[0].elements[obj.name]
		var foundIt = false;
		var isChecked = obj.checked;
		for (var i=elements.length-1 ; i >= 0 ; i--) {
			if (foundIt) {
				if (isChecked == elements[i].checked) {
					elements[i].checked = !isChecked
				} else {
					break;
				}
			}
			if (obj.value == elements[i].value) {
				foundIt= true
			}
		}
	}
}


//---------------------
function showTip(id) {
	var elem = document.getElementById(id)
	if (elem) {
		elem.style.display = elem.style.display?'':'none'
	}
}

//---------------------
function handleViewDelete (obj, url) {
	
	var ok = confirm ('Are you sure you want to delete this record?');
	if (ok) {
		var parent = obj;
		while (parent && parent.tagName) {
			if (parent.tagName.toLowerCase() == 'tr') {
				if (parent.className.indexOf('viewRow') == 0) {
					parent.parentNode.removeChild(parent);
				}
			}
			parent = parent.parentNode;
		}
		document.location = url;
		//return true;
	}
	//return true;
}