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 preloadedImg = {};
var checkSaveRestore = [];
var aOnclickCurrElement = null;

  function aOnclick() {
//    var list = this.getElementsByTagName("IMG");
//    if (list && (list.length == 1)) {
//      // if (list[0].onmouseover != null) drawOver(list[0], '-over', '-on'); else drawOver(list[0], '-off', '-on');
//    }
    aOnclickCurrElement = this;
    try {
      if (this.oldOnclick && ((this.oldOnclick() == false) || this.tagName == 'INPUT')) return false;
      if (this._javascript) eval( this._javascript );
    } finally { aOnclickCurrElement = null; }
    return false;
  }
  var _aOnclick = aOnclick;

  function injectAOnclick() {
    var list = document.getElementsByTagName('A');
    if (list) for (var i=0, listi = list[i]; i < list.length; i++, listi = list[i]) {
      if (!(listi.onclick == _aOnclick) && listi.href && listi.href.startsWith("javascript:") && !listi.href.startsWith("javascript:void")) {
        listi._javascript = listi.getAttribute('href').substring(11);
        listi.oldOnclick = listi.onclick;
        listi.onclick = _aOnclick;
        listi.href = "javascript:void(0)";
      }
    }
  }


  function preloadImg(srcImages) {
    _prImg("/i/1.gif");
    _prImg("/i/ani-busy.gif");
    _prImg("/i/ajax-loader.gif");
    for (var i=0; srcImages && (i < srcImages.length); i++) _prImg(srcImages[i]);
  }
  function _prImg(src) { if (src && !preloadedImg[src]) { var _i = new Image(); _i.src = src; preloadedImg[src] = _i; if (_i.src && (src != _i.src)) preloadedImg[_i.src] = _i; } }

  function setInitialFocus() {
    L1:for(var i = 0; i < document.frm.elements.length; i++ ) { var e = document.frm.elements[ i ];
      if( (e.type != 'button') && (e.type != 'hidden') && (e.type != 'submit') && !e.disabled && (e.getAttributeNode( 'nofirst' ) == null)  && (e.tabIndex != -1) ) {
        for (var _e = document.frm.elements[ i ]; _e != null; _e = _e.parentNode) {
          if ((_e.style != null) && ((_e.style.display == 'none') || (_e.style.visibility == 'hidden'))) continue L1;
        }
        document.frm.elements[ i ].focus();
        if( window.getSelection ) {
          var sel = window.getSelection();
          if( sel && sel.collapseToStart ) try { sel.collapseToStart() ; } catch (Err) {}
        }
        break;
      }
    }
  }

//---------------------- Ajax Pages Test ---------------------------
  function globalEval(code) {
    if ((code == null) || (code == '')) return;
    if (code.indexOf("-->") != -1) alert("Found not allowed JS comment: " + 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 applyHTMLResponse(_data) {
      try {
        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 = [''];
          var data = extractScripts( _data, _scripts);

          if (updateType == 'REDIRECT') {
            window.location.replace( data );
            return null;
          } else if (updateType == 'UPDATE_VARS_FRAME') {
            cleanupTinyMCE();
            extractContent(data, ['AjaxFrameContent', 'AjaxVars'], ['\tMAIN\t', '\tVARS\t'])
          } else if (updateType == 'UPDATE_CONTENT') {
            cleanupTinyMCE();
            extractContent(data, ['AjaxContent', 'AjaxVars'], ['\tCNTS\t', '\tVARS\t'])
          } else if (updateType == 'UPDATE_VARS_TABS_LEFT_CONTENT') {
            cleanupTinyMCE();
            extractContent(data, ['AjaxTop', 'AjaxTabs', 'AjaxLeft', 'AjaxContent', 'AjaxRight', 'AjaxVars'], ['\tTOPP\t', '\tTABS\t', '\tLEFT\t', '\tCNTS\t', '\tRGHT\t', '\tVARS\t'])
          }
          // global vars workaround
          isBuilt = false;  masters = {};  checkSaveRestore = [];
          globalEval( _scripts[0] );
          return null;
        } else {
          //alert('epmty: ' + _data);
          return 'Server error response ( wrong data: '+ _data +' )';
        }
      } catch(err) { return 'Server response processing failed ( ' + (err.message ? err.message : err.description ? err.description : err) + ' )'; };
  }

  function positionImageOverControl(_img, ctrl) {
        var _imgCache = _img.src ? preloadedImg[_img.src] : null;
        if (!_imgCache) _imgCache = _img;
        var imgWH = [_imgCache.width, _imgCache.height], ctrlWH = [ctrl.offsetWidth, ctrl.offsetHeight];
        var ctrlXY = [ctrl.offsetLeft, ctrl.offsetTop];
        var posfixed = false;
        for (var ctrlParent = ctrl.offsetParent; ctrlParent && (ctrlParent.tagName != "BODY"); ctrlParent = ctrlParent.offsetParent) {
          if (ctrlParent.style.position == 'fixed') {
            ctrlXY[0] += parseInt(ctrlParent.style.left);  ctrlXY[1] += parseInt(ctrlParent.style.top);
            posfixed = true;  break;
          } else {
            ctrlXY[0] += ctrlParent.offsetLeft;  ctrlXY[1] += ctrlParent.offsetTop;
          }
        }
//alert(ctrlWH[0] + ' ' + ctrlWH[1]);
//alert(imgWH[0] + ' ' + imgWH[1]);
//alert(_imgCache.src);
        _img.style.position = posfixed ? 'fixed' : 'absolute';
        _img.style.left = (ctrlXY[0] + (ctrlWH[0] ? ((ctrlWH[0] - imgWH[0]) / 2) : 0)) + 'px';
        _img.style.top = (ctrlXY[1] + (ctrlWH[1] ? ((ctrlWH[1] - imgWH[1]) / 2) : 0)) + 'px';
  }

  function ajaxCallback(status, _data, callId) {
//alert(status);
    var _img = getElement( callId + '_WaitImage' );
    if (_img != null) {
      var display = false;
      if (status == null) { // INIT
//        _img.src = '/i/1.gif';  _img.alt = 'calling...';  _img.onclick = null;  display = false;
        /*_img.src = '/i/ajax-loader.gif';*/  _img.alt = 'calling...';  _img.onclick = null;  display = true;
      } else if (status < 0) { // AFTER SHORT TIMEOUT OR PING
        /*_img.src = '/i/ajax-loader.gif';*/  _img.alt = 'click to cancel call...';  _img.onclick = ajaxCancel;  display = true;
      } else if (status >= 0) {  // COMPLETED OK OR FAILED
        /*_img.src = '/i/1.gif';*/  _img.alt = '';  _img.onclick = null;  display = false;
      }
      if (submittingCtrl && _img.getAttribute('autoposition') && display) {
        var ctrl = ((submittingCtrl.tagName == 'A') && submittingCtrl.firstChild && submittingCtrl.firstChild.tagName) ? submittingCtrl.firstChild : submittingCtrl;
        positionImageOverControl(_img, ctrl);
      }
      _img.style.display = display ? '' : 'none';
    }
    if (status == 1) { // COMPLETED OK
      submitting = false;  submittingCtrl = null;
      var err = applyHTMLResponse(_data);
      if (err != null) alert(err);
    } else if (status == 0) { // failed or timed out
      submitting = false;  submittingCtrl = null;
      if ((_data != null) && ('Silent Cancel' == _data)) ; else alert('Server error or time out (' + _data + ')');
    }
  };

  function cleanupTinyMCE() {
    document.frm.OnSubmitValidate = null;
    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 extractContent(data, elementNames, markers) {
    for (var i=0; i < elementNames.length; i++) {
      var start = data.indexOf(markers[i]) + markers[i].length, len = ((i+1) >= elementNames.length) ? null : (data.indexOf(markers[i+1]) - start);
      var _data = (len == null) ? data.substr( start ) : data.substr( start, len );
      getElement( elementNames[i] ).innerHTML = _data;
    }
  }

  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, "Manual Cancel");
  };

  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')) {
        // copy of functionality of 'check()' function - tempoorary
        var check2Skip = false;
        if ((ctrl.type == 'file')) check2Skip = true;
        if ((ctrl.type == 'select-one') && ((ctrl.selectedIndex < 0) || (ctrl.options[ctrl.selectedIndex].value == ""))) check2Skip = true;
        if ((ctrl.type == 'hidden') && (ctrl.name != '') && (getField(ctrl.name).length != null) && (getField(ctrl.name)[0] != null)) {
           var chk = getField(ctrl.name)[0];
           if ((chk.type == 'checkbox') && (chk.disabled || chk.checked)) check2Skip = true;
        }
        if (!check2Skip && (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 (ctrl.name == 'NewUser') alert('user = ' + 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 iframeCallbackPing(status, data, callId) {
      var progressCtrl = getElement('UploadingProgressControl');
      if (status == 1) { // COMPLETED OK
        if (progressCtrl != null) progressCtrl.innerHTML = '' + data;
      } else if (status == 0) {  // FAILED OR TIMEOUT
        if ((data != null) && ('Silent Cancel' == data)) ; iframeRequestCancel(iframeCallback, "Ping Timeout");
      }
  };


  function iframeCallback(status, data, callId) {
      var progressCtrl = getElement('UploadingProgressControl');
      var _img = getElement( callId + '_WaitImage' );
      if (_img != null) {
        var display = false;
        if (status == null) { // INIT
//          _img.src = '/i/1.gif';  _img.alt = 'calling...';  _img.onclick = null;  display = false;
          /*_img.src = '/i/ajax-loader.gif';*/  _img.alt = 'calling...';  _img.onclick = null;  display = true;
          if (progressCtrl != null) { progressCtrl.innerHTML = 'Uploading...'; progressCtrl.onclick = iframeCancel; }
        } else if (status < 0) { // AFTER SHORT TIMEOUT OR PING, status == -1
          /*_img.src = '/i/ajax-loader.gif';*/  _img.alt = 'click to cancel call...';  _img.onclick = iframeCancel;  display = true;
        } else if (status >= 0) {  // COMPLETED OK OR FAILED
          /*_img.src = '/i/1.gif';*/  _img.alt = '';  _img.onclick = null;  display = false;
          if (progressCtrl != null) { progressCtrl.innerHTML = ''; progressCtrl.onclick = null; }
        }
        if (submittingCtrl && _img.getAttribute('autoposition') && display) {
          var ctrl = ((submittingCtrl.tagName == 'A') && submittingCtrl.firstChild && submittingCtrl.firstChild.tagName) ? submittingCtrl.firstChild : submittingCtrl;
          positionImageOverControl(_img, ctrl);
        }
        _img.style.display = display ? '' : 'none';
      }
      if (status == null) { // INIT
        // none
      } else if (status < 0) { // AFTER SHORT TIMEOUT OR PING
        if (!asyncRequestIsRunning() && (iframeForm != null) && (uploadRequestIDIF != null)) {
          var target = iframeForm.action;
          if (target.indexOf('?') != -1) target = target.substr(0, target.indexOf('?'));
          target = target + "?" + "VT_UPLOADING=" + uploadRequestIDIF;
          asyncRequest(target, iframeCallbackPing, 0, 5000, true);
        }
      } else if (status == 1) { // COMPLETED OK
        submitting = false;  submittingCtrl = null;
        asyncRequestCancel(iframeCallbackPing, 'Silent Cancel');
        var err = applyHTMLResponse(data);
        if (err != null) alert(err);
      } else if (status == 0) {  // FAILED OR TIMEOUT
        submitting = false;  submittingCtrl = null;
        asyncRequestCancel(iframeCallbackPing, 'Silent Cancel');
        if ((data != null) && ('Silent Cancel' == data)) ; else alert('Server error or time out (' + data + ')');
      }
  };


  function iframeCancel() {
    iframeRequestCancel(iframeCallback, "Manual Cancel");
  };

  function iframeCall( callId, submitType, responseType, timeoutInSeconds, _form, _uploadRequestID ) {
    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) + "&" + "ISIFRAME=true" + "&";
    if (submitType != null) targetUrl += "SubmitType=" + encodeURIComponent(submitType) + "&";
    uploadRequestIDIF = null;
    if (_uploadRequestID != null) {
      targetUrl += "UploadRequestID=" + _uploadRequestID + "&";
      uploadRequestIDIF = _uploadRequestID;
    }
    iframeRequest( targetUrl, iframeCallback, 1000, timeoutInSeconds * 1000, callId, _form, 2000);
  }

//---------------------- Async Request ---------------------------
var asyncObj = null, iframeForm = null;

var postponeSubmit = false;
var resultCallback = null;  var resultCallbackParam = null;   var isPostData = false;
var fastTimeout = 0, cancelTimeout = 0, timerID = null;

var postponeSubmitIF = false, uploadRequestIDIF = null;
var resultCallbackIF = null;  var resultCallbackParamIF = null;   var isPostDataIF = false;
var fastTimeoutIF = 0, cancelTimeoutIF = 0, timerIDIF = null, pingTimerIDIF = null, pingTimeoutIF = 0;


function formSubmitIsRunning() { return submitting; }
function asyncRequestIsRunning() { return resultCallback != null; }
function iframeRequestIsRunning() { return resultCallbackIF != null; }

  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; }
  }


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, "Forced Cancel");
  postponeSubmit = !(_noWait == true);
  if (_resultCallback != null) try { _resultCallback(null, "Init", _resultCallbackParam); } catch (e) { }
  if (asyncObj == 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, reason) {
  if ((asyncObj == null) || ((_resultCallback != null) && ((resultCallback == null) || (_resultCallback != resultCallback)))) return;
  if (timerID != null) {
    clearTimeout(timerID);  timerID = null;
  }
  var _func = resultCallback, _funcParam = resultCallbackParam;
  resultCallback = resultCallbackParam = null;
  try { asyncObj.abort(); } catch (e) { }
  postponeSubmit = false;
  if (_resultCallback != null) try { _func(0, reason ? reason : "Unknown", _funcParam); } catch (e) { }
}

function asyncRequestTimer() {
  if (timerID != null) {
    clearTimeout(timerID);  timerID = null;
    if (fastTimeout == 0) cancelTimeout = 0; else fastTimeout = 0;
  }
  if (cancelTimeout != 0) {
    var _func = resultCallback, _funcParam = resultCallbackParam;
    try { _func(-1, null, _funcParam); } catch (e) { }
    if (resultCallback != null) timerID = setTimeout("asyncRequestTimer()", cancelTimeout);
  } else {
    if (resultCallback != null) asyncRequestCancel(resultCallback, "Timeout");
  }
}

function asyncRequestCallback() {
  if (asyncObj.readyState == 4) {
//alert(asyncObj.status);
    if (asyncObj.status == 200) {
      var _func = resultCallback, _funcParam = resultCallbackParam, text = asyncObj.responseText;
      resultCallback = resultCallbackParam = null;
      asyncRequestCancel(null);
      postponeSubmit = false;
      try { _func(1, text, _funcParam); } catch (e) { }
    } else {
      var _func = resultCallback, _funcParam = resultCallbackParam, text = "Status="+asyncObj.status; //asyncObj.responseText;
      resultCallback = resultCallbackParam = null;
      asyncRequestCancel(null);
      postponeSubmit = false;
      try { _func(0, text, _funcParam); } catch (e) { }
    }
  }
}

//---------------------- Iframe Request ---------------------------

function iframeRequest(targetURL, _resultCallback, _fastTimeout, _cancelTimeout, _resultCallbackParam, _form, _pingTimeoutIF) {
  if ((isPostDataIF == true) && (resultCallbackIF != null)) return; // need explicit cancel when POST in progress!
  isPostDataIF = 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(resultCallbackIF, "Forced Cancel");
  postponeSubmitIF = 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';
  resultCallbackIF = _resultCallback;  resultCallbackParamIF = _resultCallbackParam;  fastTimeoutIF = _fastTimeout;  cancelTimeoutIF = _cancelTimeout; pingTimeoutIF = _pingTimeoutIF;
  timerIDIF = setTimeout("iframeRequestTimer()", (fastTimeoutIF == 0) ? cancelTimeoutIF : fastTimeoutIF);
  if ((fastTimeoutIF == 0) && (pingTimeoutIF > 0)) pingTimerIDIF = setTimeout("iframeRequestTimer('ping')", pingTimeoutIF);
  iframeForm.submit();
}

function iframeRequestCancel(_resultCallback, reason) {
  if ((iframeForm == null) || ((_resultCallback != null) && ((resultCallbackIF == null) || (_resultCallback != resultCallbackIF)))) return;
  if (timerIDIF != null) {
    clearTimeout(timerIDIF);  timerIDIF = null;
  }
  if (pingTimerIDIF != null) {
    clearTimeout(pingTimerIDIF);  pingTimerIDIF = null;
  }
  // restore iframeForm !!!
  iframeForm = null;
  var _func = resultCallbackIF;   var _funcParam = resultCallbackParamIF;
  resultCallbackIF = resultCallbackParamIF = 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";
  postponeSubmitIF = false;
  if (_resultCallback != null) try { _func(0, reason ? reason : "Unknown", _funcParam); } catch (e) { }
}

function iframeRequestTimer(_ping) {
  if ((timerIDIF != null) && (pingTimerIDIF != null) && (_ping == 'ping')) {
    clearTimeout(pingTimerIDIF);  pingTimerIDIF = null;
    var _func = resultCallbackIF;   var _funcParam = resultCallbackParamIF;
    try { _func(-2, null, _funcParam); } catch (e) { }
    if (resultCallbackIF != null) pingTimerIDIF = setTimeout("iframeRequestTimer('ping')", pingTimeoutIF);
    return;
  }
  if (timerIDIF != null) {
    clearTimeout(timerIDIF);  timerIDIF = null;
    if (fastTimeoutIF == 0) cancelTimeoutIF = 0; else fastTimeoutIF = 0;
  }
  if (cancelTimeoutIF != 0) {
    var _func = resultCallbackIF;   var _funcParam = resultCallbackParamIF;
    try { _func(-1, null, _funcParam); } catch (e) { }
    if ((resultCallbackIF != null) && (pingTimeoutIF > 0)) pingTimerIDIF = setTimeout("iframeRequestTimer('ping')", pingTimeoutIF);
    if (resultCallbackIF != null) timerIDIF = setTimeout("iframeRequestTimer()", cancelTimeoutIF);
  } else {
    if (resultCallbackIF != null) iframeRequestCancel(resultCallbackIF, "Timeout");
  }
}

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 = resultCallbackIF, _funcParam = resultCallbackParamIF;
    resultCallbackIF = resultCallbackParamIF = null;
    iframeRequestCancel(null);
    postponeSubmitIF = false;
    var status = 0;
    if (text != null) {
      var i1 = text.indexOf("IFRAME_ESCAPE<!--"), i2 = text.lastIndexOf("-->IFRAME_ESCAPE");
      if ((i1 != -1) && (i2 != -1) && (i2 > i1)) {
        text = text.substr(i1 + "IFRAME_ESCAPE<!--".length, i2 - i1 - "IFRAME_ESCAPE<!--".length);
        status = 1;
      }
    }
    try { _func( status, (status == 1) ? text : "Error", _funcParam); } catch (e) { }
}

//---------------------- 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 / Poststed and Land from postnummer -----------------
var lastTargetField1 = null, lastTargetField2 = null;
var lastTargetImage = null;
function getPoststed(targetURL, targetField, targetImage) {
  getPoststedL(targetURL, targetField, null, targetImage);
}
function getPoststedL(targetURL, targetField1, targetField2, targetImage) {
  lastTargetField1 = targetField1;
  lastTargetField2 = targetField2;
  lastTargetImage = targetImage;
  getField(targetField1).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) {
    getField(lastTargetField1).value = data;
    if( lastTargetField2 != null && data != null && data != '' )
        getField(lastTargetField2).value = 'Norge';
  }
}
//---------------------------------------------------------

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 RowSel(row,color) {
   var table = ParentTag(row, 'TABLE');
   RowUnsel(table);
   row.oldbgcolor = row.style.backgroundColor;
   if (color == null) color = getElementStyle(getElement("DataTableTRover"), "backgroundColor", "background-color");
   if (color == null) color = '#D0E2ED';
   row.style.backgroundColor = color;
   table.selrow = row;
 }
 function RowUnsel(rowOrTable) {
   var table = (rowOrTable && rowOrTable.tagName && (rowOrTable.tagName.toUpperCase()=='TABLE')) ? rowOrTable : ParentTag(rowOrTable, 'TABLE');
   if (table.selrow != null) {
     table.selrow.style.backgroundColor = table.selrow.oldbgcolor;
     table.selrow = null;
   }
 }
 function SetRowBGColor(row, color) {
   var table = ParentTag(row, 'TABLE');
   if ((table.selrow != null) && (table.selrow == row)) row.oldbgcolor = color; else row.style.backgroundColor = color;
 }
 function RowClick(row, optionalCell) {
   var a = optionalCell ? ChildTagAnyDepth( optionalCell , 'A') : null;
   if (!a && !optionalCell) a = ChildTagAnyDepth(row, 'A', null, 'defaultOnRowClick', 'true');
   if (!a && !optionalCell) a = ChildTagAnyDepth( ChildTag(row, 'TD') , 'A');
   if (a && a.href && !a.href.startsWith("javascript:void")) {
     if (a.href.startsWith("javascript:")) {
       eval(a.href.substr("javascript:".length));
     } else if (a.href != "") {
       window.location.assign(a.href);
     }
   } else if (a && a.onclick) {
     a.onclick();
   }
   return false;
 }
//---------------------------------------------------------

function getField(name, asArray) {
  var a = ((name == null) || (name == '') || (name == 'null')) ? null : document.frm[ name ];
  if (a == null) return asArray ? [] : null;
  var aIsField = (a.length == null) || (a.type == 'select-one');
  if (asArray) {
    return aIsField ? [ a ] : a;
  } else {
    return aIsField ? a : ( (a.length == 0) ? null : ( (a.length == 1) ? a[0] : a ) );
  }
}
function getFields(name) {
  return getField(name, true);
}
function getFirstField(name) {
  var a = getField(name, true);  return (a.length == 0) ? null : a[0];
}

function getElement(objname, asArray) {
  if (DOM) {
    var el = document.getElementById(objname), elia = null;
    if (el == null) return asArray ? [] : null;
    for (var eli = null, i = 1; (eli = document.getElementById(objname + "__i" + i)) != null; i++) {
      if (elia == null) elia = [ el ];
      elia[i] = eli;
    }
    return (elia == null) ? (asArray ? [ el ] : el) : elia;
  } else if (NN) {
    return getNNElement(null, objname);
  }
//  else if (IE) {
//    return document.all[objname];
//  }
}
function getElements(objname) {
  return getElement(objname, true);
}
function getFirstElement(objname) {
  if (DOM) return document.getElementById(objname);
  else if (NN) return (getNNElement(null, objname)[0] == null) ? getNNElement(null, objname) : getNNElement(null, objname)[0];
//  else if (IE) return (document.all[objname][0] == null) ? document.all[objname] : document.all[objname][0];
}

function dummy() { return; }
function dummyStr(){ return ''; }

function isGET() { return (__isGET != null) ? __isGET : false; }
function setGET(value) { if (__isGET != null) __isGET = value; }

function setParameter(name, value) {
  var created = false;
  if (getField(name) == null) {
    if (value == null) return; else if (document.getElementById('AjaxVars')) {
      var div = document.createElement("DIV");
      document.getElementById('AjaxVars').appendChild(div);
      div.innerHTML = "<input type='hidden' name='" + name + "'" + " value='" + value + "'>";
      created = true;
    }
  }
  checkSave(getField(name), created);
  getField(name).disabled = (value == null);
  getField(name).value = (value == null) ? "" : value;
}

function setAutoParameter(name, value) {
  if ("GET" == name) {
    checkSave("GET");
    setGET( ((value == "true") || (value == true)) ? true : false );
  } else {
    var _isGET = (isGET != null) ? isGET() : false;
    var _name = (_isGET ? "Current" : "New") + name;
    if (getField(_name) || (getField(name) == null)) setParameter(_name, value); else setParameter(name, 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, submittingCtrl = null, delayedSubmitTimer = null, delayedSubmitType, delayedNewState, delayedNewRowID, delayedHelpID, delayedMode,  delayedCtrl;

function frmSubmit(submitType, newState, newRowID, helpID, delayed, ctrl ){
//alert(document.frm.name);
	if(submitType == "DUMMY") return false;
        if (submitting) return;
	if ((document.frm.OnSubmitValidate != null) && (document.frm.OnSubmitValidate( submitType ) != null)) return;
        submitting = true;
        if (postponeSubmit || postponeSubmitIF) {
          delayedSubmitType = submitType; delayedNewState = newState; delayedNewRowID = newRowID; delayedHelpID = helpID; delayedMode = "POST";
          delayedSubmitTimer = setTimeout("delayedFrmSubmit()", 500); delayedCtrl = ctrl ? ctrl : aOnclickCurrElement;
          return;
        }
        submittingCtrl = (delayed == null) ? (ctrl ? ctrl : aOnclickCurrElement) : ctrl;
        var _isGET = isGET();
	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.method = _isGET ? "get" : "post";
        if (_isGET && (newState != null)) { document.frm.CurrentState.disabled = false; document.frm.CurrentState.value = newState; }
        if (_isGET && (newRowID != null)) { document.frm.CurrentRowID.disabled = false; document.frm.CurrentRowID.value = newRowID; }
        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, helpID, delayed, ctrl ){
//alert(document.frm.name);
    if (submitType == "DUMMY") return false;
    if (submitting) return;
    if ((document.frm.OnSubmitValidate != null) && (document.frm.OnSubmitValidate( submitType ) != null)) return;
    submitting = true;
    if (postponeSubmit || postponeSubmitIF) {
       delayedSubmitType = submitType; delayedNewState = newState; delayedNewRowID = newRowID; delayedHelpID = helpID; delayedMode = "POST";
       delayedSubmitTimer = setTimeout("delayedFrmSubmit()", 500); delayedCtrl = ctrl ? ctrl : aOnclickCurrElement;
       return;
    }
    submittingCtrl = (delayed == null) ? (ctrl ? ctrl : aOnclickCurrElement) : ctrl;
    checkSave(document.frm.SubmitType); checkSave(document.frm.NewState); checkSave(document.frm.NewRowID); 
    checkSave(document.frm.CurrentState); checkSave(document.frm.CurrentRowID); checkSave(document.frm.LangBox); 
    checkSave(document.frm.LoginName); checkSave(document.frm.LoginPassword); 
    try {
	if (document.frm.OnSubmit1 != null) document.frm.OnSubmit1();
	if (document.frm.OnSubmit2 != null) document.frm.OnSubmit2();
        var _isGET = isGET();
	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();
        if (_isGET && (newState != null)) { document.frm.CurrentState.disabled = false; document.frm.CurrentState.value = newState; }
        if (_isGET && (newRowID != null)) { document.frm.CurrentRowID.disabled = false; document.frm.CurrentRowID.value = newRowID; }
        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);

// =========================== tmp test solution ==================
        var ajaxAction = 'UPDATE_VARS_TABS_LEFT_CONTENT';
        if (getElement('ErrorFrameContentMark') != null) ajaxAction = 'UPDATE_VARS_FRAME';
        if (getElement('StartFrameContentMark') != null) ajaxAction = 'UPDATE_VARS_FRAME';
        if (newState == "Welcome") ajaxAction = 'UPDATE_VARS_FRAME';

        var useIFrame = false;
        for (var i=0; i < document.frm.length; i++) {
          var ctrl = document.frm[i];
          if ((ctrl.tagName == 'INPUT') && !ctrl.disabled && (ctrl.type == 'file') && (ctrl.value != null) && (ctrl.value != '')) {
            //alert(ctrl.value);
            useIFrame = true;
            break;
          }
        }
// =========================== tmp test solution ==================
        if (useIFrame) {
          var uploadRequestID = (getField("UploadRequestID") != null) ? getField("UploadRequestID").value : null;
          check();
          iframeCall( 'FRMSUBMIT', submitType, ajaxAction, 600, null, uploadRequestID );
        } else {
          //check(); // no need in Ajax
          ajaxCall( 'FRMSUBMIT', null/*submitType*/, ajaxAction, 60 );
        }
        checkRestore();
   } catch (err) {
      submitting = false; // true;  ???
      checkRestore();
      throw err;
   }
}
function autoFrmSubmit(submitType, newState, newRowID) {
  var useNonAjaxSubmit = asyncObj == null; // just set to constant 'true' if need to always use Non Ajax Submit
  if (useNonAjaxSubmit) frmSubmit(submitType, newState, newRowID); else ajaxFrmSubmit(submitType, newState, newRowID);
}

function delayedFrmSubmit() {
  if (delayedSubmitTimer != null) {
    clearTimeout(delayedSubmitTimer);  delayedSubmitTimer = null;
  }
  if (!submitting) return;
  if (postponeSubmit || postponeSubmitIF) {
    delayedSubmitTimer = setTimeout("delayedFrmSubmit()", 500);
    return;
  }
  submitting = false;  submittingCtrl = null;
  if (delayedMode == "POST") frmSubmit(delayedSubmitType, delayedNewState, delayedNewRowID, delayedHelpID, true,  delayedCtrl);
  else ajaxFrmSubmit(delayedSubmitType, delayedNewState, delayedNewRowID, null, true,  delayedCtrl);
}

function drawOver(oImg, sOld, sNew){
        if (!oImg) return;
        if (oImg.tagName.toUpperCase() == 'IMG') { // IMG
	  var sSrc = oImg.src;
	  sSrc = sSrc.replace(sOld,sNew);
	  oImg.src = sSrc;
	} else { // DIV or others
	  var sClass = oImg.className;
	  sClass = sClass.replace(sOld,sNew);
	  oImg.className = sClass;
	}
}

function isReadOnlyField(sName) { return sName && (val_disabled[sName] != null); }
function foundInMasters(oObj) { return oObj && oObj.name && (masters[oObj.name] != null); }

function updateVisibility(oName, bEnabled) {
  for (var els = getElements("IDDISP_"+oName), m = 0; m < els.length; m++) els[m].style.display = bEnabled ? '' : 'none';
}

function _switchField(el, bEnable) {
  if (isReadOnlyField(el.name)) return;
  el.disabled = !bEnable;
  if ((el.type != "radio") && (el.type != "checkbox")) el.style.backgroundColor = bEnable ? '' : '#F0F0F0';
}

function enableDisableFrmElement(oName, bEnable){
	     var elfrm = getField(oName);
	     if (elfrm == null) return;
	     if (((elfrm.type == null) || (elfrm.type!='select-one')) && elfrm.length); else elfrm = [elfrm];
	     var radiofix = (elfrm[0].type == 'radio'), checkfix = (elfrm[0].type == 'checkbox');
             for (var ie=0; ie < elfrm.length; ie++) {
//	       if (elfrm[ie].name==oName){
                 _switchField(elfrm[ie], bEnable);
                 if (bEnable) {
                   if (checkfix && (ie > 0)) continue; // only first checkbox
                   if (radiofix && !elfrm[ie].checked) continue; else radiofix = false; // stateoff radio if none chosen
	           state(elfrm[ie]);
	         }
//	       }
	     }
	     if (!bEnable || radiofix) stateOff(elfrm[0]);
}

function _switchLabel(el, bEnable, forButton) {
  if (!forButton) el.style.color = bEnable ? "" : (el.color_off == null) ? "darkgray" : el.color_off;
  if (el.href) el.disabled = !bEnable;
  if (el.href && bEnable && el.href_keep) { el.href = el.href_keep;  el.href_keep = null; el.onclick = el.onclick_keep;  el.onclick_keep = null; }
  if (el.href && !bEnable && !el.href_keep) { el.href_keep = el.href;  el.href = "javascript:void(0)";  el.onclick_keep = el.onclick;  el.onclick = null; }
}

function _switchButton(el, bEnable) {
  _switchLabel(el, bEnable, true); // not correct - can't distinguish between button and label
}

function enableDisableLeadText(oName, bEnable) {
  for (var els = getElements("ID_"+oName), m = 0; m < els.length; m++) {
    if (els[m].tagName == 'INPUT' || els[m].tagName == 'SELECT' || els[m].tagName == 'TEXTAREA') {
      _switchField(els[m], bEnable);
    } else {
      _switchLabel(els[m], bEnable);
    }
  }
  for (var el = null, m = 0; m < aIUD.length; m++) if (el = getElement("ID_" + oName + aIUD[m])) _switchButton(el, bEnable);
}

function stateSettingHelper(oName, bEnable) {
  enableDisableLeadText(oName, bEnable);
  updateVisibility(oName, bEnable);
  enableDisableFrmElement(oName, bEnable);
  var elfrm = getField(oName);
  if (elfrm && elfrm.syncStateEnableDisable) elfrm.syncStateEnableDisable(bEnable);
}

function state(oObj) {
	var len, oVal;
	if (!isBuilt || !foundInMasters(oObj)) return;
	if (oObj && oObj.syncStateBefore) oObj.syncStateBefore();
	if (oObj && oObj.syncState) oObj.syncState();
	else {
	  switch (oObj.type) {
	    case "checkbox":   oVal = oObj.checked ? 'true' : 'false';  break;
	    case "radio":      oVal = oObj.value;  if (!oObj.checked) return;  break;
	    case "select-one": oVal = oObj.options[oObj.selectedIndex].value;  break;
	    case "hidden":     oVal = oObj.value;  break;
	  }
	  if (oVal == null) oVal = "";
	  var val_idx = val_deps["val_"+(oObj.name).replace(" ","")+"_idx"];
	  var j = val_idx[oVal];
	  if (j != null) {
            var val_offon = [ val_deps["val_"+(oObj.name).replace(" ","")+"_off"], val_deps["val_"+(oObj.name).replace(" ","")+"_on"] ];
            for (var offon=0; offon < 2; offon++) if (val_offon[offon][j][0] == oVal) {
	      for (var i=1; i < val_offon[offon][j].length; i++) {
                if (val_offon[offon][j][i]) stateSettingHelper(val_offon[offon][j][i], offon == 1);
              }
	    }
	  }
	}
        if (oObj && oObj.syncStateAfter) oObj.syncStateAfter();
}

function stateOff(oObj){
	if (!isBuilt || !foundInMasters(oObj)) return;
	if (oObj && oObj.syncStateBefore) oObj.syncStateBefore();
	if (oObj && oObj.syncStateOff) oObj.syncStateOff();
	else {
          var val_offon = [ val_deps["val_"+(oObj.name).replace(" ","")+"_off"], val_deps["val_"+(oObj.name).replace(" ","")+"_on"] ];
          for (var j=0, offon=0; offon < 2; offon++) {
	    for (var i=1; i < val_offon[offon][j].length; i++) {
              if (val_offon[offon][j][i]) stateSettingHelper(val_offon[offon][j][i], false);
            }
	  }
        }
        if (oObj && oObj.syncStateAfter) oObj.syncStateAfter();
}

function init(masterNames, rootNames) {
        masters = {};
	isBuilt = true;
	if (masterNames) for (var i=0; i < masterNames.length; i++) if (getField(masterNames[i])) masters[masterNames[i]] = "x";
	for (var oName in masters) {
	   var el = getField(oName);  //if (el == null) alert(oName);
	   if ((rootNames != null) && (rootNames[oName] == null)) continue;
           if ((el.type == 'hidden') || (el.type == 'select-one')) {
	      stateOff(el);
	      if (!el.disabled) state(el);
	   } else if (el.length && (el.length > 1)) {
	      if (el[0].type == 'checkbox') {
                stateOff(el[0]);
	        if (!el[0].disabled) state(el[0]);
	      } else { // radio
                stateOff(el[0]);
		for (var i=0; i < el.length; i++) {
		   var eli = el[i];
		   if (eli.checked && !eli.disabled) { state(eli); break; }
		}
	      }
	   }
	}
}


function checkSave(ctrl, created) {
  if (ctrl) if (ctrl == "GET") checkSaveRestore[checkSaveRestore.length] = ["GET", null, null, isGET(), null];
  else checkSaveRestore[checkSaveRestore.length] = [ctrl, ctrl.name, ctrl.disabled, ctrl.value, created];
}
function checkRestore() {
  for (var i = checkSaveRestore.length - 1; i >= 0; i--) {
    var data = checkSaveRestore[i];
    if (data[0] == "GET") setGET(data[3]);
    else if (data[4]) { var div = data[0].parentNode; div.innerHTML = ''; div.parentNode.removeChild(div); } // all are created within own DIV !
    else { var ctrl = data[0];  ctrl.name = data[1];  ctrl.disabled = data[2];  ctrl.value = data[3]; }
  }
  checkSaveRestore = [];
}

function check() {
  for (var i=0; i < document.frm.elements.length; i++) {
    var el = document.frm.elements[i];
    if ((el.type=='checkbox') && (el.name != '') && (getFields(el.name)[1] != null)) {
      checkSave(getFields(el.name)[1]);
      getFields(el.name)[1].disabled = el.checked;
      if (el.disabled) getFields(el.name)[1].disabled = true;
    } else if (el.type=='select-one') {
      if (el.disabled || (el.selectedIndex < 0) || (el.options[el.selectedIndex].value == "")) {
        checkSave(el);
        el.name = "";
      }
    } else if (el.disabled) {
      checkSave(el);
      el.name = "";
    }
  }
  return true;
}

function clear_list(obj){
//   obj.length=1;
//   obj.options[0].value="";
//   obj.options[0].text="";
   if ((obj == null) || (obj.type != 'select-one')) return;
   while(obj.firstChild) {
      obj.removeChild(obj.firstChild);
   }
   var oOption = document.createElement("OPTION");
   oOption.value = "";
   oOption.text = "";
   // EBS: oOption.innerHTML = "";
   oOption.innerHTML = oOption.text;
   obj.appendChild(oOption);
   obj.selectedIndex=0;
   obj.length = 1;
   state(obj);
}

function fill_list(obj, val1, txt1, val){
   var n = 1;    
   if ((obj == null) || (obj.type != 'select-one')) return;
   if(val1 == undefined || txt1 == undefined) return;
   for(var i=0; i < val1.length; i++)
   {
       if( val1[ i ] == '' ) 
	   continue;
      var oOption = document.createElement("OPTION");
      oOption.value = val1[i];
      oOption.text = txt1[i];
      //EBS: oOption.innerHTML = txt1[i];
      oOption.innerHTML = oOption.text;
//      obj.options.add(oOption);
      obj.appendChild(oOption);

      if(oOption.value == val) {
        obj.selectedIndex = n;
      }
      n++;
   }
   obj.length = n;
}

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);
}

function isIntNumberKey( evt )
{
    var charCode = ( evt.which ) ? evt.which : event.keyCode;

    if( charCode == 8 || charCode == 9 )
        return true;

    if( charCode < 0x30 || charCode > 0x39  )
        return false;

    return true;
}

function get_radio_value( rad_nm )
{
    for( var i = 0; i < getField( rad_nm ).length; i++ )
    {
        if( getField( rad_nm )[ i ].checked )
        {
            var rad_val = getField( rad_nm )[i].value;
        }
   }
   return rad_val
}

function chBlockVis( blocNm )
{
    chVis( document.getElementById( blocNm + '0' ) );
    chVis( document.getElementById( blocNm + '1' ) );
    elem = document.getElementById( blocNm + 'R' );
    if( elem != null )
    {
        if( elem.innerHTML == '-' )
            elem.innerHTML = '+';
        else
            elem.innerHTML = '-';
    }
}

function chVis( elem )
{
    if( elem != null )
    {
        if( elem.style.display == "none" )
            elem.style.display = "";
        else
            elem.style.display = "none";
    }
}

/******************** 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]];
}

//var divBgColor = getElementStyle("myDiv", "backgroundColor", "background-color");
function getElementStyle(elem, IEStyleProp, CSSStyleProp) {
    if (!elem) return null;
    if (elem.currentStyle) {
        return elem.currentStyle[IEStyleProp];
    } else if (window.getComputedStyle) {
        var compStyle = document.defaultView.getComputedStyle(elem, ""/*pseudo*/);
//        var divpadding = compStyle.padding; ??? is allowed?
//        var compStyle = window.getComputedStyle(elem, ""/*pseudo*/);  ?? Safari problems
        return compStyle.getPropertyValue(CSSStyleProp);
    }
    return null;
}

/**************************************** 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)));
};

    //----------- commons

    String.prototype.startsWith = function(str) {return (this.substr(0, str.length) == str); }
    String.prototype.endsWith = function(str) {return ((this.length >= str.length) && (this.substr(this.length - str.length, str.length) == str)); }
    function jsEscape(str) { return escape(str).replace(/\+/g,"%2B"); }

    function ParentTagOLD(elm, tag) {
      for (; elm; elm = elm.parentNode) if (elm.tagName && (elm.tagName.toUpperCase() == tag)) return elm;
      return null;
    }
    function ParentTag(elm, tag, idStart) {
      if (elm) for (elm = elm.parentNode; elm; elm = elm.parentNode) if (elm.tagName && (elm.tagName.toUpperCase() == tag)) {
        if (!idStart || (elm.id && elm.id.startsWith(idStart))) return elm;
      }
      return null;
    }
    function ChildTag(elm, tag, idStart) {
      if (elm) for (elm = elm.firstChild; elm; elm = elm.nextSibling) if (elm.tagName && (elm.tagName.toUpperCase() == tag)) {
        if (!idStart || (elm.id && elm.id.startsWith(idStart))) return elm;
      }
      return null;
    }
    function ChildTagAnyDepth(elm, tag, idStart, testAttrName, testAttrVal) {
      var list = elm ? elm.getElementsByTagName(tag) : null;
      if (list) for (var i=0, listi=list[i]; i < list.length; i++, listi=list[i]) if (!idStart || (listi.id && listi.id.startsWith(idStart))) {
        if (!testAttrName) return listi;
        var attrVal = listi[testAttrName] ? listi[testAttrName] : listi.getAttribute(testAttrName);
        if (attrVal == testAttrVal) return listi;
      }
      return null;
    }


/**************************************** CALENDAR 28.02.05 ****************/
	function takeYear(theDate)
	{
	        if (theDate.getFullYear) return theDate.getFullYear();
		x = theDate.getYear();
		var y = x % 100;
		y += (y < 38) ? 2000 : 1900;
		return y;
	}


//	written	by Tan Ling	Wee	on 2 Dec 2001
//	last updated 20 Jun 2003
//	email :	fuushikaden@yahoo.com

	var	fixedX = -1; // x position (-1 if to appear below control)
	var	fixedY = -1; // y position (-1 if to appear below control)
	var startAt = 1; // 0 - sunday ; 1 - monday
	var showWeekNumber = 1;	// 0 - don't show; 1 - show
	var showToday = 0;		// 0 - don't show; 1 - show
	var imgDir = "i/";	// directory for images ... e.g. var imgDir="/img/"

//T	var gotoString = "Go To Current Month";
//T	var todayString = "Today is";
//T	var weekString = "Wk";
//T	var scrollLeftMessage = "Click to scroll to previous month. Hold mouse button to scroll automatically.";
//T	var scrollRightMessage = "Click to scroll to next month. Hold mouse button to scroll automatically.";
//T	var selectMonthMessage = "Click to select a month.";
//T	var selectYearMessage = "Click to select a year.";
//T	var selectDateMessage = "Select [date] as date."; // do not replace [date], it will be replaced by date.

	var	crossobj, crossMonthObj, crossYearObj, monthSelected, yearSelected, dateSelected, omonthSelected, oyearSelected, odateSelected, monthConstructed, yearConstructed, intervalID1, intervalID2, timeoutID1, timeoutID2, ctlToPlaceValue, ctlNow, dateFormat, nStartingYear;

	var	bCalendarInited=false;
	var	_ie_=document.all;
	var	_dom_=document.getElementById;

	var	ns4=document.layers;
	var	today =	new	Date();
	var	dateNow	 = today.getDate();
	var	monthNow = today.getMonth();
	var	yearNow	 = takeYear(today);
	var	imgsrc = new Array("cal_drop1.gif","cal_drop2.gif","cal_left1.gif","cal_left2.gif","cal_right1.gif","cal_right2.gif");
	var	img	= new Array();
	var	bImgLoaded  =  false;

	var bShow = false;

    /* hides <select> and <applet> objects (for IE only) */
    function hideElement( elmID, overDiv )
    {
      if( _ie_ )
      {
        for( i = 0; i < document.all.tags( elmID ).length; i++ )
        {
          obj = document.all.tags( elmID )[i];
          if( !obj || !obj.offsetParent )
          {
            continue;
          }

          // Find the element's offsetTop and offsetLeft relative to the BODY tag.
          objLeft   = obj.offsetLeft;
          objTop    = obj.offsetTop;
          objParent = obj.offsetParent;

          while( objParent.tagName.toUpperCase() != "BODY" )
          {
            objLeft  += objParent.offsetLeft;
            objTop   += objParent.offsetTop;
            objParent = objParent.offsetParent;
          }

          objHeight = obj.offsetHeight;
          objWidth = obj.offsetWidth;

          if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
          else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
          else if( overDiv.offsetTop >= ( objTop + objHeight ));
          else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
          else
          {
            obj.style.visibility = "hidden";
          }
        }
      }
    }

    /*
    * unhides <select> and <applet> objects (for IE only)
    */
    function showElement( elmID )
    {
      if( _ie_ )
      {
        for( i = 0; i < document.all.tags( elmID ).length; i++ )
        {
          obj = document.all.tags( elmID )[i];

          if( !obj || !obj.offsetParent )
          {
            continue;
          }

          obj.style.visibility = "";
        }
      }
    }

	function HolidayRec (d, m, y, desc)
	{
		this.d = d;
		this.m = m;
		this.y = y;
		this.desc = desc;
	}

	var HolidaysCounter = 0;
	var Holidays = new Array();

	function addHoliday (d, m, y, desc)
	{
		Holidays[HolidaysCounter++] = new HolidayRec ( d, m, y, desc );
	}


	function loadImages() {
		if (bImgLoaded) return;
		for	(i=0;i<imgsrc.length;i++) {
			img[i] = new Image;
			img[i].src= imgDir + imgsrc[i];
		}
		bImgLoaded =  true; 
        }
        var bLoadImagesPresent = true;

	if (_dom_)
	{
//	        loadImages();
		document.write ("<div onclick='bShow=true' id='calendar'	class='div-style'><table width="+((showWeekNumber==1)?250:220)+" class='table-style'><tr class='title-background-style' ><td><table width='"+((showWeekNumber==1)?248:218)+"'><tr><td class='title-style'><B><span id='caption'></span></B></td><td align=right><a href='javascript:hideCalendar()'><IMG SRC='"+imgDir+"cal_close.gif' WIDTH='15' HEIGHT='13' BORDER='0' ALT='Close the Calendar'></a></td></tr></table></td></tr><tr><td class='body-style'><span id='content'></span></td></tr>");

		if (showToday==1)
		{
			document.write ("<tr class='today-style'><td><span id='lblToday'></span></td></tr>");
		}

		document.write ("</table></div><div id='selectMonth' class='div-style'></div><div id='selectYear' class='div-style'></div>");
	}

//T	var	monthName =	new	Array("January","February","March","April","May","June","July","August","September","October","November","December");
//T	var	monthName2 = new Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");

//	if (startAt==0)
//	{
//T		dayName = new Array	("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
//	}
//	else
//	{
//T		dayName = new Array	("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
//	}

	function swapImage(srcImg, destImg){
		if (_ie_)	{ document.getElementById(srcImg).setAttribute("src",imgDir + destImg); }
	}

	function init_cal()	{
	        if (bCalendarInited) return;
	        if ((monthName == null) || (monthName2 == null) || (dayName == null) || (todayString == null)) return;
                if (!bImgLoaded) loadImages();
		if (!ns4)
		{
//			if (!_ie_) { yearNow += 1900;	}

			crossobj=(_dom_)?document.getElementById("calendar").style : _ie_? document.all.calendar : document.calendar;
			hideCalendar();

			crossMonthObj=(_dom_)?document.getElementById("selectMonth").style : _ie_? document.all.selectMonth	: document.selectMonth;

			crossYearObj=(_dom_)?document.getElementById("selectYear").style : _ie_? document.all.selectYear : document.selectYear;

			monthConstructed=false;
			yearConstructed=false;

			if (showToday==1)
			{
				document.getElementById("lblToday").innerHTML =	todayString + " <a class='today-style' onmousemove='window.status=\""+gotoString+"\"' onmouseout='window.status=\"\"' title='"+gotoString+"' href='javascript:monthSelected=monthNow;yearSelected=yearNow;constructCalendar();'>"+dayName[(today.getDay()-startAt==-1)?6:(today.getDay()-startAt)]+", " + dateNow + " " + monthName[monthNow].substring(0,3)	+ "	" +	yearNow	+ "</a>";
			}

			sHTML1= "<span id='spanLeft'  class='title-control-normal-style' onmouseover='swapImage(\"changeLeft\",\"cal_left2.gif\");this.className=\"title-control-select-style\";window.status=\""+scrollLeftMessage+"\"' onclick='javascript:decMonth()' onmouseout='clearInterval(intervalID1);swapImage(\"changeLeft\",\"cal_left1.gif\");this.className=\"title-control-normal-style\";window.status=\"\"' onmousedown='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"StartDecMonth()\",500)'	onmouseup='clearTimeout(timeoutID1);clearInterval(intervalID1)'>&nbsp<IMG id='changeLeft' SRC='"+imgDir+"cal_left1.gif' width=10 height=11 BORDER=0>&nbsp</span>&nbsp;";
			sHTML1+="<span id='spanRight' class='title-control-normal-style' onmouseover='swapImage(\"changeRight\",\"cal_right2.gif\");this.className=\"title-control-select-style\";window.status=\""+scrollRightMessage+"\"' onmouseout='clearInterval(intervalID1);swapImage(\"changeRight\",\"cal_right1.gif\");this.className=\"title-control-normal-style\";window.status=\"\"' onclick='incMonth()' onmousedown='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"StartIncMonth()\",500)'	onmouseup='clearTimeout(timeoutID1);clearInterval(intervalID1)'>&nbsp<IMG id='changeRight' SRC='"+imgDir+"cal_right1.gif'	width=10 height=11 BORDER=0>&nbsp</span>&nbsp";
			sHTML1+="<span id='spanMonth' class='title-control-normal-style' onmouseover='swapImage(\"changeMonth\",\"cal_drop2.gif\");this.className=\"title-control-select-style\";window.status=\""+selectMonthMessage+"\"' onmouseout='swapImage(\"changeMonth\",\"cal_drop1.gif\");this.className=\"title-control-normal-style\";window.status=\"\"' onclick='popUpMonth()'></span>&nbsp;";
			sHTML1+="<span id='spanYear'  class='title-control-normal-style' onmouseover='swapImage(\"changeYear\",\"cal_drop2.gif\");this.className=\"title-control-select-style\";window.status=\""+selectYearMessage+"\"'	onmouseout='swapImage(\"changeYear\",\"cal_drop1.gif\");this.className=\"title-control-normal-style\";window.status=\"\"'	onclick='popUpYear()'></span>&nbsp;";

			document.getElementById("caption").innerHTML  =	sHTML1;

			bCalendarInited=true;
		}
	}

	function hideCalendar()	{
		crossobj.visibility="hidden";
		if (crossMonthObj != null){crossMonthObj.visibility="hidden";}
		if (crossYearObj !=	null){crossYearObj.visibility="hidden";}

		showElement( 'SELECT' );
		showElement( 'APPLET' );
	}

	function padZero(num) {
		return (num	< 10)? '0' + num : num ;
	}

	function constructDate(d,m,y)
	{
		sTmp = dateFormat;
		sTmp = sTmp.replace	("dd","<e>");
		sTmp = sTmp.replace	("d","<d>");
		sTmp = sTmp.replace	("<e>",padZero(d));
		sTmp = sTmp.replace	("<d>",d);
		sTmp = sTmp.replace	("mmm","<o>");
		sTmp = sTmp.replace	("mm","<n>");
		sTmp = sTmp.replace	("m","<m>");
		sTmp = sTmp.replace	("<m>",m+1);
		sTmp = sTmp.replace	("<n>",padZero(m+1));
		sTmp = sTmp.replace	("<o>",monthName2[m]);
		sTmp = sTmp.replace	("yyyy",y);
		return sTmp.replace ("yy",padZero(y%100));
	}

	function closeCalendar() {
		var	sTmp;

		hideCalendar();
		if (ctlToPlaceValue.tagName == "SELECT")
		{
			opt = new Option();
			opt.text = constructDate(dateSelected,monthSelected,yearSelected);
			opt.value = opt.text;
			ctlToPlaceValue.options.add(opt);
		}
		else
                {
			ctlToPlaceValue.value =	constructDate(dateSelected,monthSelected,yearSelected);
                        if( ctlToPlaceValue.onchange != null )
                            ctlToPlaceValue.onchange();
                }
                ctlToPlaceValue.focus();
	}

	/*** Month Pulldown	***/

	function StartDecMonth()
	{
		intervalID1=setInterval("decMonth()",80);
	}

	function StartIncMonth()
	{
		intervalID1=setInterval("incMonth()",80);
	}

	function incMonth () {
		monthSelected++;
		if (monthSelected>11) {
			monthSelected=0;
			yearSelected++;
		}
		constructCalendar();
	}

	function decMonth () {
		monthSelected--;
		if (monthSelected<0) {
			monthSelected=11;
			yearSelected--;
		}
		constructCalendar();
	}

	function constructMonth() {
		popDownYear();
		if (!monthConstructed) {
			sHTML =	"";
			for	(i=0; i<12;	i++) {
				sName =	monthName[i];
				if (i==monthSelected){
					sName =	"<B>" +	sName +	"</B>";
				}
				sHTML += "<tr><td id='m" + i + "' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='this.className=\"dropdown-normal-style\"' onclick='monthConstructed=false;monthSelected=" + i + ";constructCalendar();popDownMonth();event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>";
			}

			document.getElementById("selectMonth").innerHTML = "<table width=70	class='dropdown-style' cellspacing=0 onmouseover='clearTimeout(timeoutID1)'	onmouseout='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"popDownMonth()\",100);event.cancelBubble=true'>" +	sHTML +	"</table>";

			monthConstructed=true;
		}
	}

	function popUpMonth() {
		constructMonth()
		crossMonthObj.visibility = (_dom_||_ie_)? "visible"	: "show";
		crossMonthObj.left = (parseInt(crossobj.left) + 50) + "px";
		crossMonthObj.top =	(parseInt(crossobj.top) + 26) + "px";

		hideElement( 'SELECT', document.getElementById("selectMonth") );
		hideElement( 'APPLET', document.getElementById("selectMonth") );
	}

	function popDownMonth()	{
		crossMonthObj.visibility= "hidden";
	}

	/*** Year Pulldown ***/

	function incYear() {
		for	(i=0; i<7; i++){
			newYear	= (i+nStartingYear)+1;
			if (newYear==yearSelected)
			{ txtYear =	"&nbsp;<B>"	+ newYear +	"</B>&nbsp;"; }
			else
			{ txtYear =	"&nbsp;" + newYear + "&nbsp;"; }
			document.getElementById("y"+i).innerHTML = txtYear;
		}
		nStartingYear++;
		bShow=true;
	}

	function decYear() {
		for	(i=0; i<7; i++){
			newYear	= (i+nStartingYear)-1;
			if (newYear==yearSelected)
			{ txtYear =	"&nbsp;<B>"	+ newYear +	"</B>&nbsp;"; }
			else
			{ txtYear =	"&nbsp;" + newYear + "&nbsp;"; }
			document.getElementById("y"+i).innerHTML = txtYear;
		}
		nStartingYear--;
		bShow=true;
	}

	function selectYear(nYear) {
		yearSelected=parseInt(nYear+nStartingYear);
		yearConstructed=false;
		constructCalendar();
		popDownYear();
	}

	function constructYear() {
		popDownMonth();
		sHTML =	"";
		if (!yearConstructed) {

			sHTML =	"<tr><td align='center'	onmouseover='this.className=\"dropdown-select-style\"' onmouseout='clearInterval(intervalID1);this.className=\"dropdown-normal-style\"' onmousedown='clearInterval(intervalID1);intervalID1=setInterval(\"decYear()\",30)' onmouseup='clearInterval(intervalID1)'>-</td></tr>";
			j =	0;
			nStartingYear =	yearSelected-3;
			for	(i=(yearSelected-3); i<=(yearSelected+3); i++) {
				sName =	i;
				if (i==yearSelected){
					sName =	"<B>" +	sName +	"</B>";
				}

				sHTML += "<tr><td id='y" + j + "' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='this.className=\"dropdown-normal-style\"' onclick='selectYear("+j+");event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>";
				j ++;
			}

			sHTML += "<tr><td align='center' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='clearInterval(intervalID2);this.className=\"dropdown-normal-style\"' onmousedown='clearInterval(intervalID2);intervalID2=setInterval(\"incYear()\",30)'	onmouseup='clearInterval(intervalID2)'>+</td></tr>";

			document.getElementById("selectYear").innerHTML	= "<table width=44 class='dropdown-style' onmouseover='clearTimeout(timeoutID2)' onmouseout='clearTimeout(timeoutID2);timeoutID2=setTimeout(\"popDownYear()\",100)' cellspacing=0>"	+ sHTML	+ "</table>";

			yearConstructed	= true;
		}
	}

	function popDownYear() {
		clearInterval(intervalID1);
		clearTimeout(timeoutID1);
		clearInterval(intervalID2);
		clearTimeout(timeoutID2);
		crossYearObj.visibility= "hidden";
	}

	function popUpYear() {
		var	leftOffset;

		constructYear();
		crossYearObj.visibility	= (_dom_||_ie_)? "visible" : "show";
		leftOffset = parseInt(crossobj.left) + document.getElementById("spanYear").offsetLeft;
		if (_ie_)
		{
			leftOffset += 6;
		}
		crossYearObj.left =	(leftOffset) + "px";
		crossYearObj.top = (parseInt(crossobj.top) +	26) + "px";
	}

	/*** calendar ***/

	function WeekNbr(today)
	{
		Year = takeYear(today);
		Month = today.getMonth();
		Day = today.getDate();
		now = Date.UTC(Year,Month,Day+1,0,0,0);
		var Firstday = new Date();
		Firstday.setYear(Year);
		Firstday.setMonth(0);
		Firstday.setDate(1);
		then = Date.UTC(Year,0,1,0,0,0);
		var Compensation = Firstday.getDay();
		if (Compensation > 3) Compensation -= 4;
		else Compensation += 3;
		NumberOfWeek =  Math.round((((now-then)/86400000)+Compensation)/7);
		return NumberOfWeek;
	}

	function constructCalendar () {
		var dateMessage;
		var	startDate =	new	Date (yearSelected,monthSelected,1);
		var	endDate	= new Date (yearSelected,monthSelected+1,1);
		endDate	= new Date (endDate	- (24*60*60*1000));
		numDaysInMonth = endDate.getDate();

		datePointer	= 0;
		dayPointer = startDate.getDay() - startAt;

		if (dayPointer<0)
		{
			dayPointer = 6;
		}

		sHTML =	"<table	border=0 class='body-style'><tr>";

		if (showWeekNumber==1)
		{
			sHTML += "<td width=27><b>" + weekString + "</b></td><td width=1 rowspan=7 class='weeknumber-div-style'><img src='"+imgDir+"1.gif' width=1></td>";
		}

		for	(i=0; i<7; i++)	{
			sHTML += "<td width='27' align='right'><B>"+ dayName[i]+"</B></td>";
		}
		sHTML +="</tr><tr>";

		if (showWeekNumber==1)
		{
			sHTML += "<td align=right>" + WeekNbr(startDate) + "&nbsp;</td>";
		}

		for	( var i=1; i<=dayPointer;i++ )
		{
			sHTML += "<td>&nbsp;</td>";
		}

		for	( datePointer=1; datePointer<=numDaysInMonth; datePointer++ )
		{
			dayPointer++;
			sHTML += "<td align=right>";

			var sStyle="normal-day-style"; //regular day

			if ((datePointer==dateNow)&&(monthSelected==monthNow)&&(yearSelected==yearNow)) //today
			{ sStyle = "current-day-style"; }
			else if	(dayPointer % 7 == (startAt * -1) +1) //end-of-the-week day
			{ sStyle = "end-of-weekday-style"; }

			//selected day
			if ((datePointer==odateSelected) &&	(monthSelected==omonthSelected)	&& (yearSelected==oyearSelected))
			{ sStyle += " selected-day-style"; }

			sHint = "";
			for (k=0;k<HolidaysCounter;k++)
			{
				if ((parseInt(Holidays[k].d)==datePointer)&&(parseInt(Holidays[k].m)==(monthSelected+1)))
				{
					if ((parseInt(Holidays[k].y)==0)||((parseInt(Holidays[k].y)==yearSelected)&&(parseInt(Holidays[k].y)!=0)))
					{
						sStyle += " holiday-style";
						sHint+=sHint==""?Holidays[k].desc:"\n"+Holidays[k].desc;
					}
				}
			}

			var regexp= /\"/g ;
			sHint=sHint.replace(regexp,"&quot;");

			dateMessage = "onmousemove='window.status=\""+selectDateMessage.replace("[date]",constructDate(datePointer,monthSelected,yearSelected))+"\"' onmouseout='window.status=\"\"' ";

			sHTML += "<a class='"+sStyle+"' "+dateMessage+" title=\"" + sHint + "\" href='javascript:dateSelected="+datePointer+";closeCalendar();'>&nbsp;" + datePointer + "&nbsp;</a>";

			sHTML += "";
			if ((dayPointer+startAt) % 7 == startAt) {
				sHTML += "</tr><tr>" ;
				if ((showWeekNumber==1)&&(datePointer<numDaysInMonth))
				{
					sHTML += "<td align=right>" + (WeekNbr(new Date(yearSelected,monthSelected,datePointer+1))) + "&nbsp;</td>";
				}
			}
		}

		document.getElementById("content").innerHTML   = sHTML;
		document.getElementById("spanMonth").innerHTML = "&nbsp;" +	monthName[monthSelected] + "&nbsp;<IMG id='changeMonth' SRC='"+imgDir+"cal_drop1.gif' WIDTH='12' HEIGHT='10' BORDER=0>";
		document.getElementById("spanYear").innerHTML =	"&nbsp;" + yearSelected	+ "&nbsp;<IMG id='changeYear' SRC='"+imgDir+"cal_drop1.gif' WIDTH='12' HEIGHT='10' BORDER=0>";
	}

	function popUpCalendar(ctl,	ctl2, format) {
		var	leftpos=0;
		var	toppos=0;

		if (!bCalendarInited) {
			init_cal();
			if (!bCalendarInited) return;
		}
		if (ctl2.disabled) return;

		if ( crossobj.visibility ==	"hidden" ) {
			ctlToPlaceValue	= ctl2;
			dateFormat=format;

			formatChar = " ";
			aFormat	= dateFormat.split(formatChar);
			if (aFormat.length<3)
			{
				formatChar = "/";
				aFormat	= dateFormat.split(formatChar);
				if (aFormat.length<3)
				{
					formatChar = ".";
					aFormat	= dateFormat.split(formatChar);
					if (aFormat.length<3)
					{
						formatChar = "-";
						aFormat	= dateFormat.split(formatChar);
						if (aFormat.length<3)
						{
							// invalid date	format
							formatChar="";
						}
					}
				}
			}

			tokensChanged =	0;
			if ( formatChar	!= "" )
			{
				// use user's date
				aData =	ctl2.value.split(formatChar);

				for	(i=0;i<3;i++)
				{
					if ((aFormat[i]=="d") || (aFormat[i]=="dd"))
					{
						dateSelected = parseInt(aData[i], 10);
						tokensChanged ++;
					}
					else if	((aFormat[i]=="m") || (aFormat[i]=="mm"))
					{
						monthSelected =	parseInt(aData[i], 10) - 1;
						tokensChanged ++;
					}
					else if	(aFormat[i]=="yyyy")
					{
						yearSelected = parseInt(aData[i], 10);
						tokensChanged ++;
					}
					else if	(aFormat[i]=="mmm")
					{
						for	(j=0; j<12;	j++)
						{
							if (aData[i]==monthName[j]);
							{
								monthSelected=j;
								tokensChanged ++;
							}
						}
					}
				}
			}

			if ((tokensChanged!=3)||isNaN(dateSelected)||isNaN(monthSelected)||isNaN(yearSelected))
			{
				dateSelected = dateNow;
				monthSelected =	monthNow;
				yearSelected = yearNow;
			}

			odateSelected=dateSelected;
			omonthSelected=monthSelected;
			oyearSelected=yearSelected;

			aTag = ctl;
			do {
				aTag = aTag.offsetParent;
				leftpos	+= aTag.offsetLeft;
				toppos += aTag.offsetTop;
			} while(aTag.tagName!="BODY");

			crossobj.left =	(fixedX==-1 ? ctl.offsetLeft	+ leftpos :	fixedX) + "px";
			crossobj.top = (fixedY==-1 ?	ctl.offsetTop +	toppos + ctl.offsetHeight +	2 :	fixedY) + "px";
			constructCalendar (1, monthSelected, yearSelected);
			crossobj.visibility=(_dom_||_ie_)? "visible" : "show";

			hideElement( 'SELECT', document.getElementById("calendar") );
			hideElement( 'APPLET', document.getElementById("calendar") );

			bShow = true;
		}
	}

	var SaveOnDocumentKeypress = document.onkeypress;
	document.onkeypress = function hidecal1 (event) {
		if (!event) { event = window.event; }
		if (SaveOnDocumentKeypress != null){SaveOnDocumentKeypress(event);}
		if (bCalendarInited && (event) && (event.keyCode == 27)) hideCalendar();
		if ((event) && (event.keyCode==13)) {
			var DefBtn = getElement('DEFAULT_BTN');
			if ((DefBtn != null) && ((DefBtn.href != null) || (DefBtn.onclick != 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') || (srcType == 'BUTTON') || (srcTag == 'A') || (srcType == 'FILE')) return;
				event.cancelBubble = true;
				if (event.stopPropagation) event.stopPropagation();
			        if (DefBtn.onclick != null) {
                                        if (DefBtn.onclick() == false) return false;
			        }
			        if (DefBtn.href && !DefBtn.href.startsWith("javascript:void")) {
			        	var _href = ''+DefBtn.href;
			        	if (_href.startsWith('javascript:')) {
			                	var cmd = DefBtn.href.substring(11);
			                	eval( cmd );
						return false;
			        	};
			        	if (!_href.startsWith('javascript:')) {
			        		window.location.assign( DefBtn.href );
						return false;
			        	};
			        }
			};
			var none = 1;
		}
	}
	var SaveOnDocumentClick = document.onclick;
	document.onclick = function hidecal2 () {
		if (SaveOnDocumentClick != null) SaveOnDocumentClick();
		if (bCalendarInited && !bShow) hideCalendar();
		bShow = false;
	}
	function checkSubmit() {
		return false;
	}


	function setFieldValueIf(checkVal,fname,val) { return setFieldValue(fname,val,true,false,checkVal,false,false,false); }
	function setFieldValueIfNot(checkVal,fname,val) { return setFieldValue(fname,val,false,true,checkVal,false,false,false); }
	function setFieldValueSI(fname,val) { return setFieldValue(fname,val,false,false,null,false,false,true); }
	function setFieldValue(fname,val,_if,_ifnot,checkVal,notfireevent,forcefireevent,SI) {
	  var ctrl = getField(fname);
	  if (ctrl == null) return false;
	  var oldval = SI ? ctrl.selectedIndex : ctrl.value;
	  if ((_if && !(oldval == checkVal)) || (_ifnot && (oldval == checkVal))) return false;
	  if (!(oldval == val)) { if (SI) ctrl.selectedIndex = val; else ctrl.value = val; }
	  if ((!notfireevent && !(oldval == val)) || forcefireevent) ctrl.onchange();
	  return !(oldval == val);
	}

