var DOM = (document.getElementById)?true:false;
var NN = (document.layers)?true:false;
var IE = (document.all)?true:false;
var isBuilt = false;
var masters = {};
var aIUD = new Array("_INSERT", "_UPDATE", "_DELETE");

var NEditor1=null, NEditorField1='', NEditorInstance1=null;


//---------------------- Ajax Pages Test ---------------------------

  function globalEval(code) {
    if (window.execScript) {
      window.execScript( code );
    } else if (window._GlobalEvalTest) {
      if (window._GlobalEvalTest == 1) window.eval( code ); else setTimeout( code, 0 );
    } else {
      window.eval( "var _GlobalEvalTest = 1;" );
      if (window._GlobalEvalTest) {
        window.eval( code );
      } else {
        window._GlobalEvalTest = 2;
        setTimeout( code, 0 );
      }
    }

  }

  function ajaxCallback(status, data, callId) {
    var _img = getElement( callId + '_WaitImage' );
    if (_img != null) {
      if (status == null) { // INIT
        _img.src = '/i/1.gif';  _img.alt = 'calling...';  _img.onclick = null;
      } else if (status < 0) { // AFTER SHORT TIMEOUT
        _img.src = '/i/ani-busy.gif';  _img.alt = 'click to cancel call...';  _img.onclick = ajaxCancel;
      } else {  // COMPLETED OK OR FAILED
        _img.src = '/i/1.gif';  _img.alt = '';  _img.onclick = null;
      }
    }
    if (status == 1) { // COMPLETED OK
      try {

if (data == '') alert('Error - empty data!');// else alert(data);
        if ((data != null) && (data != '') && (data.indexOf('\t') != -1)) {  // ELSE - REPORT ERROR IN OVERLAY!!!
//alert(data);
          var updateType = data.substr( 0, data.indexOf('\t') );
          data = data.substr( data.indexOf('\t') );

          var _scripts = [''];
          data = extractScripts( data, _scripts);

          if (updateType == 'ERROR_FRAME') {

           data = data.substr( data.indexOf('\tMAIN\t')+6 );
           var _div = getElement( 'AjaxFrameContent' );
           cleanupTinyMCE()
           _div.innerHTML = "" + data;
           globalEval( _scripts[0] );

          } else if (updateType == 'UPDATE_CONTENT') {

           data = data.substr( data.indexOf('\tCNTS\t')+6 );
           var _div = getElement( 'AjaxContent' );
           cleanupTinyMCE()
           _div.innerHTML = "" + data;
           globalEval( _scripts[0] );

          } else if (updateType == 'UPDATE_VARS_TABS_LEFT_CONTENT') {

           var _vars = data.substr( data.indexOf('\tVARS\t')+6 );
           var _divvars = getElement( 'AjaxVars' );
           _divvars.innerHTML = "" + _vars;

           data = data.substr( data.indexOf('\tTABS\t')+6 );
           var _tabs = data.substr( 0, data.indexOf('\tLEFT\t') );
           var _divtabs = getElement( 'AjaxTabs' );
           _divtabs.innerHTML = "" + _tabs;

           data = data.substr( data.indexOf('\tLEFT\t')+6 );
           var _left = data.substr( 0, data.indexOf('\tCNTS\t') );
           var _divLeft = getElement( 'AjaxLeft' );
           _divLeft.innerHTML = "" + _left;

           data = data.substr( data.indexOf('\tCNTS\t')+6 );
           var _cnts = data.substr( 0, data.indexOf('\tVARS\t') );
           var _div = getElement( 'AjaxContent' );
           cleanupTinyMCE()
           _div.innerHTML = "" + _cnts;

//       alert(_scripts[0]);
           globalEval( _scripts[0] );
//           try { eval( _scripts[0] ); } catch(errS) { alert(errS); };
          }
        }

      } catch(err) { };
    } else if (status == 0) { // failed or timed out
      alert('Error - status 0!');
    }
  };

  function cleanupTinyMCE() {
    document.frm.OnSubmit1 = null;
    document.frm.OnSubmit2 = null;
    if (window.tinyMCE && tinyMCE.editors) {
	for (n in tinyMCE.editors) {
		if (tinyMCE.editors.hasOwnProperty(n)) {
			tinyMCE.editors[n].remove();
		}
	}
    }
  }

  function extractScripts(html, scripts) {
    for (pos = html.indexOf('<script '); pos != -1;  pos = html.indexOf('<script ') ) {
      pos1 = html.indexOf('>', pos);
      pos2 = html.indexOf('</script>', pos);
//alert(pos1 + ', ' + pos2 + ', ' + html.substr(pos1+1, pos2 - pos1 - 1));
      scripts[0] = scripts[0] + html.substr(pos1+1, pos2 - pos1 - 1) + '\n';
      html = html.substr(0, pos) + html.substr(pos2+9);
    }
    return html;
  }

  function ajaxCancel() {
    asyncRequestCancel(ajaxCallback);
  };

  function ajaxCall( callId, submitType, responseType, timeoutInSeconds ) {
    if (timeoutInSeconds == null) timeoutInSeconds = 10;

    var _isGET = isGET();
    var map = _isGET ? __Public : __Main;
    var p1 = document.frm.action.lastIndexOf(";jsessionid");
    var p2 = document.frm.action.lastIndexOf("/");
    var addon = (p1 == -1) ? "" : document.frm.action.substring(p1, document.frm.action.length);
    var targetUrl = document.frm.action.substring(0,p2) + map + addon;
    var postData = "";
    for (i=0; i < document.frm.length; i++) {
      var ctrl = document.frm[i];
//alert('elTag = ' + ctrl.tagName + '    name = ' + ctrl.name + '    value = ' + ctrl.value);
      if ((ctrl.tagName == 'INPUT') || (ctrl.tagName == 'SELECT') || (ctrl.tagName == 'TEXTAREA')) {
        if ((ctrl.name != '') && !ctrl.disabled && (ctrl.value != null)) {
          if ((ctrl.type == "radio") || (ctrl.type == "checkbox")) {
            if (ctrl.checked) postData += ctrl.name + "=" + encodeURIComponent(ctrl.value) + "&";
          } else {
            postData += ctrl.name + "=" + encodeURIComponent(ctrl.value) + "&";
          }
        }
      }
    }
    if (submitType != null) postData += "SubmitType=" + encodeURIComponent(submitType) + "&";
    postData += "VT_AJAX=" + encodeURIComponent(responseType) + "&";
//alert(postData);
    asyncRequest( targetUrl, ajaxCallback, 1000, timeoutInSeconds * 1000, null, callId, postData);

  }


//---------------------- Iframe Pages Test ---------------------------

  function iframeCallback(status, data, callId) {
    var _img = getElement( callId + '_WaitImage' );
    if (_img != null) {
      if (status == null) { // INIT
        _img.src = '/i/1.gif';  _img.alt = 'calling...';  _img.onclick = null;
      } else if (status < 0) { // AFTER SHORT TIMEOUT
        _img.src = '/i/ani-busy.gif';  _img.alt = 'click to cancel call...';  _img.onclick = iframeCancel;
      } else {  // COMPLETED OK OR FAILED
        _img.src = '/i/1.gif';  _img.alt = '';  _img.onclick = null;
      }
    }
    var _elm = getElement( callId + '_Listener' );
    if (status == 1) { // COMPLETED OK
      try {

        _elm.iframeNotify(data);

      } catch(err) { };
    } else if (status == 0) { // failed
      _elm.iframeNotify(null);
    }
  };

  function iframeCancel() {
    iframeRequestCancel(iframeCallback);
  };

  function iframeCall( callId, submitType, responseType, timeoutInSeconds, _form ) {
    if (timeoutInSeconds == null) timeoutInSeconds = 10;
    var mfrm = (document.frm == null) ? window.parent.document.frm : document.frm;
    if (_form == null) _form = mfrm;
    var _isGET = isGET();
    var map = _isGET ? __Public : __Main;
    var p1 = mfrm.action.lastIndexOf(";jsessionid");
    var p2 = mfrm.action.lastIndexOf("/");
    var addon = (p1 == -1) ? "" : mfrm.action.substring(p1, mfrm.action.length);
    var targetUrl = mfrm.action.substring(0,p2) + map + addon;
    targetUrl += "?VT_AJAX=" + encodeURIComponent(responseType) + "&";
    if (submitType != null) targetUrl += "SubmitType=" + encodeURIComponent(submitType) + "&";
    iframeRequest( targetUrl, iframeCallback, 1000, timeoutInSeconds * 1000, callId, _form);

  }


//---------------------- Async Request ---------------------------
var postponeSubmit = false;
var asyncObj = null, iframeForm = null;
var resultCallback = null;  var resultCallbackParam = null;   var isPostData = false;
var fastTimeout = 0, cancelTimeout = 0, timerID = null;

function asyncRequest(targetURL, _resultCallback, _fastTimeout, _cancelTimeout, _noWait, _resultCallbackParam, _postData) {
  if ((isPostData == true) && (resultCallback != null)) return; // need explicit cancel when POST in progress!
  isPostData = (_postData != null);
  asyncRequestCancel(resultCallback);
  postponeSubmit = !(_noWait == true);
  if (_resultCallback != null) try { _resultCallback(null, "Init", _resultCallbackParam); } catch (e) { }
  if (asyncObj == null) {
    try { asyncObj = new XMLHttpRequest(); }
    catch (e1) {
      try { asyncObj = new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e2) { asyncObj = new ActiveXObject("Msxml2.XMLHTTP"); }
    }
    if (asyncObj == null) { alert("XMLHttpRequest is NULL"); return; }
  }
  asyncObj.onreadystatechange = asyncRequestCallback;
  resultCallback = _resultCallback;  resultCallbackParam = _resultCallbackParam;  fastTimeout = _fastTimeout;  cancelTimeout = _cancelTimeout;
  timerID = setTimeout("asyncRequestTimer()", (fastTimeout == 0) ? cancelTimeout : fastTimeout);
  asyncObj.open((_postData != null) ? "POST" : "GET", targetURL, true);
  if (_postData != null) {
//    asyncObj.setRequestHeader("Content-Type","text/html; charset=ISO-8859-1");
//    asyncObj.setRequestHeader("Content-Type","text/html; charset=ISO-8859-1");
    asyncObj.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
    asyncObj.setRequestHeader("Content-length", _postData.length);
    if (asyncObj.overrideMimeType) asyncObj.overrideMimeType("text/html; charset=ISO-8859-1");
  }
  asyncObj.setRequestHeader("Connection", "close");
  asyncObj.send(_postData);
}

function asyncRequestCancel(_resultCallback) {
  if ((asyncObj == null) || ((_resultCallback != null) && ((resultCallback == null) || (_resultCallback != resultCallback)))) return;
  if (timerID != null) {
    clearTimeout(timerID);  timerID = null;
  }
  var _func = resultCallback;   var _funcParam = resultCallbackParam;
  resultCallback = null;   resultCallbackParam = null;
  try { asyncObj.abort(); } catch (e) { }
  if (_resultCallback != null) try { _func(0, "Timeout", _funcParam); } catch (e) { }
  postponeSubmit = false;
}

function asyncRequestTimer() {
  if (timerID != null) {
    clearTimeout(timerID);  timerID = null;
    if (fastTimeout == 0) cancelTimeout = 0; else fastTimeout = 0;
  }
  if (cancelTimeout != 0) {
    var _func = resultCallback;   var _funcParam = resultCallbackParam;
    _func(-1, null, _funcParam);
    if (resultCallback != null) timerID = setTimeout("asyncRequestTimer()", cancelTimeout);
  } else {
    if (resultCallback != null) asyncRequestCancel(resultCallback);
  }
}

function asyncRequestCallback() {
  if (asyncObj.readyState == 4) {
//alert(asyncObj.status);
    if (asyncObj.status == 200) {
      var _func = resultCallback, text = asyncObj.responseText, _funcParam = resultCallbackParam;  resultCallback = null;
      asyncRequestCancel(null);
      try { _func(1, text, _funcParam); } catch (e) { }
    } else {
      var _func = resultCallback, text = asyncObj.responseText, _funcParam = resultCallbackParam;  resultCallback = null;
      asyncRequestCancel(null);
      try { _func(0, text, _funcParam); } catch (e) { }
    }
    postponeSubmit = false;
//alert('callback completed.');
  }
}

//---------------------- Iframe Request ---------------------------

function iframeRequest(targetURL, _resultCallback, _fastTimeout, _cancelTimeout, _resultCallbackParam, _form) {
  if ((isPostData == true) && (resultCallback != null)) return; // need explicit cancel when POST in progress!
  isPostData = true;
  var f = document.getElementById('UploadIFrame');
  if (f == null) {
    document.getElementById('UploadIFrameHolder').innerHTML = "<iframe onload='iframeRequestCallback()' src='about:blank' name='UploadIFrame' id='UploadIFrame' style='display:none'/>";
    f = document.getElementById('UploadIFrame');
  }
  if (iframeForm == null) asyncRequestCancel(resultCallback); else iframeRequestCancel(resultCallback);
  postponeSubmit = true;
  if (_resultCallback != null) try { _resultCallback(null, "Init", _resultCallbackParam); } catch (e) { }
  iframeForm = _form;
  iframeForm.action = targetURL;  iframeForm.method='post';
  iframeForm.enctype='multipart/form-data';  iframeForm.encoding='multipart/form-data';
  iframeForm.target = 'UploadIFrame';
  resultCallback = _resultCallback;  resultCallbackParam = _resultCallbackParam;  fastTimeout = _fastTimeout;  cancelTimeout = _cancelTimeout;
  timerID = setTimeout("asyncRequestTimer()", (fastTimeout == 0) ? cancelTimeout : fastTimeout);
  iframeForm.submit();
}

function iframeRequestCancel(_resultCallback) {
  if ((iframeForm == null) || ((_resultCallback != null) && ((resultCallback == null) || (_resultCallback != resultCallback)))) return;
  if (timerID != null) {
    clearTimeout(timerID);  timerID = null;
  }
  // restore iframeForm !!!
  iframeForm = null;
  var _func = resultCallback;   var _funcParam = resultCallbackParam;
  resultCallback = null;   resultCallbackParam = null;
  var f = document.getElementById('UploadIFrame');
  var d = (f.contentDocument) ? f.contentDocument : ((f.contentWindow) ? f.contentWindow.document : window.frames['UploadIFrame'].document);
  d.location.href = "about:blank";
  if (_resultCallback != null) try { _func(0, "Timeout", _funcParam); } catch (e) { }
  postponeSubmit = false;
}

function iframeRequestTimer() {
  if (timerID != null) {
    clearTimeout(timerID);  timerID = null;
    if (fastTimeout == 0) cancelTimeout = 0; else fastTimeout = 0;
  }
  if (cancelTimeout != 0) {
    var _func = resultCallback;   var _funcParam = resultCallbackParam;
    _func(-1, null, _funcParam);
    if (resultCallback != null) timerID = setTimeout("iframeRequestTimer()", cancelTimeout);
  } else {
    if (resultCallback != null) iframeRequestCancel(resultCallback);
  }
}

function iframeRequestCallback() {
    var f = document.getElementById('UploadIFrame');
    var d = (f.contentDocument) ? f.contentDocument : ((f.contentWindow) ? f.contentWindow.document : window.frames['UploadIFrame'].document);
    if (d.location.href == "about:blank") return;
    var text = d.body.innerHTML;
    d.location.href = "about:blank";
    var _func = resultCallback, _funcParam = resultCallbackParam;  resultCallback = null;
    iframeRequestCancel(null);
    try { _func( ((text != null) && (text != '')) ? 1 : 0, text, _funcParam); } catch (e) { }
    postponeSubmit = false;
}

//---------------------- Help for fields -----------------------
function getHelp(targetURL, iIcon) {
  var helpFieldBox = getElement("rightHelpForFieldBox");
  var helpPageBox = getElement("rightHelpForPageBox");
  if ((helpFieldBox == null) || (helpPageBox == null)) return;
  if (iIcon != null) {
    var oldIcon = helpFieldBox.iIcon;
    if (oldIcon != null) {
      drawOver(oldIcon,'-over','-off');
      helpFieldBox.iIcon = null;
    }
    if (iIcon != oldIcon) {
      drawOver(iIcon,'-off','-over');
      helpFieldBox.iIcon = iIcon;
    } else {
      helpFieldBox.style.display = "none";
      helpPageBox.style.display = "block";
      return;
    }
  }
  asyncRequest(targetURL, helpCallback, 1000, 5000, true);
}

function helpCallback(status, data) {
  var helpFieldBox = getElement("rightHelpForFieldBox");
  var helpPageBox = getElement("rightHelpForPageBox");
  if ((helpFieldBox == null) || (helpPageBox == null)) return;
  if (helpFieldBox.iIcon != null) {
    helpPageBox.style.display = "none";
    helpFieldBox.style.display = "block";
    if (status == null) {
      helpFieldBox.innerHTML = "";
    } else if (status < 0) {
      helpFieldBox.innerHTML = "...loading help...";
    } else {
      helpFieldBox.innerHTML = "";
    }
    if (status == 1) {
      helpFieldBox.innerHTML = data;
    } else if (status != null) {
//    helpBox.innerHTML = "Help request faild with HTTP code '" + data + "'";
    }
  }
}

//---------------------- Poststed from postnummer -----------------
var lastTargetField = null;
var lastTargetImage = null;
function getPoststed(targetURL, targetField, targetImage) {
  lastTargetField = targetField;
  lastTargetImage = targetImage;
  document.frm[targetField].value = "";
  asyncRequest(targetURL, poststedCallback, 1000, 10000);
}
function poststedCancel() {
  asyncRequestCancel(poststedCallback);
}
function poststedCallback(status, data) {
  if (lastTargetImage != null) {
    var _img = getElement(lastTargetImage);
    if (status == null) {
      _img.src = poststedIMG2;
      _img.alt = poststedTXT2;
      _img.onclick = null;
    } else if (status < 0) {
      _img.src = poststedIMG3;
      _img.alt = poststedTXT3;
      _img.onclick = poststedCancel;
    } else {
      _img.src = poststedIMG1;
      _img.alt = poststedTXT1;
      _img.onclick = null;
    }
  }
  if (status == 1) {
    document.frm[lastTargetField].value = data;
  }
}
//---------------------------------------------------------

function restrictEditBoxLength(control, maxChars) {
  if ((control == null) || (control.value == null) || (maxChars == 0)) return;
  if (control.value.length > maxChars) control.value = control.value.substr(0,maxChars);
}

//------------ table row select ---------------------------------------------

 function _cancel(e) {
   if (!e) e = window.event;
   e.cancelBubble = true;
   if (e.stopPropagation) e.stopPropagation();
   return false;
 }
 function _getTable(row) {
   while (row.tagName != 'TABLE') row = row.parentNode;
   return row;
 }
 function RowSel(row) {
   var table = _getTable(row);
   RowUnsel(table);
   row.oldbgcolor = row.style.backgroundColor;
   row.style.backgroundColor = '#D0E2ED';
   table.selrow = row;
 }
 function RowUnsel(row) {
   var table = _getTable(row);
   if (table.selrow != null) {
     table.selrow.style.backgroundColor = table.selrow.oldbgcolor;
     table.selrow = null;
   }
 }
 function findNode(startingNode, tagName) {
   var myElement = startingNode;
   var i=0;
   while (myElement && (!myElement.tagName || (myElement.tagName && myElement.tagName!=tagName))) myElement = startingNode.childNodes[i++];
   if (myElement && myElement.tagName && myElement.tagName==tagName) return myElement;
   if (startingNode.firstChild) return findNode(startingNode.firstChild, tagName);
   return null;
 }
 function RowClick(row) {
   var cell = findNode(row, 'TD');   if (cell == null) return;
//alert(cell.firstChild.tagName);
   var _a = findNode(cell, 'A');     if (_a == null) return;
//alert(_a.href);
   if (_a.href != null) {
     if (_a.href.indexOf("javascript:") == 0) {
//       alert("eval!=" + _a.href.substr("javascript:".length));
       eval(_a.href.substr("javascript:".length));
     } else if (_a.href != "") {
       window.location.replace(_a.href);
     }
   }
   return false;
 }
//---------------------------------------------------------

function getElement(objname)
{
//  if (IE) {
//    return document.all[objname];
//  }
  if (NN) {
    return getNNElement(null, objname);
  }
  if (DOM) {
    var el = document.getElementById(objname);
    if (el == null) return el;
    var i = 1;
    var eli = null;
    var elia = null;
    while ((eli = document.getElementById(objname + "__i" + i)) != null) {
      if (elia == null) { elia = new Array();  elia[0] = el; }
      elia[i] = eli;
      i++;
    }
    return (elia == null) ? el : elia;
  }
}

function getFirstElement(objname)
{
  if (IE) return (document.all[objname][0] == null) ? document.all[objname] : document.all[objname][0];
  if (NN) return (getNNElement(null, objname)[0] == null) ? getNNElement(null, objname) : getNNElement(null, objname)[0];
  if (DOM) return document.getElementById(objname);
}

function dummy(){
	return;
}

function setParameter(name, value) {
  document.frm[name].disabled = (value == null);
  document.frm[name].value = (value == null) ? "" : value;
}

function setAutoParameter(name, value) {
  if ("GET" == name) {
    setGET( ((value == "true") || (value == true)) ? true : false );
  } else {
    var _isGET = (isGET != null) ? isGET() : false;
    var _name = (_isGET ? "Current" : "New") + name;
    if (document.frm[_name] == null) _name = name;
    if (document.frm[_name] != null) {
      document.frm[_name].disabled = (value == null);
      document.frm[_name].value = (value == null) ? "" : value;
//alert('setting: ' + document.frm[_name].tagName + '    name = ' + document.frm[_name].name + '    value = ' + document.frm[_name].value);
    }
  }
}

function isGET() { return (__isGET != null) ? __isGET : false; }
function setGET(value) { if (__isGET != null) __isGET = value; }

function setOverlay(overlay, overlayData) {
  if (overlay == null) overlay = document.frm.CurrentOverlay.disabled ? null : document.frm.CurrentOverlay.value;
  if (overlayData == null) overlayData = document.frm.CurrentOverlayData.disabled ? null : document.frm.CurrentOverlayData.value;
  setParameter("NewOverlay", overlay);
  setParameter("NewOverlayData", overlayData);
}

var submitting = false, delayedSubmitTimer = null, delayedSubmitType, delayedNewState, delayedNewRowID, delayedHelpID;
function frmSubmit(submitType, newState, newRowID, helpID ){
//alert(document.frm.name);
        if (submitting) return; else submitting = true;
        if (postponeSubmit) {
          delayedSubmitType = submitType; delayedNewState = newState; delayedNewRowID = newRowID; delayedHelpID = helpID;
          delayedSubmitTimer = setTimeout("delayedFrmSubmit()", 500);
          return;
        }
        var _isGET = isGET();
	if(submitType == "DUMMY") return false;
	if (document.frm.OnSubmit1 != null) document.frm.OnSubmit1();
	if (document.frm.OnSubmit2 != null) document.frm.OnSubmit2();
	if(!_isGET && (submitType != null)) { document.frm.SubmitType.disabled = false; document.frm.SubmitType.value = submitType; }
	if(!_isGET && (newState != null)) { document.frm.NewState.disabled = false; document.frm.NewState.value = newState; }
	if(!_isGET && (newRowID != null) && (document.frm.NewRowID != null) && ((newRowID != '') || (helpID == null))) { document.frm.NewRowID.disabled = false; document.frm.NewRowID.value = newRowID; }
	if(helpID != null) { document.frm.NewHelpID.disabled = false; document.frm.NewHelpID.value = helpID; }
	check();
        var map = _isGET ? __Public : __Main;
        var p1 = document.frm.action.lastIndexOf(";jsessionid");
        var p2 = document.frm.action.lastIndexOf("/");
        var addon = (p1 == -1) ? "" : document.frm.action.substring(p1, document.frm.action.length);
        document.frm.action = document.frm.action.substring(0,p2) + map + addon;
        document.frm.enctype = _isGET ? "application/x-www-form-urlencoded" : "multipart/form-data";
        document.frm.encoding = _isGET ? "application/x-www-form-urlencoded" : "multipart/form-data";
        document.frm.method = _isGET ? "get" : "post";
        if (_isGET && (newState != null)) { document.frm.CurrentState.disabled = false; document.frm.CurrentState.value = newState; }
        if (_isGET && document.frm.LangBox != null) document.frm.LangBox.disabled = true;
        if (_isGET && document.frm.LoginName != null) document.frm.LoginName.disabled = true;
        if (_isGET && document.frm.LoginPassword != null) document.frm.LoginPassword.disabled = true;
//alert("Navn = " + document.frm["FLD_1"].value);
        document.frm.submit();
}
function ajaxFrmSubmit(submitType, newState, newRowID){
//alert(document.frm.name);
        if (submitting) return;
        var _isGET = isGET();
	if(submitType == "DUMMY") return false;
	if (document.frm.OnSubmit1 != null) document.frm.OnSubmit1();
	if (document.frm.OnSubmit2 != null) document.frm.OnSubmit2();
	if(!_isGET && (submitType != null)) { document.frm.SubmitType.disabled = false; document.frm.SubmitType.value = submitType; }
	if(!_isGET && (newState != null)) { document.frm.NewState.disabled = false; document.frm.NewState.value = newState; }
	if(!_isGET && (newRowID != null) && (document.frm.NewRowID != null) && ((newRowID != '') || (helpID == null))) { document.frm.NewRowID.disabled = false; document.frm.NewRowID.value = newRowID; }
//	check();
//alert("Navn = " + document.frm["FLD_1"].value);
        ajaxCall( 'FRMSUBMIT', submitType, 'UPDATE_VARS_TABS_LEFT_CONTENT', 60 );
}
function autoFrmSubmit(submitType, newState, newRowID) {
  ajaxFrmSubmit(submitType, newState, newRowID);
}

function delayedFrmSubmit() {
  if (delayedSubmitTimer != null) {
    clearTimeout(delayedSubmitTimer);  delayedSubmitTimer = null;
  }
  if (!submitting) return;
  if (postponeSubmit) {
    delayedSubmitTimer = setTimeout("delayedFrmSubmit()", 500);
    return;
  }
  submitting = false;
  frmSubmit(delayedSubmitType, delayedNewState, delayedNewRowID, delayedHelpID);
}

function drawOver(oImg, sOld, sNew){
	var sSrc = oImg.src;
	sSrc = sSrc.replace(sOld,sNew);
	oImg.src = sSrc;
}

function isDisabled(sName){
        return val_disabled[sName] != null;
//	for(var i=0;i<val_disabled.length;i++){
//	   if(sName==val_disabled[i]) return true;
//	}
//	return false;
}

function foundIn(oObj, arr){
        return masters[oObj.name] != null;
//	for(var i=0;i<masters.length;i++)
//	   if(oObj.name==masters[i]) return true;
//	return false;
}

function enableDisableFrmElement(oName, bEnable){
	     var elfrm = document.frm[oName];
	     if (elfrm == null) return;
	     if (((elfrm.type == null) || (elfrm.type!='select-one')) && (elfrm.length > 1)) {
               for(var ie=0;ie<elfrm.length;ie++){
	         if(elfrm[ie].name==oName){
	           elfrm[ie].disabled=!bEnable;
	           if((elfrm[ie].type!="radio") && (elfrm[ie].type!="checkbox")) {
			elfrm[ie].style.backgroundColor= bEnable ? '' : '#F0F0F0';
		   }
		   if (bEnable) state(elfrm[ie]); else stateOff(elfrm[ie]);
	         }
	       }
	     } else {
	           elfrm.disabled=!bEnable;
	           if((elfrm.type!="radio") && (elfrm.type!="checkbox")) {
			elfrm.style.backgroundColor= bEnable ? '' : '#F0F0F0';
		   }
		   if (bEnable) state(elfrm); else stateOff(elfrm);
	     }
}

function state(oObj){
	var len;
	var oVal;

	if(!isBuilt) return;
	if(!foundIn(oObj, masters)) return;

	switch(oObj.type){
	case "checkbox":
	   oVal = oObj.checked?'true':'false';
	   break;
	case "radio":
	   oVal = oObj.value;
//alert(oVal);
	   if (!oObj.checked) return;
	   break;
	case "select-one":
	   oVal = oObj.options[oObj.selectedIndex].value;
//	   if (oVal == null) oVal = "";
	   break;
	}


	var val_idx = eval("val_"+(oObj.name).replace(" ","")+"_idx");
	if (oVal == null) oVal = "";
	var j = val_idx[oVal];
	var val_off = eval("val_"+(oObj.name).replace(" ","")+"_off");
	var val_on = eval("val_"+(oObj.name).replace(" ","")+"_on");


//	for(var j=0;j<val_off.length;j++){
        if((j != null) && (val_off[j][0] == oVal)) {
	  for(var i=1;i<val_off[j].length;i++){
	     var oName = val_off[j][i];
	     if(isDisabled(oName)) continue;

	     var el = getElement("ID_"+oName);
	     if(el != null)
	       if(el.length != null){
	         for(var m=0; m < el.length; m++)
		   if(el[m] != null){
		     el[m].style.color = (el[m].color_off == null) ? "darkgray" : el[m].color_off;
		     if(el[m].href != null){ el[m].name=el[m].href; el[m].href="#";}
		   }
	       }
	       else
	         if(el != null) el.style.color = (el.color_off == null) ? "darkgray" : el.color_off;

	     for(var m=0;m<aIUD.length;m++){
		var el1 = getElement("ID_"+oName+aIUD[m]);
		var el2 = getElement("ID_"+oName+aIUD[m]+"_IMG");
		if((el1 != null) && (el1.href!="javascript:dummy();")) {
		  el1.name=el1.href;
		  el1.href="javascript:dummy();";
		}
		if(el2 != null){
		  el2.disabled = true;
//		  el2.onmouseover="";
//		  el2.onmouseout="";
		}
	     }

             enableDisableFrmElement(oName, false);
//	     for(var ie=0;ie<document.frm.elements.length;ie++){
//	        if(document.frm.elements[ie].name==oName){
//	           document.frm.elements[ie].disabled=true;
//	           if((document.frm.elements[ie].type!="radio") && (document.frm.elements[ie].type!="checkbox")) {
//			document.frm.elements[ie].style.backgroundColor='#F0F0F0';
//		   }
//		   stateOff(document.frm.elements[ie]);
//	        }
//	     }
	  }
	}

//	for(var j=0;j<val_on.length;j++){
	if((j != null) && (val_on[j][0] == oVal)) {
	  for(var i=1;i<val_on[j].length;i++){
	     var oName = val_on[j][i];
	     if(isDisabled(oName)) continue;

	     var el = getElement("ID_"+oName);
	     if(el != null)
	       if(el.length != null){
	         for(var m=0; m < el.length; m++)
		   if(el[m] != null){
		     el[m].style.color = "";
		     if(el[m].href != null){if(el[m].name != "") el[m].href=el[m].name;}
		   }
	       }
	       else
	         if(el != null) el.style.color = "";

	     for(var m=0;m<aIUD.length;m++){
		var el1 = getElement("ID_"+oName+aIUD[m]);
		var el2 = getElement("ID_"+oName+aIUD[m]+"_IMG");
		if((el1 != null) && (el1.href=="javascript:dummy();")) {
		  el1.disabled = false;
		  if(el1.name != "") el1.href=el1.name;
		}
		if(el2 != null){
		  el2.disabled = false;
//		  el2.onmouseover="\"drawOver(this,'-off','-over')\"";
//		  el2.onmouseout="\"drawOver(this,'-over','-off')\"";
		}
	     }

             enableDisableFrmElement(oName, true);
//	     for(var ie=0;ie<document.frm.elements.length;ie++){
//	        if(document.frm.elements[ie].name==oName){
//	           document.frm.elements[ie].disabled=false;
//	           if((document.frm.elements[ie].type!="radio") && (document.frm.elements[ie].type!="checkbox")) {
//			document.frm.elements[ie].style.backgroundColor='';
//		   }
//		   state(document.frm.elements[ie]);
//	        }
//	     }
	  }
	}
}

function stateOff(oObj){
	if(!isBuilt) return;
	if(!foundIn(oObj, masters)) return;

	var val_off = eval("val_"+(oObj.name).replace(" ","")+"_off");
	var doneObjs = {};

	for(var j=0;j<val_off.length;j++){
	  for(var i=1;i<val_off[j].length;i++){
	     var oName = val_off[j][i];
	     if (doneObjs[oName] != null) continue;
             doneObjs[oName] = "";

	     var el = getElement("ID_"+oName);
	     if(el != null)
	       if(el.length != null){
	         for(var m=0; m < el.length; m++)
		   if(el[m] != null){
		     el[m].style.color = (el[m].color_off == null) ? "darkgray" : el[m].color_off;
		     if(el[m].href != null){ /*el[m].name=el[m].href; el[m].href="";*/}
		   }
	       }
	       else
	         if(el != null) el.style.color = (el.color_off == null) ? "darkgray" : el.color_off;

	     for(var m=0;m<aIUD.length;m++){
		var el1 = getElement("ID_"+oName+aIUD[m]);
		var el2 = getElement("ID_"+oName+aIUD[m]+"_IMG");
		if((el1 != null) && (el1.href!="javascript:dummy();")) {
		  el1.name=el1.href;
		  el1.href="javascript:dummy();";
		}
		if(el2 != null){
		  el2.disabled = true;
//		  el2.onmouseover="";
//		  el2.onmouseout="";
		}
	     }

             enableDisableFrmElement(oName, false);
//	     for(var ie=0;ie<document.frm.elements.length;ie++){
//	        if(document.frm.elements[ie].name==oName){
//	           document.frm.elements[ie].disabled=true;
//	           if((document.frm.elements[ie].type!="radio") && (document.frm.elements[ie].type!="checkbox")) {
//			document.frm.elements[ie].style.backgroundColor='#F0F0F0';
//		   }
//	        }
//	     }
	  }
	}
}

function init(){
	isBuilt = true;
	for(var n=0;n<arguments.length;n++){
	   var oName = arguments[n];

	   masters[oName] = "";

	   var el = document.frm[oName];
	   if(el.type=='select-one'){
	      stateOff(el);
	      if(!(el.disabled)){
		state(el);
	      }
	   } else if(el.length > 1){
	      var el2 = el[0];
	      if(el2.type=='checkbox' && !(el2.disabled)){
		state(el2);
	      } else {
		for(var i=0;i<el.length;i++){
		   var el3 = el[i];
                   stateOff(el3);
		}
		for(var i=0;i<el.length;i++){
		   var el3 = el[i];
		   if(el3.checked && !(el3.disabled)){
                      state(el3);
		      break;
		   }
		}
	      }
	   }

	}
}

function check(){
	for(var i=0;i<document.frm.elements.length;i++){
	   var el=document.frm.elements[i];
	   if((el.type=='checkbox') && (el.name != '') && (document.frm[el.name][1] != null)) {
	     document.frm[el.name][1].disabled=el.checked;
	     if(el.disabled)document.frm[el.name][1].disabled=true;
	   }

	   if(el.type=='select-one'){
	     if((el.selectedIndex < 0) || (el.options[el.selectedIndex].value=="")) el.name="";
	   }

	   if(el.disabled){
	      el.name="";
	   }
	}
	return true;
}

function clear_list(obj){
//   obj.length=1;
//   obj.options[0].value="";
//   obj.options[0].text="";
   while(obj.firstChild) {
      obj.removeChild(obj.firstChild);
   }
   var oOption = document.createElement("OPTION");
   oOption.value = "";
   oOption.text = "";
   oOption.innerHTML = oOption.text;
   obj.appendChild(oOption);
   obj.selectedIndex=0;
   obj.length = 1;
   state(obj);
}

function fill_list(obj, val1, txt1, val){
   if(val1 == undefined || txt1 == undefined) return;
   for(var i=0; i < val1.length; i++){
      var oOption = document.createElement("OPTION");
      oOption.value = val1[i];
      oOption.text = txt1[i];
      oOption.innerHTML = oOption.text;
//      obj.options.add(oOption);
      obj.appendChild(oOption);
      if(oOption.value == val) {
        obj.selectedIndex = i+1;
      }
   }
   obj.length = 1 + val1.length;
}

function filter(level){
   var obj, val;
   var arr1;
   var arrt;
   var undef=0;
   if(level == "1"){
     return;
   }
   if(level == "2"){
     return;
   }
   var obj0 = getElement("id_0");
   var idx1 = obj0.selectedIndex-1;
   var obj1 = getElement("id_1");
   var idx2 = obj1.selectedIndex-1;
   var val1 = obj1.value;
   if(level == "0"){
     clear_list(obj1);
     if(idx1 < 0) { return;}
     eval( "if(typeof(F_"+idx1+") == 'undefined') undef=1;" );
     if(undef == 1) { return;}
     arr1 = eval("F_"+idx1);
     arrt = eval("T_"+idx1);
     if (arrt==null) arrt = arr1;
     obj = obj1;
     val = val1;
   }
   fill_list(obj, arr1, arrt, val);
}

/*
function filter(level){

   var obj, val;
   var arr1;
   var arrt;
   var undef=0;

   if(level == "2"){
     return;
   }


   var obj0 = getElement("id_0");
   var idx1 = obj0.selectedIndex-1;

   var obj1 = getElement("id_1");
   var idx2 = obj1.selectedIndex-1;
   var val1 = obj1.value;
   var obj2 = getElement("id_2");
   var val2 = obj2.value;


   if(level == "1"){
     clear_list(obj2);
     if(idx2 < 0) return;
     eval( "if(typeof(F_"+idx1+"_"+idx2+") == 'undefined') undef=1;" );
     if(undef == 1) return;
     arr1 = eval("F_"+idx1+"_"+idx2);
     arrt = eval("T_"+idx1+"_"+idx2);
     if (arrt==null) arrt = arr1;
     obj = obj2;
     val = val2;
   }

   if(level == "0"){
     clear_list(obj1);
     if(idx1 < 0) {clear_list(obj2); return;}

     eval( "if(typeof(F_"+idx1+") == 'undefined') undef=1;" );
     if(undef == 1) {clear_list(obj2); return;}
     arr1 = eval("F_"+idx1);
     arrt = eval("T_"+idx1);
     if (arrt==null) arrt = arr1;
     obj = obj1;
     val = val1;
   }


   fill_list(obj, arr1, arrt, val);

   if(obj==obj1 && obj.selectedIndex == 0) clear_list(obj2);
}
*/
function filter_roles(level){

   var obj, val;
   var arr1;
   var undef=0;

   if(level == "1"){
     return;
   }

   var obj0 = getElement("id_0");
   var idx1 = obj0.selectedIndex-1;

   var obj1 = getElement("id_1");
   var val = obj1.value;

   clear_list(obj1);
   if(idx1 < 0) return;

   var val1 = RolesValue[idx1];
   var txt1 = RolesText[idx1];

   fill_list(obj1, val1, txt1, val);
}

/******************** document sizes  ****************************/

function getDocumentSize(){
	return [
	document.body.scrollWidth > document.body.offsetWidth ? 
		document.body.scrollWidth : document.body.offsetWidth,
	document.body.scrollHeight > document.body.offsetHeight ? 
		document.body.scrollHeight : document.body.offsetHeight
	];
}

function getClientSize(){
	if(document.compatMode=='CSS1Compat')
		return [document.documentElement.clientWidth, document.documentElement.clientHeight];
	else
		return [document.body.clientWidth, document.body.clientHeight];
}

function getDocumentScroll(){
	return [
	self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) 
		|| (document.body && document.body.scrollLeft),
	self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) 
		|| (document.body && document.body.scrollTop)
	];
}

function getClientCenter(){
	var sizes = getClientSize();
	var scrl = getDocumentScroll();
	return [parseInt(sizes[0]/2)+scrl[0], parseInt(sizes[1]/2)+scrl[1]];
}

/**************************************** Universal SPLIT  ****************/
/*
	Cross-Browser Split 0.2.1	By Steven Levithan <http://stevenlevithan.com>	MIT license
*/

var nativeSplit = nativeSplit || String.prototype.split;

String.prototype.split = function (s /* separator */, limit) {
	// If separator is not a regex, use the native split method
	if (!(s instanceof RegExp))
		return nativeSplit.apply(this, arguments);

	/* Behavior for limit: If it's...
	 - Undefined: No limit
	 - NaN or zero: Return an empty array
	 - A positive number: Use limit after dropping any decimal
	 - A negative number: No limit
	 - Other: Type-convert, then use the above rules */
	if (limit === undefined || +limit < 0) {
		limit = false;
	} else {
		limit = Math.floor(+limit);
		if (!limit)
			return [];
	}

	var	flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") + (s.multiline ? "m" : ""),
		s2 = new RegExp("^" + s.source + "$", flags),
		output = [],
		lastLastIndex = 0,
		i = 0,
		match;

	if (!s.global)
		s = new RegExp(s.source, "g" + flags);

	while ((!limit || i++ <= limit) && (match = s.exec(this))) {
		var zeroLengthMatch = !match[0].length;

		// Fix IE's infinite-loop-resistant but incorrect lastIndex
		if (zeroLengthMatch && s.lastIndex > match.index)
			s.lastIndex = match.index; // The same as s.lastIndex--

		if (s.lastIndex > lastLastIndex) {
			// Fix browsers whose exec methods don't consistently return undefined for non-participating capturing groups
			if (match.length > 1) {
				match[0].replace(s2, function () {
					for (var j = 1; j < arguments.length - 2; j++) {
						if (arguments[j] === undefined)
							match[j] = undefined;
					}
				});
			}

			output = output.concat(this.slice(lastLastIndex, match.index), (match.index === this.length ? [] : match.slice(1)));
			lastLastIndex = s.lastIndex;
		}

		if (zeroLengthMatch)
			s.lastIndex++;
	}

	return (lastLastIndex === this.length) ?
		(s.test("") ? output : output.concat("")) :
		(limit      ? output : output.concat(this.slice(lastLastIndex)));
};


   //---------------------- links ----------------------------------------

    function setLinkType(_form, type) {
      document.getElementById('Link_filePane').style.display = (type == 2) ? 'block' : 'none';
      document.getElementById('Link_treePane').style.display = ((type == 3) || (type == 4)) ? 'block' : 'none';
      document.getElementById('Link_emptyPane').style.display = ((type == null) || (type == 1)) ? 'block' : 'none';
      _form['Link_type'][(type == null) ? 0 : (type - 1)].checked = true;
    }

    function FileSelectById(dbid) {
      var filePaneDiv = document.getElementById('FilePane');
      for (node = filePaneDiv.firstChild; node != null; node = node.nextSibling) if (node.tagName == 'DIV') {
        if (node.FILE_dbid == dbid) { FileClick(node); return; }
      }
//      document.getElementById('_file').innerHTML = '';
    }

    function FileClick(divLine) {
      var filePaneDiv = document.getElementById('FilePane');
      filePaneDiv.FileClick('?VT_FILE=' + divLine.FILE_dbid + "_ENVELOPE", divLine.FILE_name);
//      var _form = ParentTag(divLine, "FORM");
//      document.getElementById('_file').innerHTML = divLine.FILE_name;
//      _form['Link_url'].value = '?VT_FILE=' + divLine.FILE_dbid + "_ENVELOPE";
    }

    function OnTreeClick(_form, dbid) {
      var treePaneDiv = document.getElementById('TreePane');
      if (_form['Link_type'][2].checked) {
        treePaneDiv.TreeClick('?CurrentDoc=' + dbid);
//        _form['Link_url'].value = '?CurrentDoc=' + dbid;
      } else if (_form['Link_type'][3].checked) {
        treePaneDiv.TreeClick('?VT_PRNOUT=' + dbid);
//        _form['Link_url'].value = '?VT_PRNOUT=' + dbid;
      }
    }

    function setTitleAndUrl(_form, title, url) {
      var type = 0;
      if (url == null) url = "";
      else if (url.startsWith('?VT_FILE=')) type = 1;
      else if (url.startsWith('?CurrentDoc=')) type = 2;
      else if (url.startsWith('?VT_PRNOUT=')) type = 3;
      setLinkType(_form, type+1);
      TreeSelect(null);
      FileSelectById(null);
      _form['Link_title'].value = title;
      _form['Link_url'].value = url;
      if (url.indexOf('_ENVELOPE') != -1) url = url.substr(0, url.indexOf('_ENVELOPE'));
      if (type > 1) {
        var dbid = url.substr(url.indexOf('=')+1, url.length);
        TreeSelectById(dbid);
      } else if (type == 1) {
        var dbid = parseInt(url.substr(url.indexOf('=')+1, url.length),10);
        FileSelectById(dbid);
      }
    }

    function getTitle(_form) { return _form['Link_title'].value; }
    function getUrl(_form) { return _form['Link_url'].value; }
    function getTarget(_form) { return (_form['Link_type'][0].checked || _form['Link_type'][3].checked) ? '_blank' : ''; }

    function FillFilePane(filePaneDiv, fileArray) {  // [dbid, name]
      if ((filePaneDiv == null) || (fileArray == null)) return;
      for (i=0; i < fileArray.length; i=i+2) {
        var line = document.createElement('DIV');
        line.innerHTML = "<div style='cursor:pointer' onclick='FileClick(this.parentNode);'>"+ fileArray[i+1] +"</div>";
        line.FILE_dbid = fileArray[i+0];  line.FILE_name = fileArray[i+1];
        filePaneDiv.appendChild(line);
      }
    }

   //---------------------- images ----------------------------------------

    function ImageSelectById(dbid) {
      var imagePaneDiv = document.getElementById('ImagePane');
      for (node = imagePaneDiv.firstChild; node != null; node = node.nextSibling) if (node.tagName == 'DIV') {
        if (node.IMAGE_dbid == dbid) { ImageClick(node); return; }
      }
//      document.getElementById('_image').innerHTML = '';
//      document.getElementById('_imagePreview').src = 'i/1.gif';
    }

    function ImageClick(divLine) {
      var imagePaneDiv = document.getElementById('ImagePane');
      imagePaneDiv.ImageClick('?VT_FILE=' + divLine.IMAGE_dbid, divLine.IMAGE_name);
//      var _form = ParentTag(divLine, "FORM");
//      document.getElementById('_image').innerHTML = divLine.IMAGE_name;
//      document.getElementById('_imagePreview').src = _form['Image_src'].value = '?VT_FILE=' + divLine.IMAGE_dbid;
    }

    function setSrcAltAndAlign(_form, src, alt, align) {
      var type = 0;
      if (src == null) src = ""; else if (src.startsWith('?VT_FILE=')) type = 1;
      ImageSelectById(null);
      _form['Image_alt'].value = alt;
      _form['Image_src'].value = src;
      _form['Image_align'].value = align;
      var dbid = (type > 0) ? parseInt(src.substr(src.indexOf('=')+1, src.length),10) : null;
      if (type == 1) ImageSelectById(dbid);
    }

    function getAlt(_form) { return _form['Image_alt'].value; }
    function getSrc(_form) { return _form['Image_src'].value; }
    function getAlign(_form) { return _form['Image_align'].value; }

    function FillImagePane(imagePaneDiv, imageArray) {  // [dbid, name]
      if ((imagePaneDiv == null) || (imageArray == null)) return;
      for (i=0; i < imageArray.length; i=i+2) {
        var line = document.createElement('DIV');
        line.innerHTML = "<div style='cursor:pointer' onclick='ImageClick(this.parentNode);'>"+ imageArray[i+1] +"</div>";
        line.IMAGE_dbid = imageArray[i+0];  line.IMAGE_name = imageArray[i+1];
        imagePaneDiv.appendChild(line);
      }
    }

    // -----------------------  TREE ------------------------------------

    function FillTreePane(treePaneDiv, treeArray) {  // [+-level, dbid, name]
      if ((treePaneDiv == null) || (treeArray == null)) return;
      var lastInLevel = [];
      for (i=0; i < treeArray.length; i=i+3) {
        var level = treeArray[i+0];
        var levelAbs = (level < 0) ? -level : level;
        lastInLevel[levelAbs] = (level <= 0);
        var line = document.createElement('DIV'), _obj = line;  line.style.display = 'none';  //line.className = 'TLine';
        for (j=1; j <= levelAbs; j++) {
          var gap = document.createElement('DIV');  gap.className = 'TGap' + (((j == levelAbs) ? 3 : 1) + (lastInLevel[j] ? 1 : 0));
          _obj.appendChild(gap);  _obj = gap;
        }
        _obj.innerHTML = "<div class='TTxt' onclick='TreeClick(this);'>"+ treeArray[i+2] +"</div>";
        line.TP_level = levelAbs;  line.TP_dbid = treeArray[i+1];  line.TP_title = treeArray[i+2];
        treePaneDiv.appendChild(line);
      }
    }

    function TreeClick(_TTxt) {
      for (node = _TTxt.parentNode; node != null; node = node.parentNode) if (node.tagName == 'DIV') {
        if (node.TP_level != null) { TreeSelect(node); return; }
      }
      var TreePane = ParentTag(_TTxt, "DIV", "TreePane");
      TreeSelect(null, TreePane);
    }
    function TreeSelectById(dbid, treePaneDiv) {
      if (dbid != null) dbid = '' + dbid;
      if (treePaneDiv == null) treePaneDiv = document.getElementById('TreePane');
      for (node = treePaneDiv.firstChild; node != null; node = node.nextSibling) if (node.tagName == 'DIV') {
        if (node.TP_dbid == dbid) { TreeSelect(node); return; }
      }
      TreeSelect(null, treePaneDiv);
    }
    function TreeLineShow(node, bShow, bSel) {
      if (!bShow) { if (node.style.display != 'none') node.style.display = 'none'; return; }
      node.style.display = 'block';
      var level = node.TP_level;
      for (i=0; i <= level; i++) {
        node = node.firstChild;  while (node.tagName != 'DIV') node = node.nextSibling;
      }
      node.className = bSel ? 'TTxtSel' : 'TTxt';
    }
    function TreeSelect(_line, TreePane) {
      if (_line != null) TreePane = ParentTag(_line, "DIV", "TreePane");
      if (TreePane == null) TreePane = document.getElementById('TreePane');
      var rootLine = (_line == null) ? TreePane.firstChild : _line.parentNode.firstChild;
      while (rootLine.tagName != 'DIV') rootLine = rootLine.nextSibling;
      if (_line == null) _line = rootLine;
      var _depth = _line.TP_level;
      var _dbid = (rootLine == _line) ? null : _line.TP_dbid;
      var _path = (rootLine == _line) ? '/' : _line.TP_title;
      TreeLineShow(_line, true, true);
      // UP
      var depthref = _depth;
      for (node = _line.previousSibling; node != null; node = node.previousSibling) if (node.tagName == 'DIV') {
        var bSel = false;
        var depth = node.TP_level;
        if (depth < depthref) {
          depthref = depth;
          bSel = true;
          _path = ((rootLine == node) ? '/' : node.TP_title + '/') + _path;
        }
        if (depth == depthref) TreeLineShow(node, true, bSel); else if (depth > depthref) TreeLineShow(node, false, false);
      }
      // DOWN
      var depthref = _depth + 1;
      for (node = _line.nextSibling; node != null; node = node.nextSibling) if (node.tagName == 'DIV') {
        var depth = node.TP_level;
        if (depth < depthref) depthref = depth;
        if (depth == depthref) TreeLineShow(node, true, false); else if (depth > depthref) TreeLineShow(node, false, false);
      }
      // external ctrls
      var pathCtrlName = (TreePane._path != null) ? TreePane._path : "_path";
      var pathCtrl = document.getElementById(pathCtrlName);
      if (pathCtrl != null) pathCtrl.innerHTML = _path;
      var dbidCtrlName = (TreePane.LPLine_url != null) ? TreePane.LPLine_url : "LPLine_url";
      var dbidCtrl = document.getElementById(dbidCtrlName);
      if ((_dbid != null) && (dbidCtrl != null)) dbidCtrl.value = ''+_dbid; 
      if (TreePane.OnTreeClick != null) {
        TreePane.OnTreeClick(ParentTag(TreePane, "FORM"), _dbid);
      }
    }

    //----------- commons

    String.prototype.startsWith = function(str) {return (this.substr(0, str.length) == str); }

    function ParentTag(elm, tag, idStart) {
      do {
        if (elm && elm.tagName && elm.tagName.toUpperCase() == tag) {
          if (!idStart || (elm.id && elm.id.startsWith(idStart))) return elm;

        }
        elm = elm.parentNode;
      } while(elm);
      return false;
    }

    function setOptions(checkbox, cod, fieldName, forcedSet) {
     var value = parseInt(document.frm[fieldName].value,10);
     if (checkbox != null) { if (checkbox.checked) value = value | cod; else value = value & ~cod; }
     if (forcedSet != null) { if (forcedSet == 1) value = value | cod; else value = value & ~cod; }
     document.frm[fieldName].value = value;
    }

    function BtnOver(btn, overClasss) {
      btn.origClass = btn.className;
      btn.className = (overClasss == null) ? 'BtnOver' : overClasss;
    }
    function BtnOut(btn) {
      if (btn.origClass != null) {
        btn.className = btn.origClass; btn.origClass = null;
      }
    }

    function getRadioValue(radio,novalue) {
      for (i=0; (radio != null) && (radio.length != null) && (i < radio.length); i++) {
        if (radio[i].checked) return radio[i].value;
      }
      return novalue;
    }

    function SetListNode() {
      var _list = document.frm['ListNodeSelect'];
//alert(_list.value);
      setParameter('NewListNode',_list.value);
      setParameter('NewPageN','0');
      autoFrmSubmit('UPDATE', null);
    }

    var enc = [ '&','&#'+'38;', '\\','&#'+'92;', '<','&#'+'60;', '>','&#'+'62;', '"','&#'+'34;', "'",'&#'+'39;' ];
    function encodeHTML(s, nullReplace) {
      if (s == null) return nullReplace;
      for (e=0; e < enc.length; e+=2) {
        var i=-1, p=0;
        while((i = s.indexOf(enc[e],p)) != -1) {
          s = s.substr(0,i)+enc[e+1]+s.substr(i+1);
          p = i+4;
        }
      }
      return s;
    }

	function checkSubmit() {
		return false;
	}
	var SaveOnDocumentKeypress2 = document.onkeypress;
	document.onkeypress = function hidecal2 (event) {
		if (window.event) { event = window.event; }
		if (SaveOnDocumentKeypress2 != null){SaveOnDocumentKeypress2(event);}
		if ((event) && (event.keyCode==13)) {
			var DefBtn = getElement('DEFAULT_BTN');
			if ((DefBtn != null) && (DefBtn.href != null)) {
				var srcObj = null;
				if (event.target) srcObj = event.target; else if (event.srcElement) srcObj = event.srcElement;
				else if (event.srcElement && event.srcElement.tagName) srcTag = event.srcElement.tagName.toUpperCase();
				var srcTag = (srcObj && srcObj.tagName) ? srcObj.tagName.toUpperCase() : '';
				var srcType = (srcTag == 'INPUT') ? srcObj.type.toUpperCase() : '';
//alert(srcTag + ' - ' + srcType);
				if ((srcTag == 'TEXTAREA') || (srcTag == 'BUTTON') || (srcTag == 'A') || (srcType == 'FILE')) return;
			        var _href = ''+DefBtn.href;
				event.cancelBubble = true;
				if (event.stopPropagation) event.stopPropagation();
			        if (_href.startsWith('javascript:')) {
			                var cmd = DefBtn.href.substring(11);
			                eval( cmd );
					return false;
			        };
			        if (!_href.startsWith('javascript:')) {
			        	window.location = DefBtn.href;
					return false;
			        };
			};
			var none = 1;
		}
	}
