// ========================================== Dialogs ====================================
var aiChatDlg=null;
var accLogDlg=null;
var animDlg=null;
var areaAnnDlg=null;
var clbMsmtDlg=null;
var commDlg=null;
var defBomDlg=null;
var defInstrDlg=null;
var defMtlSetDlg=null;
var defNwsFeedDlg=null;
var defSnsDlg=null;
var defVlocDlg=null;
var docMgmtDlg=null;
var dwnldDlg=null;
var fAttUpldDlg=null;
var featDlg=null;
var getAutRghtDlg=null;
var hdlFattDlg=null;
var hdlInstrDlg=null;
var hdlSnsDlg=null;
var hdlVlocDlg=null;
var imgAnnDlg=null;
var imgGalDlg=null;
var imgOpenDlg=null;
var infoPntDlg=null;
var labAnnDlg=null;
var loginDlg=null;
var matDlg=null;
var measDlg=null;
var mobFopenDlg=null;
var modSaveDlg=null;
var modSelDlg=null;
var msgDlg=null;
var multSelDlg=null;
var plCutDlg=null;
var propDlg=null;
var ptlSetDlg=null;
var regUserDlg=null;
var txtAnnDlg=null;
var txtInputDlg=null;
var uSelDlg=null;
var uSetDlg=null;
var uMgmDlg=null;
var verifyDlg=null;
var vidHlpDlg=null;
var yesNoDlg=null;

function closeAllDialogs(destroy)
{
  if(aiChatDlg != null) {aiChatDlg.dialog.style.display = 'none';if(destroy) aiChatDlg = null;}
  if(accLogDlg != null) {accLogDlg.dialog.style.display = 'none';if(destroy) accLogDlg = null;}
  if(animDlg != null) {animDlg.dialog.style.display = 'none';if(destroy) animDlg = null;}
  if(areaAnnDlg != null) {areaAnnDlg.dialog.style.display = 'none';if(destroy) areaAnnDlg = null;}
  if(clbMsmtDlg != null) {clbMsmtDlg.dialog.style.display = 'none';if(destroy) clbMsmtDlg = null;}
  if(commDlg != null) {commDlg.dialog.style.display = 'none';if(destroy) commDlg = null;}
  if(defBomDlg != null) {defBomDlg.dialog.style.display = 'none';if(destroy) defBomDlg = null;}
  if(defInstrDlg != null) {defInstrDlg.dialog.style.display = 'none';if(destroy) defInstrDlg = null;}
  if(defMtlSetDlg != null) {defMtlSetDlg.dialog.style.display = 'none';if(destroy) defMtlSetDlg = null;}
  if(defNwsFeedDlg != null) {defNwsFeedDlg.dialog.style.display = 'none';if(destroy) defNwsFeedDlg = null;}
  if(defSnsDlg != null) {defSnsDlg.dialog.style.display = 'none';if(destroy) defSnsDlg = null;}
  if(defVlocDlg != null) {defVlocDlg.dialog.style.display = 'none';if(destroy) defVlocDlg = null;}
  if(docMgmtDlg != null) {docMgmtDlg.dialog.style.display = 'none';if(destroy) docMgmtDlg = null;}
  if(dwnldDlg != null) {dwnldDlg.dialog.style.display = 'none';if(destroy) dwnldDlg = null;}
  if(fAttUpldDlg != null) {fAttUpldDlg.dialog.style.display = 'none';if(destroy) fAttUpldDlg = null;}
  if(featDlg != null) {featDlg.dialog.style.display = 'none';if(destroy) featDlg = null;}
  if(getAutRghtDlg != null) {getAutRghtDlg.dialog.style.display = 'none';if(destroy) getAutRghtDlg = null;}
  if(hdlFattDlg != null) {hdlFattDlg.dialog.style.display = 'none';if(destroy) hdlFattDlg = null;}
  if(hdlInstrDlg != null) {hdlInstrDlg.dialog.style.display = 'none';if(destroy) hdlInstrDlg = null;}
  if(hdlSnsDlg != null) {hdlSnsDlg.dialog.style.display = 'none';if(destroy) hdlSnsDlg = null;}
  if(hdlVlocDlg != null) {hdlVlocDlg.dialog.style.display = 'none';if(destroy) hdlVlocDlg = null;}
  if(imgAnnDlg != null) {imgAnnDlg.dialog.style.display = 'none';if(destroy) imgAnnDlg = null;}
  if(imgGalDlg != null) {imgGalDlg.dialog.style.display = 'none';if(destroy) imgGalDlg = null;}
  if(imgOpenDlg != null) {imgOpenDlg.dialog.style.display = 'none';if(destroy) imgOpenDlg = null;}
  if(infoPntDlg != null) {infoPntDlg.dialog.style.display = 'none';if(destroy) infoPntDlg = null;}
  if(labAnnDlg != null) {labAnnDlg.dialog.style.display = 'none';if(destroy) labAnnDlg = null;}
  if(loginDlg != null) {loginDlg.dialog.style.display = 'none';if(destroy) loginDlg = null;}
  if(matDlg != null) {matDlg.dialog.style.display = 'none';if(destroy) matDlg = null;}
  if(measDlg != null) {measDlg.dialog.style.display = 'none';if(destroy) measDlg = null;}
  if(mobFopenDlg != null) {mobFopenDlg.dialog.style.display = 'none';if(destroy) mobFopenDlg = null;}
  if(modSaveDlg != null) {modSaveDlg.dialog.style.display = 'none';if(destroy) modSaveDlg = null;}
  if(modSelDlg != null) {modSelDlg.dialog.style.display = 'none';if(destroy) modSelDlg = null;}
  if(msgDlg != null) {msgDlg.dialog.style.display = 'none';if(destroy) msgDlg = null;}
  if(multSelDlg != null) {multSelDlg.dialog.style.display = 'none';if(destroy) multSelDlg = null;}
  if(plCutDlg != null) {plCutDlg.dialog.style.display = 'none';if(destroy) plCutDlg = null;}
  if(propDlg != null) {propDlg.dialog.style.display = 'none';if(destroy) propDlg = null;}
  if(ptlSetDlg != null) {ptlSetDlg.dialog.style.display = 'none';if(destroy) ptlSetDlg = null;}
  if(regUserDlg != null) {regUserDlg.dialog.style.display = 'none';if(destroy) regUserDlg = null;}
  if(txtAnnDlg != null) {txtAnnDlg.dialog.style.display = 'none';if(destroy) txtAnnDlg = null;}
  if(txtInputDlg != null) {txtInputDlg.dialog.style.display = 'none';if(destroy) txtInputDlg = null;}
  if(uSelDlg != null) {uSelDlg.dialog.style.display = 'none';if(destroy) uSelDlg = null;}
  if(uSetDlg != null) {uSetDlg.dialog.style.display = 'none';if(destroy) uSetDlg = null;}
  if(uMgmDlg != null) {uMgmDlg.dialog.style.display = 'none';if(destroy) uMgmDlg = null;}
  if(verifyDlg != null) {verifyDlg.dialog.style.display = 'none';if(destroy) verifyDlg = null;}
  if(vidHlpDlg != null) {vidHlpDlg.dialog.style.display = 'none';if(destroy) vidHlpDlg = null;}
  if(yesNoDlg != null) {yesNoDlg.dialog.style.display = 'none';if(destroy) yesNoDlg = null;}
};//function closeAllDialogs()

function showDefVlocDlg(parentDlg)
{
  if (!defVlocDlg)
    defVlocDlg = new DialogBox('defVlocDlg', defVlocDlgCbk, cmiCanvas);

  document.getElementById("defVlocDlg_HintVal").value = "";
  defVlocDlg.showDialog(parentDlg);

  function defVlocDlgCbk(btnName)
  {
    var viewLocations = poi3dConnector.getLeftDocument().getViewLocations();

    switch(btnName)
    {
      case "save":
        var toolTip = document.getElementById("defVlocDlg_HintVal").value;
        if(toolTip.length == 0) toolTip=" "; //to be selectable

        var locatorName = "loc"+(viewLocations.length+1).toString()+"_"+Date.now().toString(36);
        leftModel.addCurrentViewPositionLocatorToModel(locatorName,toolTip);

        var cmiLocator = leftModel.getEntityByName(locatorName);
        cmiLocator.setTexture("./Poi3d/Images/telescope.png");
        cmiLocator.setPointSize(30);
        cmiLocator.fromPoi3d = true;
        let jObj = cmiLocator.getJsonObject();
        jObj.fromPoi3d = true;
        viewLocations.push(jObj);

        if(viewLocations.length == 1)
        {
          myCmiWindow.showModelLocators = true;
          myCmiWindow.selectionEnabled = true;
          myCmiWindow.makeTypeInselectable("cmiComponentObject");
        }
        poi3dConnector.getLeftDocument().getViewLocationObject().setLocalChangeFlag(true);
        break;
      case "close":
        break;
    }
  }
}//function showDefVlocDlg()

function showHdlVlocDlg(parentDlg)
{
  if (!hdlVlocDlg)
  {
    hdlVlocDlg = new DialogBox('hdlVlocDlg', hdlVlocDlgCbk, cmiCanvas);

    hdlVlocDlg.initialize = function()
    {
      let viewLocations = poi3dConnector.getLeftDocument().getViewLocations();
      let hdlVlocDlg_Sel = document.getElementById("hdlVlocDlg_Sel");
      hdlVlocDlg_Sel.options.length = 0;

      for ( var i =0; i< viewLocations.length; i++)
      {
        var option = document.createElement("option");
        option.text = viewLocations[i].sTx;
        hdlVlocDlg_Sel.add(option);
      }
    };//hdlVlocDlg.initialize
  };//if (!hdlVlocDlg)

  if(viewingMode == "VR")
  {
    var pinIcon = document.getElementById("gPinModel");
    pinIcon.checked = true;
    pinModelToEnv(pinIcon);
  }

  hdlVlocDlg.initialize();
  hdlVlocDlg.showDialog(parentDlg);

  function hdlVlocDlgCbk(btnName)
  {
    var viewLocations = poi3dConnector.getLeftDocument().getViewLocations();
    var hdlVlocDlg_Sel = document.getElementById("hdlVlocDlg_Sel");
    var currentLocation = null;
    var currentLocator = null;

    if(viewLocations.length >0)
    {
      currentLocation = viewLocations[hdlVlocDlg_Sel.selectedIndex];
      currentLocator = leftModel.getEntityByName(currentLocation.eNm);
    }

    switch(btnName)
    {
      case "set":
        hdlVlocDlg.dialog.style.display = 'block';
        if(viewLocations.length == 0) break;

        var org = currentLocator.getGlobalOrigin();
        var ang = currentLocator.getGlobalEulerAngles();
        myCmiWindow.moveViewerToModelPosition(org[0],org[1],org[2]);
        myCmiWindow.rotateViewerToModelAngles(ang[0],ang[1],ang[2]);
        myCmiWindow.drawScene();
        break;
      case "delete":
        hdlVlocDlg.dialog.style.display = 'block';
        if(viewLocations.length == 0) break;
        leftModel.removeEntitiesFromModelByNames([currentLocation.eNm]);

        for (var i=0; i<viewLocations.length; i++)
        {
          if(viewLocations[i].eNm == currentLocation.eNm)
          {
            viewLocations = viewLocations.filter(function(item) {return item !== viewLocations[i]});
            i = viewLocations.length;
          }
        }

        if(viewLocations.length == 0)
        {
          hdlVlocDlg_Sel.options.length = 0;
        }
        else
        {
          hdlVlocDlg_Sel.options.length = 0;
          for ( var i =0; i< viewLocations.length; i++)
          {
            var option = document.createElement("option");
            option.text = viewLocations[i].sTx;
            hdlVlocDlg_Sel.add(option);
          }
        }
        poi3dConnector.getLeftDocument().setViewLocations(viewLocations);
        break;
      case "close":
        break;
    }
  }//function hdlVlocDlgCbk(btnName)
}//function showHdlVlocDlg()

function showDefInstrDlg(parentDlg)
{
  if (!defInstrDlg)
  {
    defInstrDlg = new DialogBox('defInstrDlg', defInstrDlgCbk, cmiCanvas);
    defInstrDlg.instrSelection = document.getElementById("defInstrDlg_Sel");

    defInstrDlg.createNew  = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();

      var instrName = document.getElementById("defInstrDlg_NameVal").value;
      if(instrName.length == 0)
      {
        instrName="instr"+(instructions.length+1).toString()+"_"+Date.now().toString(36);
        document.getElementById("defInstrDlg_NameVal").value = instrName;
      }
      else
      {
        var foundInstruction = instructions.find(item => item.title === instrName);
        if(foundInstruction != null)
        {
          instrName="instr"+(instructions.length+1).toString()+"_"+Date.now().toString(36);
          document.getElementById("defInstrDlg_NameVal").value = instrName;
        }
      }

      var components = leftAssemblyBrowser.getHighlightedComponents(true);

      var colorVal = document.getElementById("defInstrDlg_ColVal").value;
      var oglColor = Poi3dHelpers.hexToOgl(colorVal);

      var instruction = new Poi3dInstruction();
      instruction.title = instrName;
      instruction.advice = document.getElementById("defInstrDlg_TextInp").textContent;
      instruction.blinkColor = [oglColor.r,oglColor.g,oglColor.b,1.0];
      instruction.blinkCount = 5;
      instruction.blinkPause = 0.2;

      instruction.setEntities(components);

      if(viewingMode == "VR+")
      {
        var position = myCmiWindow.getCurrentViewerPosition();
        //var angles = myCmiWindow.getCurrentViewerAngles();
        var curVwAng = myCmiWindow.getCurrentModelViewAngles();
        var angles = myCmiWindow.getModelAnglesFromViewerAngles(curVwAng[0],curVwAng[1],curVwAng[2]);

        instruction.viewPosition = new Array(position[0],position[1],position[2]);
        instruction.viewAngles = new Array(angles[0],angles[1],angles[2]);
        instruction.viewAngles = new Array(CmiHelpers.getCorrectedAngle(angles[0]),CmiHelpers.getCorrectedAngle(angles[1]),CmiHelpers.getCorrectedAngle(angles[2]));
      }
      else
      {
        instruction.viewPosition = new Array();
        instruction.viewAngles = new Array();
      }

      instructions.push(instruction);
      poi3dConnector.getLeftDocument().getInstructionObject().setLocalChangeFlag(true);
      currentInstruction=instruction;

      var option = document.createElement("option");
      option.text = instruction.title;
      defInstrDlg.instrSelection.add(option);
      defInstrDlg.instrSelection.selectedIndex = instructions.length-1;
    };//defInstrDlg.createNew

    defInstrDlg.deleteCurrent  = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();

      if(instructions.length == 0) return;
      var currentInstruction = instructions[defInstrDlg.instrSelection.selectedIndex];

      for (var i=0; i<instructions.length; i++)
      {
        if(instructions[i].title == currentInstruction.title)
        {
          instructions = instructions.filter(function(item) {return item !== instructions[i]});
          i = instructions.length;
        }
      }

      if(instructions.length == 0)
      {
        defInstrDlg.instrSelection.options.length = 0;
        document.getElementById("defInstrDlg_NameVal").value = "";
        document.getElementById("defInstrDlg_TextInp").innerHTML = "";
      }
      else
      {
        defInstrDlg.instrSelection.options.length = 0;
        for ( var i =0; i< instructions.length; i++)
        {
          var option = document.createElement("option");
          option.text = instructions[i].title;
          defInstrDlg.instrSelection.add(option);

          if(i==0)
          {
            var currentInstruction = instructions[0];
            document.getElementById("defInstrDlg_NameVal").value = currentInstruction.title;
            document.getElementById("defInstrDlg_TextInp").innerHTML = currentInstruction.advice;
            document.getElementById("defInstrDlg_ColVal").value = Poi3dHelpers.oglToHex(currentInstruction.blinkColor);

            leftAssemblyBrowser.switchHighlightStateForAll(false);
            leftBomBrowser.switchHighlightStateForAll(false);

            leftAssemblyBrowser.highlightComponents(currentInstruction.getEntities());
            leftBomBrowser.highlightComponents(currentInstruction.getEntities());

            myCmiWindow.drawScene();
          }
        }
      }//if(instructions.length == 0) else
      poi3dConnector.getLeftDocument().setInstructions(instructions);
    };//defInstrDlg.deleteCurrent

    defInstrDlg.saveCurrent  = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();
      if(instructions.length == 0) return;

      var currentInstruction = instructions[defInstrDlg.instrSelection.selectedIndex];

      var components = leftAssemblyBrowser.getHighlightedComponents(true);

      var colorVal = document.getElementById("defInstrDlg_ColVal").value;
      var oglColor = Poi3dHelpers.hexToOgl(colorVal);

      currentInstruction.advice = document.getElementById("defInstrDlg_TextInp").textContent;
      currentInstruction.blinkColor = [oglColor.r,oglColor.g,oglColor.b,1.0];
      currentInstruction.blinkCount = 5;
      currentInstruction.blinkPause = 0.2;

      currentInstruction.setEntities(components);
      poi3dConnector.getLeftDocument().getInstructionObject().setLocalChangeFlag(true);

      if(viewingMode == "VR+")
      {
        var position = myCmiWindow.getCurrentViewerPosition();
        var curVwAng = myCmiWindow.getCurrentModelViewAngles();
        var rotationArray = myCmiWindow.getModelAnglesFromViewerAngles(curVwAng[0],curVwAng[1],curVwAng[2]);

        currentInstruction.viewPosition = new Array(position[0],position[1],position[2]);
        currentInstruction.viewAngles = new Array(CmiHelpers.getCorrectedAngle(rotationArray[0]),CmiHelpers.getCorrectedAngle(rotationArray[1]),CmiHelpers.getCorrectedAngle(rotationArray[2]));
      }
      else
      {
        currentInstruction.viewPosition = new Array();
        currentInstruction.viewAngles = new Array();
      }
    };//defInstrDlg.saveCurrent

    defInstrDlg.showCurrent  = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();
      if(instructions.length == 0) return;

      var currentInstruction = instructions[defInstrDlg.instrSelection.selectedIndex];

      var components = currentInstruction.getEntities();
      runShowComponentAnimation(components,instructionAnimation,"instructionAnimation",currentInstruction.blinkCount,currentInstruction.blinkColor,currentInstruction.blinkPause);
    };//defInstrDlg.showCurrent

    defInstrDlg.renameActive  = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();
      if(instructions.length >0)
      {
        currentInstruction = instructions[defInstrDlg.instrSelection.selectedIndex];
        var instrName = document.getElementById("defInstrDlg_NameVal").value;
        if(instrName.length > 0)
        {
          var foundInstruction = instructions.find(item => item.title === instrName);
          if(foundInstruction == null)
          {
            currentInstruction.title = instrName;
            defInstrDlg.instrSelection[defInstrDlg.instrSelection.selectedIndex].text = instrName;
          }
        }
        poi3dConnector.getLeftDocument().getInstructionObject().setLocalChangeFlag(true);
      }
    };//defInstrDlg.renameActive

    defInstrDlg.onSelectionChange = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();

      var currentInstruction = instructions[defInstrDlg.instrSelection.selectedIndex];
      document.getElementById("defInstrDlg_NameVal").value = currentInstruction.title;
      document.getElementById("defInstrDlg_TextInp").innerHTML = currentInstruction.advice;
      document.getElementById("defInstrDlg_ColVal").value = Poi3dHelpers.oglToHex(currentInstruction.blinkColor);

      leftAssemblyBrowser.switchHighlightStateForAll(false);
      leftBomBrowser.switchHighlightStateForAll(false);

      leftAssemblyBrowser.highlightComponents(currentInstruction.getEntities());
      leftBomBrowser.highlightComponents(currentInstruction.getEntities());

      myCmiWindow.drawScene();
    };//defInstrDlg.onSelectionChange

    defInstrDlg.initialize = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();

      defInstrDlg.instrSelection.options.length = 0;
      document.getElementById("defInstrDlg_NameVal").value = "";
      document.getElementById("defInstrDlg_TextInp").innerHTML = "";

      for ( var i =0; i< instructions.length; i++)
      {
        var option = document.createElement("option");
        option.text = instructions[i].title;
        defInstrDlg.instrSelection.add(option);

        if(i==0)
        {
          var currentInstruction = instructions[0];
          document.getElementById("defInstrDlg_NameVal").value = currentInstruction.title;
          document.getElementById("defInstrDlg_TextInp").innerHTML = currentInstruction.advice;
          document.getElementById("defInstrDlg_ColVal").value = Poi3dHelpers.oglToHex(currentInstruction.blinkColor);

          leftAssemblyBrowser.switchHighlightStateForAll(false);
          leftBomBrowser.switchHighlightStateForAll(false);

          leftAssemblyBrowser.highlightComponents(currentInstruction.getEntities());
          leftBomBrowser.highlightComponents(currentInstruction.getEntities());

          myCmiWindow.drawScene();
        }
      }
    };//defInstrDlg.initialize
  }//if (!defInstrDlg)

  //init --------------
  defInstrDlg.initialize();
  defInstrDlg.showDialog(parentDlg);

  function defInstrDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "diCancel":
      case "close":
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        leftBomBrowser.switchHighlightStateForAll(false);
        break;
      default:
        defInstrDlg.dialog.style.display = 'block';
        break;
    }//switch(btnName)
  }
}//function showDefInstrDlg()

function showDefSnsDlg(parentDlg,sensorElement)
{
  if (!defSnsDlg)
  {
    defSnsDlg = new DialogBox('defSnsDlg', defSnsDlgCbk, cmiCanvas);
    defSnsDlg.sensorSelection = document.getElementById("defSnsDlg_Sel");
    defSnsDlg.dateOptions = {year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"};

    defSnsDlg.onTabSelectionChange = function(sectionToActivate)
    {
      if(sectionToActivate == "defSensorDlg_DataSection")
      {
        Poi3dHelpers.setDisplayStyle("defSensorDlg_DataSection","block");
        Poi3dHelpers.setDisplayStyle("defSensorDlg_LoginSection","none");
        Poi3dHelpers.setDisplayStyle("defSensorDlg_QuerySection","none");
      }
      else if(sectionToActivate == "defSensorDlg_LoginSection")
      {
        Poi3dHelpers.setDisplayStyle("defSensorDlg_DataSection","none");
        Poi3dHelpers.setDisplayStyle("defSensorDlg_LoginSection","block");
        Poi3dHelpers.setDisplayStyle("defSensorDlg_QuerySection","none");
      }
      else if(sectionToActivate == "defSensorDlg_QuerySection")
      {
        Poi3dHelpers.setDisplayStyle("defSensorDlg_DataSection","none");
        Poi3dHelpers.setDisplayStyle("defSensorDlg_LoginSection","none");
        Poi3dHelpers.setDisplayStyle("defSensorDlg_QuerySection","block");
      }
    };//defSnsDlg.onTabSelectionChange

    defSnsDlg.createNew  = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];

      let sensorName = document.getElementById("defSnsDlg_NameVal").value;
      if(sensorName.length == 0)
      {
        sensorName="sensor"+(sensors.length+1).toString()+"_"+Date.now().toString(36);
        document.getElementById("defSnsDlg_NameVal").value = sensorName;
      }
      else
      {
        let foundSensor = sensors.find(item => item.getTitle() === sensorName);
        if(foundSensor != null)
        {
          sensorName="sensor"+(sensors.length+1).toString()+"_"+Date.now().toString(36);
          document.getElementById("defSnsDlg_NameVal").value = sensorName;
        }
      }

      let colorVal = document.getElementById("defSnsDlg_ColVal").value;
      let oglColor = Poi3dHelpers.hexToOgl(colorVal);

      let sensorObj = poi3dConnector.getLeftDocument().getSensorObject();
      let sensor = new Poi3dSensor(sensorObj);
      sensor.setTitle(sensorName);
      sensor.setPageRef(currentPageNr);
      //copy values from current sensor
      if(currentSensor)
      {
        sensor.setLoginName(currentSensor.getLoginName());
        sensor.setLoginPwd(currentSensor.getLoginPwd());
        sensor.setLoginUrl(currentSensor.getLoginUrl());
        sensor.setLoginPayload(currentSensor.getLoginPayload());
        sensor.setLoginMethod(currentSensor.getLoginMethod());
        sensor.setQueryUrl(currentSensor.getQueryUrl());
        sensor.setQueryPayload(currentSensor.getQueryPayload());
        sensor.setQueryMethod(currentSensor.getQueryMethod());
        sensor.setUpdateInterval(currentSensor.getUpdateInterval());
        sensor.setMaxValue(currentSensor.getMaxValue());
        sensor.setMinValue(currentSensor.getMinValue());
        sensor.setMaxFailedQueries(currentSensor.getMaxFailedQueries());
        sensor.setUiString(currentSensor.getUiString());
        sensor.setJsonRef(currentSensor.getJsonRef());
      }

      sensors.push(sensor);
      sensorObj.setLocalChangeFlag(true);

      let option = document.createElement("option");
      option.text = sensor.getTitle();
      defSnsDlg.sensorSelection.add(option);
      defSnsDlg.sensorSelection.selectedIndex = sensors.length-1;
      defSnsDlg.onSelectionChange();
      updatePageBrowser();
    };//defSnsDlg.createNew

    defSnsDlg.deleteCurrent  = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();

      if(sensors.length == 0) return;
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      currentSensor.detach();

      for (let i=0; i<sensors.length; i++)
      {
        if(sensors[i].getTitle() == currentSensor.getTitle())
        {
          sensors = sensors.filter(function(item) {return item !== sensors[i]});
          i = sensors.length;
        }
      }

      if(sensors.length == 0)
      {
        defSnsDlg.sensorSelection.options.length = 0;
        document.getElementById("defSnsDlg_NameVal").value = "";
      }
      else
      {
        defSnsDlg.sensorSelection.options.length = 0;
        for ( let i =0; i< sensors.length; i++)
        {
          let option = document.createElement("option");
          option.text = sensors[i].getTitle();
          defSnsDlg.sensorSelection.add(option);

          if(i==0)
          {
            let currentSensor = sensors[0];
            document.getElementById("defSnsDlg_NameVal").value = currentSensor.getTitle();
            document.getElementById("defSnsDlg_ColVal").value = Poi3dHelpers.oglToHex(currentSensor.getBlinkColor());

            leftAssemblyBrowser.switchHighlightStateForAll(false);
            leftBomBrowser.switchHighlightStateForAll(false);

            leftAssemblyBrowser.highlightComponents(currentSensor.getEntities());
            leftBomBrowser.highlightComponents(currentSensor.getEntities());

            myCmiWindow.drawScene();
          }
        }
      }//if(sensors.length == 0) else
      poi3dConnector.getLeftDocument().setSensors(sensors);
      updatePageBrowser();
    };//defSnsDlg.deleteCurrent

    defSnsDlg.saveCurrent  = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      if(sensors.length == 0) return;

      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];

      let components = leftAssemblyBrowser.getHighlightedComponents(true);

      let colorVal = document.getElementById("defSnsDlg_ColVal").value;
      let oglColor = Poi3dHelpers.hexToOgl(colorVal);

      currentSensor.setBlinkColor([oglColor.r,oglColor.g,oglColor.b,1.0]);
      currentSensor.setBlinkCount(5);
      currentSensor.setBlinkPause(0.2);

      currentSensor.setEntities(components);
      poi3dConnector.getLeftDocument().getSensorObject().setLocalChangeFlag(true);

      if(viewingMode == "VR+")
      {
        let position = myCmiWindow.getCurrentViewerPosition();
        let curVwAng = myCmiWindow.getCurrentModelViewAngles();
        let rotationArray = myCmiWindow.getModelAnglesFromViewerAngles(curVwAng[0],curVwAng[1],curVwAng[2]);

        currentSensor.setViewPosition(new Array(position[0],position[1],position[2]));
        currentSensor.setViewAngles(new Array(CmiHelpers.getCorrectedAngle(rotationArray[0]),CmiHelpers.getCorrectedAngle(rotationArray[1]),CmiHelpers.getCorrectedAngle(rotationArray[2])));
      }
      else
      {
        currentSensor.setViewPosition(new Array());
        currentSensor.setViewAngles(new Array());
      }

      let uiPos = document.getElementById("defSnsDlg_ViewPosVal").value;

      currentSensor.setPageRef(currentPageNr);

      currentSensor.setUpdateInterval(parseInt(document.getElementById("defSnsDlg_UpdIntrvVal").value));
      currentSensor.setMaxValue(parseFloat(document.getElementById("defSnsDlg_MaxValVal").value));
      currentSensor.setMinValue(parseFloat(document.getElementById("defSnsDlg_MinValVal").value));
      currentSensor.setMaxFailedQueries(parseInt(document.getElementById("defSnsDlg_MaxQryErrVal").value));
      currentSensor.setUiVisible(document.getElementById("defSnsDlg_VisVal").checked,true);
      currentSensor.setUiString(document.getElementById("defSnsDlg_ViewTxtVal").value);

      currentSensor.setLoginName(document.getElementById("defSnsDlg_LoginUsrVal").value);
      currentSensor.setLoginPwd(document.getElementById("defSnsDlg_LoginPwdVal").value);
      currentSensor.setLoginUseCredentials(document.getElementById("defSnsDlg_LoginUseCredVal").checked);
      currentSensor.setLoginMethod(document.getElementById("defSnsDlg_LoginMethodSel").value );
      currentSensor.setLoginRequestMethod(document.getElementById("defSnsDlg_LoginReqMethodSel").value );
      currentSensor.setLoginDataType(document.getElementById("defSnsDlg_LoginDataTypSel").value );
      currentSensor.setLoginDataFormat(document.getElementById("defSnsDlg_LoginDataFmtSel").value );
      currentSensor.setLoginHeaders(document.getElementById("defSnsDlg_LoginHdrVal").value);
      currentSensor.setLoginPayload(document.getElementById("defSnsDlg_LoginPayldVal").value);
      currentSensor.setLoginUrl(document.getElementById("defSnsDlg_LoginUrlVal").value);

      currentSensor.setQueryUseCredentials(document.getElementById("defSnsDlg_QryUseCredVal").checked);
      currentSensor.setQueryMethod(document.getElementById("defSnsDlg_QryMethodSel").value);
      currentSensor.setQueryRequestMethod(document.getElementById("defSnsDlg_QryReqMethodSel").value );
      currentSensor.setQueryDataType(document.getElementById("defSnsDlg_QryDataTypSel").value );
      currentSensor.setQueryDataFormat(document.getElementById("defSnsDlg_QryDataFmtSel").value );
      currentSensor.setQueryHeaders(document.getElementById("defSnsDlg_QryHdrVal").value);
      currentSensor.setQueryPayload(document.getElementById("defSnsDlg_QryPayldVal").value);
      currentSensor.setQueryUrl(document.getElementById("defSnsDlg_QryUrlVal").value);
      currentSensor.setJsonRef(document.getElementById("defSnsDlg_QryJsonReflVal").value);
      currentSensor.setUpdateActivated(document.getElementById("defSnsDlg_QryActivatedVal").checked);

      if(document.getElementById("defSnsDlg_QryActivatedVal").checked == true)
        currentSensor.startValueUpdate();
      else
        currentSensor.stopValueUpdate();

      updatePageBrowser();
    };//defSnsDlg.saveCurrent

    defSnsDlg.animateCurrent  = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      if(sensors.length == 0) return;

      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      let components = leftAssemblyBrowser.getHighlightedComponents(true);
      let colorVal = document.getElementById("defSnsDlg_ColVal").value;
      let colorValRGB = Poi3dHelpers.hexToOgl(colorVal);
      let showColor = [colorValRGB.r,colorValRGB.g,colorValRGB.b];

      if(currentSensor.getPageRef() != currentPageNr)
      {
        currentPageNr=currentSensor.getPageRef();
        openCurrentMultipageImage();
      }
      poi3dConnector.getLeftDocument().getSensorObject().showSingle(currentSensor);

      runShowComponentAnimation(components,sensorAnimation,"sensorAnimation",5,showColor,0.2);
    };//defSnsDlg.showCurrent

    defSnsDlg.renameActive  = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      if(sensors.length >0)
      {
        currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
        let sensorName = document.getElementById("defSnsDlg_NameVal").value;
        if(sensorName.length > 0)
        {
          let foundSensor = sensors.find(item => item.getTitle() === sensorName);
          if(foundSensor == null)
          {
            currentSensor.setTitle(sensorName);
            defSnsDlg.sensorSelection[defSnsDlg.sensorSelection.selectedIndex].text = sensorName;
          }
        }
        poi3dConnector.getLeftDocument().getSensorObject().setLocalChangeFlag(true);
      }
    };//defSnsDlg.renameActive

    defSnsDlg.updateFieldsAppearance = function()
    {
      document.getElementById("defSnsDlg_LoginUsrVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginPwdVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginUseCredVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginMethodSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginReqMethodSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginDataTypSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginDataFmtSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginHdrVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginPayldVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_LoginUrlVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_LogoffUrlVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_TstLoginImg").style.visibility = "initial";
      document.getElementById("defSnsDlg_TstLogoffImg").style.visibility = "initial";

      document.getElementById("defSnsDlg_QryUseCredVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryMethodSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryReqMethodSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryDataTypSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryDataFmtSel").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryHdrVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryPayldVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryUrlVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_QryJsonReflVal").style.visibility = "initial";
      document.getElementById("defSnsDlg_TstJsonImg").style.visibility = "initial";

      switch(document.getElementById("defSnsDlg_LoginMethodSel").value)
      {
        case "AjaxQuery":
          break;
        case "FetchQuery":
          document.getElementById("defSnsDlg_LoginUsrVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginPwdVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginUseCredVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginDataFmtSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginHdrVal").style.visibility = "hidden";
          break;
        case "PhpQuerySensor":
        case "WebSocketsQuery":
          document.getElementById("defSnsDlg_LoginUseCredVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginReqMethodSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginDataTypSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginDataFmtSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginHdrVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginPayldVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LogoffUrlVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_TstLoginImg").style.visibility = "hidden";
          document.getElementById("defSnsDlg_TstLogoffImg").style.visibility = "hidden";
          break;
      }

      switch(document.getElementById("defSnsDlg_LoginReqMethodSel").value)
      {
        case "GetMethod":
          document.getElementById("defSnsDlg_LoginDataFmtSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_LoginPayldVal").style.visibility = "hidden";
          break;
        case "PostMethod":
          break;
      }

      switch(document.getElementById("defSnsDlg_QryMethodSel").value)
      {
        case "AjaxQuery":
          break;
        case "FetchQuery":
          document.getElementById("defSnsDlg_QryUseCredVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryDataFmtSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryHdrVal").style.visibility = "hidden";
          break;
        case "PhpQuerySensor":
        case "WebSocketsQuery":
          document.getElementById("defSnsDlg_QryUseCredVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryReqMethodSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryDataTypSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryDataFmtSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryHdrVal").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryPayldVal").style.visibility = "hidden";
          break;
      }

      switch(document.getElementById("defSnsDlg_QryReqMethodSel").value)
      {
        case "GetMethod":
          document.getElementById("defSnsDlg_QryDataFmtSel").style.visibility = "hidden";
          document.getElementById("defSnsDlg_QryPayldVal").style.visibility = "hidden";
          break;
        case "PostMethod":
          break;
      }
    };//defSnsDlg.onLoginMethodSelectionChange

    defSnsDlg.onSelectionChange = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();

      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];

      if(currentSensor.getPageRef() != currentPageNr)
      {
        currentPageNr=currentSensor.getPageRef();
        openCurrentMultipageImage();
      }

      document.getElementById("defSnsDlg_NameVal").value = currentSensor.getTitle();
      document.getElementById("defSnsDlg_ColVal").value = Poi3dHelpers.oglToHex(currentSensor.getBlinkColor());

      leftAssemblyBrowser.switchHighlightStateForAll(false);
      leftBomBrowser.switchHighlightStateForAll(false);

      leftAssemblyBrowser.highlightComponents(currentSensor.getEntities());
      leftBomBrowser.highlightComponents(currentSensor.getEntities());

      let uiPos = currentSensor.getUiPosition();

      document.getElementById("defSnsDlg_UpdIntrvVal").value = currentSensor.getUpdateInterval();
      document.getElementById("defSnsDlg_MaxValVal").value = currentSensor.getMaxValue();
      document.getElementById("defSnsDlg_MinValVal").value = currentSensor.getMinValue();
      document.getElementById("defSnsDlg_MaxQryErrVal").value = currentSensor.getMaxFailedQueries();
      document.getElementById("defSnsDlg_VisVal").checked = currentSensor.getStoredUiVisible();
      document.getElementById("defSnsDlg_ViewTxtVal").value = currentSensor.getUiString();
      document.getElementById("defSnsDlg_ValOutVal").value = currentSensor.getValueOutput();
      document.getElementById("defSnsDlg_ViewPosVal").value = uiPos[0].toFixed(2) + "," + uiPos[1].toFixed(2) + "," + uiPos[2].toFixed(2);

      document.getElementById("defSnsDlg_LoginUsrVal").value = currentSensor.getLoginName();
      document.getElementById("defSnsDlg_LoginPwdVal").value = currentSensor.getLoginPwd();
      document.getElementById("defSnsDlg_LoginUseCredVal").checked = currentSensor.getLoginUseCredentials();
      document.getElementById("defSnsDlg_LoginMethodSel").value = currentSensor.getLoginMethod();
      document.getElementById("defSnsDlg_LoginReqMethodSel").value = currentSensor.getLoginRequestMethod();
      document.getElementById("defSnsDlg_LoginDataTypSel").value = currentSensor.getLoginDataType();
      document.getElementById("defSnsDlg_LoginDataFmtSel").value = currentSensor.getLoginDataFormat();
      document.getElementById("defSnsDlg_LoginHdrVal").value = currentSensor.getLoginHeaders();
      document.getElementById("defSnsDlg_LoginPayldVal").value = currentSensor.getLoginPayload();
      document.getElementById("defSnsDlg_LoginUrlVal").value = currentSensor.getLoginUrl();
      document.getElementById("defSnsDlg_LogoffUrlVal").value = currentSensor.getLogoffUrl();

      document.getElementById("defSnsDlg_QryUseCredVal").checked = currentSensor.getQueryUseCredentials();
      document.getElementById("defSnsDlg_QryMethodSel").value = currentSensor.getQueryMethod();
      document.getElementById("defSnsDlg_QryReqMethodSel").value = currentSensor.getQueryRequestMethod();
      document.getElementById("defSnsDlg_QryDataTypSel").value = currentSensor.getQueryDataType();
      document.getElementById("defSnsDlg_QryDataFmtSel").value = currentSensor.getQueryDataFormat();
      document.getElementById("defSnsDlg_QryHdrVal").value = currentSensor.getQueryHeaders();
      document.getElementById("defSnsDlg_QryPayldVal").value = currentSensor.getQueryPayload();
      document.getElementById("defSnsDlg_QryUrlVal").value = currentSensor.getQueryUrl();
      document.getElementById("defSnsDlg_QryJsonReflVal").value = currentSensor.getJsonRef();
      document.getElementById("defSnsDlg_QryCurrValVal").value = currentSensor.getCurrentValue();
      document.getElementById("defSnsDlg_QryUpdDateVal").value = currentSensor.getQueryDate().toLocaleString(poi3dConnector.getCurrentLanguage(),defSnsDlg.dateOptions);
      document.getElementById("defSnsDlg_QryActivatedVal").checked = currentSensor.getUpdateActivated();

      document.getElementById("defSnsDlg_StateVal").value = currentSensor.getState();

      defSnsDlg.updateFieldsAppearance();
      myCmiWindow.drawScene();
    };//defSnsDlg.onSelectionChange

    defSnsDlg.pickUiPosition = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      if(sensors.length == 0) return;

      interactionMode="snsPosPick";
      myCmiWindow.setMouseModeToPicking();
      myCmiWindow.showModelLocators = true;
      setStatusText(poi3dConnector.getStatusText(2));//"select position"
    };//defSnsDlg.pickUiPosition

    defSnsDlg.setPickPos = function()
    {
      if(pickPoints.length > 0)
      {
        let sensors = poi3dConnector.getLeftDocument().getSensors();

        let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let globalOrigin=loc1.getGlobalOrigin();
        let snsOrg = new Array(globalOrigin[0],globalOrigin[1],globalOrigin[2]);
        document.getElementById("defSnsDlg_ViewPosVal").value = snsOrg[0].toFixed(2)+","+snsOrg[1].toFixed(2)+","+snsOrg[2].toFixed(2);
        currentSensor.setUiPosition(snsOrg);
        currentSensor.updatePosition(myCmiWindow);
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      if(viewingMode == "VR+")
        switchMouseMode("zoom");
      else
        switchMouseMode("rotate");

      interactionMode = "";
      handleSelectionSettings();

    };//defSnsDlg.setPickPos

    defSnsDlg.loginTest = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      if(currentSensor)
      {
        currentSensor.login();
      }
    };//defSnsDlg.loginTest

    defSnsDlg.logoffTest = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      if(currentSensor)
      {
        currentSensor.logoff();
      }
    };//defSnsDlg.logoffTest

    defSnsDlg.uiStringTest = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      if(currentSensor)
      {
        //ui-text not saved
        let testString = document.getElementById("defSnsDlg_ViewTxtVal").value;
        document.getElementById("defSnsDlg_ValOutVal").value = currentSensor.getValueOutput(testString);
      }
    };//defSnsDlg.uiStringTest

    defSnsDlg.queryTest = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      if(currentSensor)
      {
        currentSensor.querySensorValue(currentSensor,true);
      }
    };//defSnsDlg.queryTest

    defSnsDlg.getJsonValueTest = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      if(currentSensor)
      {
        currentSensor.getJsonQueryValue();
      }
    };//defSnsDlg.getJsonValueTest

    defSnsDlg.downloadHelp = function()
    {
      let cfg = poi3dConnector.getPortalConfiguration();
      window.open(cfg.downloadDir+'/Sensor-Queries.pdf','_blank');
    };//defSnsDlg.downloadHelp

    defSnsDlg.onUpdate = function(context)
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[defSnsDlg.sensorSelection.selectedIndex];
      if(currentSensor)
      {
        switch(context)
        {
          case "updateUi":
            document.getElementById("defSnsDlg_QryCurrValVal").value = currentSensor.getCurrentValue();
            document.getElementById("defSnsDlg_QryUpdDateVal").value = currentSensor.getQueryDate().toLocaleString(poi3dConnector.getCurrentLanguage(),defSnsDlg.dateOptions);
            document.getElementById("defSnsDlg_StateVal").value = currentSensor.getState();
            break;
          case "showResponse":
            console.clear();
            console.log(currentSensor.getQueryUrl() + " response:");
            console.log(JSON.stringify(currentSensor.getResponseObject()));
            break;
        }
      }
    };//defSnsDlg.onUpdate

    defSnsDlg.initialize = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();

      defSnsDlg.sensorSelection.options.length = 0;

      document.getElementById("defSnsDlg_UpdIntrvVal").value = "10";
      document.getElementById("defSnsDlg_MaxValVal").value = "0.0";
      document.getElementById("defSnsDlg_MinValVal").value = "0.0";
      document.getElementById("defSnsDlg_VisVal").checked = true;
      document.getElementById("defSnsDlg_ViewTxtVal").value = "";
      document.getElementById("defSnsDlg_ValOutVal").value = "";
      document.getElementById("defSnsDlg_ViewPosVal").value = "0.0,0.0,0.0";

      document.getElementById("defSnsDlg_LoginUsrVal").value = "";
      document.getElementById("defSnsDlg_LoginPwdVal").value = "";
      document.getElementById("defSnsDlg_LoginUseCredVal").checked = true;
      document.getElementById("defSnsDlg_LoginMethodSel").value = "AjaxQuery";
      document.getElementById("defSnsDlg_LoginReqMethodSel").value = "GetMethod";
      document.getElementById("defSnsDlg_LoginDataTypSel").value = "JsonType";
      document.getElementById("defSnsDlg_LoginDataFmtSel").value = "FormType";
      document.getElementById("defSnsDlg_LoginHdrVal").value = "";
      document.getElementById("defSnsDlg_LoginPayldVal").value = "";
      document.getElementById("defSnsDlg_LoginUrlVal").value = "";
      document.getElementById("defSnsDlg_LogoffUrlVal").value = "";

      document.getElementById("defSnsDlg_QryUseCredVal").checked = false;
      document.getElementById("defSnsDlg_QryMethodSel").value = "AjaxQuery";
      document.getElementById("defSnsDlg_QryReqMethodSel").value = "GetMethod";
      document.getElementById("defSnsDlg_QryDataTypSel").value = "JsonType";
      document.getElementById("defSnsDlg_QryDataFmtSel").value = "FormType";
      document.getElementById("defSnsDlg_QryHdrVal").value = "";
      document.getElementById("defSnsDlg_QryPayldVal").value = "";
      document.getElementById("defSnsDlg_QryUrlVal").value = "";
      document.getElementById("defSnsDlg_QryJsonReflVal").value = "";
      document.getElementById("defSnsDlg_QryCurrValVal").value = 0.0;
      document.getElementById("defSnsDlg_QryUpdDateVal").value = "";
      document.getElementById("defSnsDlg_QryActivatedVal").checked = false;

      document.getElementById("defSnsDlg_StateVal").value = "";

      for ( let i =0; i< sensors.length; i++)
      {
        let option = document.createElement("option");
        option.text = sensors[i].getTitle();
        defSnsDlg.sensorSelection.add(option);
      }

      if(viewingMode == "2d")
        Poi3dHelpers.canBeUsed("defSnsDlg_AnimButt",false);
      else
        Poi3dHelpers.canBeUsed("defSnsDlg_AnimButt",true);

      if(sensors.length > 0)
        defSnsDlg.onSelectionChange();
      else
        defSnsDlg.updateFieldsAppearance();

      myCmiWindow.makeAllTypesInselectable();
      myCmiWindow.makeTypeSelectable("cmiComponentObject");
      myCmiWindow.makeTypeSelectable("cmiGrepObject");

      let sensorObject = poi3dConnector.getLeftDocument().getSensorObject();
      sensorObject.setDialogUpdateFunction(defSnsDlg.onUpdate);
    };//defSnsDlg.initialize
  }//if (!defSnsDlg)

  //init --------------
  defSnsDlg.initialize();
  defSnsDlg.showDialog(parentDlg);

  if(sensorElement)
  {
    let sensors = poi3dConnector.getLeftDocument().getSensors();
    for (let i=0; i<sensors.length; i++)
    {
      if(sensors[i].getId() == sensorElement.id)
      {
        defSnsDlg.sensorSelection.selectedIndex = i;
        defSnsDlg.onSelectionChange();
        i=sensors.length;
      }
    }//for (let i=0; i<sensors.length; i++)
  }//if(sensorElement)

  function defSnsDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "dsCancel":
      case "close":
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        leftBomBrowser.switchHighlightStateForAll(false);
        break;
      default:
        defSnsDlg.dialog.style.display = 'block';
        break;
    }//switch(btnName)

    handleSelectionSettings();
  }
}//function showDefSnsDlg()

function showHdlSnsDlg(parentDlg)
{
  if (!hdlSnsDlg)
  {
    hdlSnsDlg = new DialogBox('hdlSnsDlg', hdlSnsDlgCbk, cmiCanvas);

    hdlSnsDlg.onSelectionChange = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let sensorSelection = document.getElementById("hdlSnsDlg_Sel");
      let currentSensor = sensors[sensorSelection.selectedIndex];
      let beamButton = document.getElementById("hdlSnsDlg_BeamBut");
      let showButton = document.getElementById("hdlSnsDlg_ShowBut");
      let selectButton = document.getElementById("hdlSnsDlg_SelBut");
      let animateButton = document.getElementById("hdlSnsDlg_AnimBut");

      if(currentSensor.getPageRef() != currentPageNr)
      {
        currentPageNr=currentSensor.getPageRef();
        openCurrentMultipageImage();
      }

      if(currentSensor.getViewPosition().length==0)
        Poi3dHelpers.canBeUsed(beamButton,false);
      else
        Poi3dHelpers.canBeUsed(beamButton,true);

      if(currentSensor.getUiVisible() == true)
        Poi3dHelpers.canBeUsed(showButton,false);
      else
        Poi3dHelpers.canBeUsed(showButton,true);

      if(currentSensor.getEntities().length==0)
      {
        Poi3dHelpers.canBeUsed(selectButton,false);
        Poi3dHelpers.canBeUsed(animateButton,false);
      }
      else
      {
        Poi3dHelpers.canBeUsed(selectButton,true);
        Poi3dHelpers.canBeUsed(animateButton,true);
      }
    };//hdlSnsDlg.onSelectionChange

    hdlSnsDlg.beamCurrent = function()
    {
      let sensorSelection = document.getElementById("hdlSnsDlg_Sel");
      let sensors = poi3dConnector.getLeftDocument().getSensors();

      if(sensors.length >0)
      {
        let currentSensor = sensors[sensorSelection.selectedIndex];
        if(currentSensor.getViewPosition().length==0) return;

        if(viewingMode.includes("VR")==false)
        {
          let vrCheckbox = document.getElementById("gVrMode");
          vrCheckbox.checked = true;
          switchToVrMode(vrCheckbox);
        }

        if(viewingMode != "VR+")
        {
          let pinIcon = document.getElementById("gPinModel");
          pinIcon.checked = true;
          pinModelToEnv(pinIcon);
        }

        let viewPosition = currentSensor.getViewPosition();
        let viewAngles = currentSensor.getViewAngles();
        myCmiWindow.moveViewerToModelPosition(viewPosition[0],viewPosition[1],viewPosition[2]);
        myCmiWindow.rotateViewerToModelAngles(viewAngles[0],viewAngles[1],viewAngles[2]);
        myCmiWindow.drawScene();
        poi3dConnector.getLeftDocument().getSensorObject().updatePositions(myCmiWindow);
      }//if(sensors.length >0)
    };//hdlSnsDlg.beamCurrent

    hdlSnsDlg.showCurrent = function()
    {
      let sensorSelection = document.getElementById("hdlSnsDlg_Sel");
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let currentSensor = sensors[sensorSelection.selectedIndex];
      currentSensor.setUiVisible(true,false);
    };

    hdlSnsDlg.animateCurrent = function()
    {
      let sensorSelection = document.getElementById("hdlSnsDlg_Sel");
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      if(sensors.length == 0) return;

      let currentSensor = sensors[sensorSelection.selectedIndex];
      let components = currentSensor.getEntities();

      if(currentSensor.getPageRef() != currentPageNr)
      {
        currentPageNr=currentSensor.getPageRef();
        openCurrentMultipageImage();
      }
      poi3dConnector.getLeftDocument().getSensorObject().showSingle(currentSensor);

      runShowComponentAnimation(components,sensorAnimation,"sensorAnimation",currentSensor.getBlinkCount(),currentSensor.getBlinkColor(),currentSensor.getBlinkPause());
    };//hdlSnsDlg.selectCurrent

    hdlSnsDlg.selectCurrent = function()
    {
      let sensorSelection = document.getElementById("hdlSnsDlg_Sel");
      let sensors = poi3dConnector.getLeftDocument().getSensors();

      if(sensors.length >0)
      {
        if(document.getElementById("leftBrowserArea").style.visibility != 'visible')
          showLeftTable(true);

        let currentSensor = sensors[sensorSelection.selectedIndex];

        let components = currentSensor.getEntities();
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        leftBomBrowser.switchHighlightStateForAll(false);

        leftAssemblyBrowser.highlightComponents(components);
        leftBomBrowser.highlightComponents(components);

        leftAssemblyBrowser.expandComponentBranch(components);
        leftBomBrowser.expandComponentBranch(components);
        myCmiWindow.drawScene();
      }//if(sensors.length >0)
    };//hdlSnsDlg.selectCurrent

    hdlSnsDlg.applyAction = function()
    {
      let sensorAction = document.getElementById("hdlSnsDlg_ActionSel").value;
      let sensorsObj = poi3dConnector.getLeftDocument().getSensorObject();
      switch(sensorAction)
      {
        case "hdleSensorDlgShowAll":
          sensorsObj.showAll(currentPageNr);
          break;
        case "hdleSensorDlgHideAll":
          sensorsObj.hideAll();
          break;
        case "hdleSensorDlgShowCritical":
          sensorsObj.showCritical(currentPageNr);
          break;
        case "hdleSensorDlgResetVis":
          sensorsObj.restoreVisibility(currentPageNr);
          break;
      }
      sensorsObj.updatePositions(myCmiWindow);
      hdlSnsDlg.onSelectionChange();
    };//hdlSnsDlg.applyAction

    hdlSnsDlg.initialize = function()
    {
      let sensors = poi3dConnector.getLeftDocument().getSensors();
      let sensorSelection = document.getElementById("hdlSnsDlg_Sel");
      sensorSelection.options.length = 0;

      for ( let i =0; i< sensors.length; i++)
      {
        let option = document.createElement("option");
        option.text = sensors[i].getTitle();
        sensorSelection.add(option);

        if(i==0)
        {
          let currentSensor = sensors[i];

          if(currentSensor.getPageRef() != currentPageNr)
          {
            currentPageNr=currentSensor.getPageRef();
            openCurrentMultipageImage();
          }

          if(currentSensor.getViewPosition().length==0)
            Poi3dHelpers.canBeUsed("hdlSnsDlg_BeamBut",false);
          else
            Poi3dHelpers.canBeUsed("hdlSnsDlg_BeamBut",true);
        }
      }//for ( let i =0; i< sensors.length; i++)

      if(viewingMode == "2d")
      {
        Poi3dHelpers.canBeUsed("hdlSnsDlg_AnimBut",false);
        Poi3dHelpers.canBeUsed("hdlSnsDlg_SelBut",false);
      }
      else
      {
        Poi3dHelpers.canBeUsed("hdlSnsDlg_AnimBut",true);
        Poi3dHelpers.canBeUsed("hdlSnsDlg_SelBut",true);
      }

      if(sensors.length > 0)
        hdlSnsDlg.onSelectionChange();
    };//hdlSnsDlg.initialize
  };//if (!hdlSnsDlg)

  hdlSnsDlg.initialize();
  hdlSnsDlg.showDialog(parentDlg);

  function hdlSnsDlgCbk(btnName)
  {
    let sensors = poi3dConnector.getLeftDocument().getSensors();

    switch(btnName)
    {
      case "hsShowAll":
        hdlSnsDlg.dialog.style.display = 'block';
        for(let i=0; i<sensors.length; i++)
          sensors[i].setUiVisible(true,false);
        break;
      case "hsHideAll":
        hdlSnsDlg.dialog.style.display = 'block';
        for(let i=0; i<sensors.length; i++)
          sensors[i].setUiVisible(false,false);
        break;
      case "hsClose":
        break;
    }//switch(btnName)
  }//function hdlSnsDlgCbk(btnName)
}//function showHdlSnsDlg()

function showDefBomDlg(parentDlg)
{
  if (!defBomDlg)
  {
    defBomDlg = new DialogBox('defBomDlg', defBomDlgCbk, cmiCanvas);
    defBomDlg.currentBom = null;
    defBomDlg.bomSelection = document.getElementById("defBomDlg_Sel");

    defBomDlg.renameActive  = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();

      if(bomStructures.length >0)
      {
        defBomDlg.currentBom = bomStructures[defBomDlg.bomSelection.selectedIndex];
        var bomName = document.getElementById("defBomDlg_NameVal").value;
        if(bomName.length > 0)
        {
          var foundBom = bomStructures.find(item => item.getTitle() === bomName);
          if(foundBom == null)
          {
            defBomDlg.currentBom.setTitle(bomName);
            defBomDlg.bomSelection[defBomDlg.bomSelection.selectedIndex].text = bomName;
          }
        }
        poi3dConnector.getLeftDocument().getBomStructureObject().setLocalChangeFlag(true);
      }
    };//defBomDlg.renameActive

    defBomDlg.deleteCurrent  = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();
      if(bomStructures.length == 0) return;

      defBomDlg.currentBom = bomStructures[defBomDlg.bomSelection.selectedIndex];

      for (var i=0; i<bomStructures.length; i++)
      {
        if(bomStructures[i].getTitle() == defBomDlg.currentBom.getTitle())
        {
          bomStructures = bomStructures.filter(function(item) {return item !== bomStructures[i]});
          i = bomStructures.length;
        }
      };

      if(bomStructures.length == 0)
      {
        defBomDlg.bomSelection.options.length = 0;
        document.getElementById("defBomDlg_NameVal").value = "";
      }
      else
      {
        defBomDlg.bomSelection.options.length = 0;
        for ( var i =0; i< bomStructures.length; i++)
        {
          var option = document.createElement("option");
          option.text = bomStructures[i].getTitle();
          defBomDlg.bomSelection.add(option);

          if(i==0)
          {
            defBomDlg.currentBom = bomStructures[0];
            document.getElementById("defBomDlg_NameVal").value = defBomDlg.currentBom.getTitle();
          }
        };//for ( var i =0; i< bomStructures.length; i++)
      }//if(bomStructures.length == 0) else

      if(propDlg != null) propDlg.dialog.style.display = 'none';
      poi3dConnector.getLeftDocument().setBomStructures(bomStructures);
      leftBomBrowser.clearContent();
      updateBomBrowserSelection();
      resizeWindow(false);
    };//defBomDlg.deleteCurrent

    defBomDlg.showCurrent  = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();
      if(bomStructures.length == 0) return;

      defBomDlg.currentBom = bomStructures[defBomDlg.bomSelection.selectedIndex];

      leftBomBrowser.saveTableLayout();
      leftBomBrowser.buildProductStructureTree(defBomDlg.currentBom);
      leftBomBrowser.restoreTableLayout();
      leftBomBrowser.rebuildTreeViewTable();

      let bomBrowserSelection = document.getElementById("lbrBomSel");
      bomBrowserSelection.selectedIndex = defBomDlg.bomSelection.selectedIndex+1;

      leftAssemblyBrowser.switchHighlightStateForAll(false);
      leftBomBrowser.switchHighlightStateForAll(false);
      switchToLeftBrowser(true);
      switchBrowserView('bom');
      myCmiWindow.drawScene();
    };//defBomDlg.showCurrent

    defBomDlg.showAttribs  = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();
      if(bomStructures.length == 0) return;

      defBomDlg.currentBom = bomStructures[defBomDlg.bomSelection.selectedIndex];

      let psLinks = defBomDlg.currentBom.getLinkageArray(false,true,true);
      showPropDlg(defBomDlg,psLinks,"bom",defBomDlg.currentBom);
    };

    defBomDlg.createNew  = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();
      var bomName = document.getElementById("defBomDlg_NameVal").value;

      if(bomName.length == 0)
      {
        bomName="bom"+(bomStructures.length+1).toString()+"_"+Date.now().toString(36);
        document.getElementById("defBomDlg_NameVal").value = bomName;
      }
      else
      {
        var foundBom = bomStructures.find(item => item.getTitle() === bomName);
        if(foundBom != null)
        {
          bomName="bom"+(bomStructures.length+1).toString()+"_"+Date.now().toString(36);
          document.getElementById("defBomDlg_NameVal").value = bomName;
        }
      }

      var bomStruct = new CmiProductStructure();
      bomStruct.setTitle(bomName);
      bomStruct.defineFromWpmModel(leftModel);

      bomStructures.push(bomStruct);
      poi3dConnector.getLeftDocument().getBomStructureObject().setLocalChangeFlag(true);

      defBomDlg.currentBom=bomStruct;

      var option = document.createElement("option");
      option.text = bomStruct.getTitle();
      defBomDlg.bomSelection.add(option);
      defBomDlg.bomSelection.selectedIndex = bomStructures.length-1;

      updateBomBrowserSelection();
    };//defBomDlg.createNew

    defBomDlg.sendBom  = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();

      if(bomStructures.length > 0)
      {
        defBomDlg.currentBom = bomStructures[defBomDlg.bomSelection.selectedIndex];
        var tgtSelection = document.getElementById("defBomDlg_TgtSel");
        var expFlags = new CmiJsonBomExportFlags();
        var tgt = tgtSelection[tgtSelection.selectedIndex].value;

        expFlags.createModelReferences = false;
        expFlags.useModFlags = true;

        switch(tgt)
        {
          case "bomTgtConsoleFull":
            expFlags.skipWrittenSubstructures = false;
            expFlags.writeNodes = true;
            expFlags.writeNodeAttributesInStructure = false;
            expFlags.combinePosNrs = false;
            console.clear();
            console.log(defBomDlg.currentBom.getObjectAsJsonString(expFlags));
            break;
          case "bomTgtConsoleRed":
            expFlags.skipWrittenSubstructures = true;
            expFlags.writeNodes = true;
            expFlags.writeNodeAttributesInStructure = false;
            expFlags.combinePosNrs = false;
            console.clear();
            console.log(defBomDlg.currentBom.getObjectAsJsonString(expFlags));
            break;
          case "bomTgtHtmlFull":
          case "bomTgtPdfFull":
            expFlags.skipWrittenSubstructures = false;
            expFlags.writeNodes = false;
            expFlags.writeNodeAttributesInStructure = true;
            expFlags.combinePosNrs = true;
            poi3dConnector.sendBom(tgt,defBomDlg.currentBom.getObjectAsJsonString(expFlags));
            break;
          case "bomTgtHtmlRed":
          case "bomTgtPdfRed":
            expFlags.skipWrittenSubstructures = true;
            expFlags.writeNodes = false;
            expFlags.writeNodeAttributesInStructure = true;
            expFlags.combinePosNrs = true;
            poi3dConnector.sendBom(tgt,defBomDlg.currentBom.getObjectAsJsonString(expFlags));
            break;
          case "bomTgtAzure":
            if(poi3dConnector.getPoi3dUser().isLoggedIn() == false)
            {
              showMsgDlg(defBomDlg,poi3dConnector.getMessage(3));
              return;
            }
            expFlags.skipWrittenSubstructures = true;
            expFlags.writeNodes = true;
            expFlags.writeNodeAttributesInStructure = false;
            expFlags.combinePosNrs = false;
            poi3dConnector.sendBom(tgt,defBomDlg.currentBom.getObjectAsJsonString(expFlags));
            break;
        }
      }
    };//defBomDlg.sendBom

    defBomDlg.readBom  = function()
    {
    };//defBomDlg.readBom

    defBomDlg.onSelectionChange = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();
      defBomDlg.currentBom = bomStructures[defBomDlg.bomSelection.selectedIndex];
      document.getElementById("defBomDlg_NameVal").value = defBomDlg.currentBom.getTitle();
    };//defBomDlg.onSelectionChange

    defBomDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      switch(currentStatus)
      {
        case "sendBomInProgress":
          if(textToDisplay.length > 0)
          {
            document.getElementById("defBomDlg_TransStateVal").innerHTML = textToDisplay;
          }
          break;
        case "sendBomError":
        case "sendBomSuccess":
          if(textToDisplay.length > 0)
          {
            document.getElementById("defBomDlg_TransStateVal").innerHTML = textToDisplay;
            showMsgDlg(defBomDlg,"Remote info:" + textToDisplay);
          }
          break;
      }
    };//defBomDlg.onStatusUpdate

    defBomDlg.initialize = function()
    {
      let bomStructures = poi3dConnector.getLeftDocument().getBomStructures();
      defBomDlg.bomSelection.options.length = 0;

      document.getElementById("defBomDlg_NameVal").value = "";
      for ( var i =0; i< bomStructures.length; i++)
      {
        var option = document.createElement("option");
        option.text = bomStructures[i].getTitle();
        defBomDlg.bomSelection.add(option);

        if(i==0)
        {
          defBomDlg.currentBom = bomStructures[0];
          document.getElementById("defBomDlg_NameVal").value = defBomDlg.currentBom.getTitle();
        }
      }
    };//defBomDlg.initialize

    poi3dConnector.registerCallback("bomStatusUpdate",defBomDlg.onStatusUpdate);
  }//if (!defBomDlg)

  defBomDlg.initialize();
  defBomDlg.showDialog(parentDlg);

  function defBomDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "bomCancel":
      case "close":
        break;
    }//switch(btnName)
  };//function defBomDlgCbk
}//function showDefBomDlg()

function showHdlInstrDlg(parentDlg)
{
  if (!hdlInstrDlg)
  {
    hdlInstrDlg = new DialogBox('hdlInstrDlg', hdlInstrDlgCbk, cmiCanvas);

    hdlInstrDlg.onSelectionChange = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();
      let instructionSelection = document.getElementById("hdlInstrDlg_Sel");
      let currentInstruction = instructions[instructionSelection.selectedIndex];

      document.getElementById("hdlInstrDlg_TxtInp").innerHTML = currentInstruction.advice;

      if(currentInstruction.viewPosition.length==0)
        Poi3dHelpers.canBeUsed("hdlInstrDlg_BeamBut",false);
      else
        Poi3dHelpers.canBeUsed("hdlInstrDlg_BeamBut",true);
    };//hdlInstrDlg.onSelectionChange

    hdlInstrDlg.initialize = function()
    {
      let instructions = poi3dConnector.getLeftDocument().getInstructions();
      let instructionSelection = document.getElementById("hdlInstrDlg_Sel");
      instructionSelection.options.length = 0;
      document.getElementById("hdlInstrDlg_TxtInp").innerHTML = "";

      for ( var i =0; i< instructions.length; i++)
      {
        var option = document.createElement("option");
        option.text = instructions[i].title;
        instructionSelection.add(option);

        if(i==0)
        {
          var currentInstruction = instructions[i];
          document.getElementById("hdlInstrDlg_TxtInp").innerHTML = currentInstruction.advice;
          if(currentInstruction.viewPosition.length==0)
            Poi3dHelpers.canBeUsed("hdlInstrDlg_BeamBut",false);
          else
            Poi3dHelpers.canBeUsed("hdlInstrDlg_BeamBut",true);
        }
      }
    };//hdlInstrDlg.initialize
  };//if (!hdlInstrDlg)

  hdlInstrDlg.initialize();
  hdlInstrDlg.showDialog(parentDlg);

  function hdlInstrDlgCbk(btnName)
  {
    let instructionSelection = document.getElementById("hdlInstrDlg_Sel");
    let currentInstruction = null;
    let instructions = poi3dConnector.getLeftDocument().getInstructions();

    if(instructions.length >0)
    {
      currentInstruction = instructions[instructionSelection.selectedIndex];
      document.getElementById("hdlInstrDlg_TxtInp").innerHTML = currentInstruction.advice;
    }

    switch(btnName)
    {
      case "hiBeam":
        hdlInstrDlg.dialog.style.display = 'block';

        if(instructionSelection.length == 0) break;
        if(currentInstruction.viewPosition.length==0) break;

        if(viewingMode.includes("VR")==false)
        {
          var vrCheckbox = document.getElementById("gVrMode");
          vrCheckbox.checked = true;
          switchToVrMode(vrCheckbox);
        }
        if(viewingMode != "VR+")
        {
          var pinIcon = document.getElementById("gPinModel");
          pinIcon.checked = true;
          pinModelToEnv(pinIcon);
        }

        myCmiWindow.moveViewerToModelPosition(currentInstruction.viewPosition[0],currentInstruction.viewPosition[1],currentInstruction.viewPosition[2]);
        myCmiWindow.rotateViewerToModelAngles(currentInstruction.viewAngles[0],currentInstruction.viewAngles[1],currentInstruction.viewAngles[2]);
        myCmiWindow.drawScene();
        break;
      case "hiShow":
        hdlInstrDlg.dialog.style.display = 'block';
        if(instructionSelection.length == 0) break;

        var components = currentInstruction.getEntities();
        runShowComponentAnimation(components,instructionAnimation,"instructionAnimation",currentInstruction.blinkCount,currentInstruction.blinkColor,currentInstruction.blinkPause);

        break;
      case "hiSelect":
        hdlInstrDlg.dialog.style.display = 'block';
        if(instructionSelection.length == 0) break;

        var components = currentInstruction.getEntities();
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        leftBomBrowser.switchHighlightStateForAll(false);

        leftAssemblyBrowser.highlightComponents(components);
        leftBomBrowser.highlightComponents(components);

        leftAssemblyBrowser.expandComponentBranch(components);
        leftBomBrowser.expandComponentBranch(components);
        myCmiWindow.drawScene();

        break;
      case "hiClose":
        break;
    }//switch(btnName)
  }//function hdlInstrDlgCbk(btnName)
}//function showHdlInstrDlg()

function showInfoPntDlg(parentDlg,objectToHandle)
{
  if (!infoPntDlg)
  {
    infoPntDlg = new DialogBox('infoPntDlg', infoPntDlgCbk, cmiCanvas);
  }
  infoPntDlg.selectedEntity = objectToHandle;
  infoPntDlg.showDialog(parentDlg);

  function infoPntDlgCbk(btnName)
  {
    var annotations = poi3dConnector.getLeftDocument().getAnnotations();

    var layerName = document.getElementById("infoPntDlg_LayVal").value;
    var toolTip  = document.getElementById("infoPntDlg_TlTipVal").value;
    var hrefValue = document.getElementById("infoPntDlg_HrefVal").value;

    if (btnName == 'repos')
    {
      if(pickPoints.length > 0)
      {
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      switchMouseMode("pick");
      if(infoPntDlg.selectedEntity != null)
        interactionMode = "ipPickEdit";
      else
        interactionMode = "ipPick";

      handleSelectionSettings();
      setStatusText(poi3dConnector.getStatusText(2));//"select position"

      return;
    }
    else if (btnName == 'ok')
    {
      if(toolTip.length == 0) toolTip=" "; //to be selectable

      var annotation = null;

      if(infoPntDlg.selectedEntity != null)
      {
        annotation = infoPntDlg.selectedEntity;
      }
      else
      {
        annotation = new CmiSpriteObject(myCmiWindow);
        annotation.entityName = "ann"+(annotations.length+1).toString()+"_"+Date.now().toString(36);;
        annotation.setTexture("./Poi3d/Images/Info.png");
        annotation.setPixelOffset([0,18]);
        annotation.setPointSize(30);
        annotation.fromPoi3d = true;
        annotation.setPropertyValue("annTyp","infoPnt")
      }

      annotation.setLayer(layerName);
      annotation.setSelectionInfo(toolTip);
      annotation.setUrlInfo(hrefValue);
      annotation.setPropertyValue("pageRef",currentPageNr)

      if(pickPoints.length > 0)
      {
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let globalOrigin1=loc1.getGlobalOrigin();
        annotation.setOrigin(globalOrigin1);
      }

      if(infoPntDlg.selectedEntity != null)
      {
        let foundIndex = annotations.findIndex((ent) => ent.eNm === infoPntDlg.selectedEntity.entityName);
        if(foundIndex != -1 ) annotations[foundIndex] = infoPntDlg.selectedEntity.getJsonObject();
      }
      else
      {
        leftModel.addAnnotationToModel(annotation,layerName,toolTip,hrefValue,true);
        var jObj = annotation.getJsonObject();
        jObj.fromPoi3d = true;
        annotations.push(jObj);
      }

      layerBrowser.buildLayerList(leftModel,true,0);
      layerBrowser.rebuildLayerViewTable();
      resizeWindow(false);
      if(viewingMode == "2d")
      {
        openCurrentMultipageImage();
        updatePageBrowser();
      }

      poi3dConnector.getLeftDocument().getAnnotationObject().setLocalChangeFlag(true);
    }//if (btnName == 'ok')

    if(viewingMode == "VR+")
      switchMouseMode("zoom");
    else
      switchMouseMode("rotate");

    interactionMode = "";
    handleSelectionSettings();
    if(pickPoints.length > 0)
    {
      leftModel.removeLocatorsFromModelByNames(pickPoints);
      pickPoints = new Array();
    }
  }
}//function showInfoPntDlg()

function showAreaAnnDlg(parentDlg,context,objectToHandle)
{
  if (!areaAnnDlg)
    areaAnnDlg = new DialogBox('areaAnnDlg', areaAnnDlgCbk, cmiCanvas);

  areaAnnDlg.context = context;
  areaAnnDlg.selectedEntity = objectToHandle;

  areaAnnDlg.showDialog(parentDlg);

  function areaAnnDlgCbk(btnName)
  {
    var annotations = poi3dConnector.getLeftDocument().getAnnotations();

    var layerName = document.getElementById("areaAnnDlg_LayVal").value;
    var toolTip  = document.getElementById("areaAnnDlg_TlTipVal").value;
    var colorVal = document.getElementById("areaAnnDlg_ColVal").value;
    var oglColor = Poi3dHelpers.hexToOgl(colorVal);

    if (btnName == 'repos')
    {
      if(pickPoints.length > 0)
      {
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      switchMouseMode("pick");
      switch(areaAnnDlg.context)
      {
        case "area":
          if(areaAnnDlg.selectedEntity != null)
            interactionMode = "areaPickEdit";
          else
            interactionMode = "areaPick";
          setStatusText(poi3dConnector.getStatusText(3));//"select first position"
          break;
        case "plate":
          if(areaAnnDlg.selectedEntity != null)
            interactionMode = "platePickEdit";
          else
            interactionMode = "platePick";
          setStatusText(poi3dConnector.getStatusText(8));//"select center point"
          break;
        case "sphere":
          if(areaAnnDlg.selectedEntity != null)
            interactionMode = "spherePickEdit";
          else
            interactionMode = "spherePick";
          setStatusText(poi3dConnector.getStatusText(8));//"select center point"
          break;
        case "circle":
          if(areaAnnDlg.selectedEntity != null)
            interactionMode = "crcPickEdit";
          else
            interactionMode = "crcPick";
          setStatusText(poi3dConnector.getStatusText(8));//"select center point"
          break;
      }
      handleSelectionSettings();

      return;
    }
    else if (btnName == 'ok')
    {
      if(toolTip.length == 0) toolTip=" "; //to be selectable

      var annotation = null;

      if(areaAnnDlg.selectedEntity != null)
      {
        annotation = areaAnnDlg.selectedEntity;
      }
      else
      {
        switch(areaAnnDlg.context)
        {
          case "area":
          case "plate":
          case "sphere":
            annotation = new CmiGrepObject(myCmiWindow);
            break;
          case "circle":
            annotation = new CmiArcObject(myCmiWindow);
            break;
        }
        annotation.entityName = "ann"+(annotations.length+1).toString()+"_"+Date.now().toString(36);
        annotation.fromPoi3d = true;
        annotation.setPropertyValue("annTyp",areaAnnDlg.context);
      }

      if(pickPoints.length > 0)
      {
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let loc2 = leftModel.getEntityByName(pickPoints[1]);
        let globalOrigin1=loc1.getGlobalOrigin();
        let globalOrigin2=loc2.getGlobalOrigin();

        let dX =   Math.abs(globalOrigin1[0]-globalOrigin2[0]);
        let dY =   Math.abs(globalOrigin1[1]-globalOrigin2[1]);
        let dZ =   Math.abs(globalOrigin1[2]-globalOrigin2[2]);
        let dist = Math.sqrt((dX * dX) + (dY * dY) + (dZ * dZ));

        let minX = Math.min(globalOrigin1[0],globalOrigin2[0]);
        let minY = Math.min(globalOrigin1[1],globalOrigin2[1]);
        let maxX = Math.max(globalOrigin1[0],globalOrigin2[0]);
        let maxY = Math.max(globalOrigin1[1],globalOrigin2[1]);

        let cmi3dGeometry = new Cmi3dGeometry();
        let outerContour = new Cmi2dContour();

        switch(areaAnnDlg.context)
        {
          case "area":
            outerContour.addPoint(minX,minY);
            outerContour.addPoint(maxX,minY);
            outerContour.addPoint(maxX,maxY);
            outerContour.addPoint(minX,maxY);
            cmi3dGeometry.defineAsBoundedPlane(outerContour);
            annotation.defineFrom3dGeometry(cmi3dGeometry,annotation.entityName);
            break;
          case "plate":
            outerContour.addArcCpSaEa([globalOrigin1[0],globalOrigin1[1],0.0],dist,0.0,359.0,"ccw");
            cmi3dGeometry.defineAsBoundedPlane(outerContour);
            annotation.defineFrom3dGeometry(cmi3dGeometry,annotation.entityName);
            break;
          case "sphere":
            {
              let tempMatrix = new mat4.createIdent();
              let invMatrix = new mat4.createIdent();
              let eulerAngles = myCmiWindow.getCurrentInvModelViewAngles();

              mat4.AddXRotation(tempMatrix,eulerAngles[0] * Math.PI / 180.0);
              mat4.AddYRotation(tempMatrix,eulerAngles[1] * Math.PI / 180.0);
              mat4.AddZRotation(tempMatrix,eulerAngles[2] * Math.PI / 180.0);
              mat4.inverse(tempMatrix,invMatrix);

              let pPoint1 = CmiHelpers.projectPointToCs(globalOrigin1,invMatrix);
              let pPoint2 = CmiHelpers.projectPointToCs(globalOrigin2,invMatrix);
              pPoint2[2]=pPoint1[2];
              pPoint2 = CmiHelpers.projectPointToCs(pPoint2,tempMatrix);

              dX =   Math.abs(globalOrigin1[0]-pPoint2[0]);
              dY =   Math.abs(globalOrigin1[1]-pPoint2[1]);
              dZ =   Math.abs(globalOrigin1[2]-pPoint2[2]);
              dist = Math.sqrt((dX * dX) + (dY * dY) + (dZ * dZ));

              cmi3dGeometry.defineAsSphere(dist);
              cmi3dGeometry.translate(globalOrigin1[0],globalOrigin1[1],globalOrigin1[2]);
              annotation.defineFrom3dGeometry(cmi3dGeometry,annotation.entityName);
            }
            break;
          case "circle":
            annotation.setOrientation(myCmiWindow.getCurrentInvModelViewAngles());
            annotation.setCenterPoint(globalOrigin1);
            annotation.setRadius(dist);
            annotation.buildArc();
            break;
        }//switch(areaAnnDlg.context)
      }//if(pickPoints.length > 0)

      annotation.setLayer(layerName);
      annotation.setSelectionInfo(toolTip);
      if(annotation.cmiType == 2)
        annotation.setColor([oglColor.r,oglColor.g,oglColor.b,1.0]);
      else
        annotation.setColor([oglColor.r,oglColor.g,oglColor.b,0.5]);

      annotation.setPropertyValue("pageRef",currentPageNr)

      if(areaAnnDlg.selectedEntity != null)
      {
        let foundIndex = annotations.findIndex((ent) => ent.eNm === areaAnnDlg.selectedEntity.entityName);
        if(foundIndex != -1 ) annotations[foundIndex] = areaAnnDlg.selectedEntity.getJsonObject();
      }
      else
      {
        leftModel.addGeoEntityToModel(annotation,layerName,toolTip,"",true);
        var jObj = annotation.getJsonObject();
        jObj.fromPoi3d = true;
        annotations.push(jObj);
      }

      layerBrowser.buildLayerList(leftModel,true,0);
      layerBrowser.rebuildLayerViewTable();
      resizeWindow(false);
      if(viewingMode == "2d")
      {
        openCurrentMultipageImage();
        updatePageBrowser();
      }

      poi3dConnector.getLeftDocument().getAnnotationObject().setLocalChangeFlag(true);
    }//if (btnName == 'ok')

    if(viewingMode == "VR+")
      switchMouseMode("zoom");
    else
      switchMouseMode("rotate");

    interactionMode = "";
    handleSelectionSettings();
    if(pickPoints.length > 0)
    {
      leftModel.removeLocatorsFromModelByNames(pickPoints);
      pickPoints = new Array();
    }
  }//function areaAnnDlgCbk(btnName)
}//function showAreaAnnDlg()

function showTxtAnnDlg(parentDlg,objectToHandle)
{
  if (!txtAnnDlg)
  {
    txtAnnDlg = new DialogBox('txtAnnDlg', txtAnnDlgCbk, cmiCanvas);

    txtAnnDlg.calcHeightVal = function()
    {
      if(pickPoints.length > 0)
      {
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let loc2 = leftModel.getEntityByName(pickPoints[1]);
        let globalOrigin1=loc1.getGlobalOrigin();
        let globalOrigin2=loc2.getGlobalOrigin();
        let initialHeight = CmiHelpers.calculateProjectedDistance(globalOrigin1,globalOrigin2,myCmiWindow.getCurrentInvModelViewAngles())*0.2;
        document.getElementById("txtAnnDlg_HeightVal").value = (initialHeight).toFixed(3);
      }
    }

    txtAnnDlg.onSwitchBgCol = function(cbObject)
    {
      if(cbObject.checked) Poi3dHelpers.setDisplayStyle("#txtAnnDlg_BgColVal","");
      else Poi3dHelpers.setDisplayStyle("#txtAnnDlg_BgColVal","none");
    };
    
    txtAnnDlg.calcHeightVal();
  }

  txtAnnDlg.selectedEntity = objectToHandle;
  txtAnnDlg.onSwitchBgCol(document.getElementById("txtAnnDlg_hasBgColVal"));

  txtAnnDlg.showDialog(parentDlg);

  function txtAnnDlgCbk(btnName)
  {
    var annotations = poi3dConnector.getLeftDocument().getAnnotations();

    var layerName = document.getElementById("txtAnnDlg_LayVal").value;
    var toolTip  = document.getElementById("txtAnnDlg_TlTipVal").value;
    var textValue = document.getElementById("txtAnnDlg_TextVal").value;
    var colorVal = document.getElementById("txtAnnDlg_ColVal").value;
    var oglColor = Poi3dHelpers.hexToOgl(colorVal);
    var bgColorVal = document.getElementById("txtAnnDlg_BgColVal").value;
    var bgOglColor = Poi3dHelpers.hexToOgl(bgColorVal);
    var hasBgCol = document.getElementById("txtAnnDlg_hasBgColVal").checked;
    var heightValue = parseFloat(document.getElementById("txtAnnDlg_HeightVal").value);

    if (btnName == 'repos')
    {
      if(pickPoints.length > 0)
      {
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      switchMouseMode("pick");
      if(txtAnnDlg.selectedEntity != null)
        interactionMode = "taPickEdit";
      else
        interactionMode = "taPick";

      handleSelectionSettings();
      setStatusText(poi3dConnector.getStatusText(3));//"select first position"

      return;
    }
    else if (btnName == 'ok')
    {
      if(toolTip.length == 0) toolTip=" "; //to be selectable
      if(textValue.length == 0) textValue=" ";

      var annotation = null;

      if(txtAnnDlg.selectedEntity != null)
      {
        annotation = txtAnnDlg.selectedEntity;
      }
      else
      {
        annotation = new CmiLabelObject(myCmiWindow);
        annotation.entityName = "ann"+(annotations.length+1).toString()+"_"+Date.now().toString(36);
        annotation.setFontName("Segoe UI");
        annotation.setTextWidth(1.0);
        annotation.setBorderStyle(3);
        annotation.setAutoSizeWidth(true);
        annotation.fromPoi3d = true;
        annotation.setPropertyValue("annTyp","txtLab");
      }

      annotation.setTextheight(heightValue);
      annotation.setArrowSize(heightValue*0.6);
      annotation.setLayer(layerName);
      annotation.setColor([oglColor.r,oglColor.g,oglColor.b,1.0]);

      if(hasBgCol)
        annotation.setBgColor([bgOglColor.r,bgOglColor.g,bgOglColor.b,1.0]);
      else
        annotation.setBgColor([1.0,1.0,1.0,0.0]);

      annotation.setText(textValue);
      annotation.setSelectionInfo(toolTip);
      annotation.setPropertyValue("pageRef",currentPageNr)

      if(pickPoints.length > 0)
      {
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let loc2 = leftModel.getEntityByName(pickPoints[1]);
        let globalOrigin1=loc1.getGlobalOrigin();
        let globalOrigin2=loc2.getGlobalOrigin();

        annotation.setOrientation(myCmiWindow.getCurrentInvModelViewAngles());
        annotation.setLineStartPoint(globalOrigin1);
        annotation.setLineEndPoint(globalOrigin2,true);
        annotation.setTextPoint(globalOrigin2,true);
      }
      annotation.buildLabel(false);

      if(txtAnnDlg.selectedEntity != null)
      {
        let foundIndex = annotations.findIndex((ent) => ent.eNm === txtAnnDlg.selectedEntity.entityName);
        if(foundIndex != -1 ) annotations[foundIndex] = txtAnnDlg.selectedEntity.getJsonObject();
      }
      else
      {
        leftModel.addAnnotationToModel(annotation,layerName,toolTip,"",true);
        var jObj = annotation.getJsonObject();
        jObj.fromPoi3d = true;
        annotations.push(jObj);
      }

      layerBrowser.buildLayerList(leftModel,true,0);
      layerBrowser.rebuildLayerViewTable();
      resizeWindow(false);
      if(viewingMode == "2d")
      {
        openCurrentMultipageImage();
        updatePageBrowser();
      }

      poi3dConnector.getLeftDocument().getAnnotationObject().setLocalChangeFlag(true);
    }//if (btnName == 'ok')

    if(viewingMode == "VR+")
      switchMouseMode("zoom");
    else
      switchMouseMode("rotate");

    interactionMode = "";
    handleSelectionSettings();
    if(pickPoints.length > 0)
    {
      leftModel.removeLocatorsFromModelByNames(pickPoints);
      pickPoints = new Array();
    }

  }//function txtAnnDlgCbk(btnName)
}//function showTxtAnnDlg()

function showLabAnnDlg(parentDlg,objectToHandle)
{
  if (!labAnnDlg)
  {
    labAnnDlg = new DialogBox('labAnnDlg', labAnnDlgCbk, cmiCanvas);

    labAnnDlg.onSwitchBgCol = function(cbObject)
    {
      if(cbObject.checked) Poi3dHelpers.setDisplayStyle("#labAnnDlg_BgColVal","");
      else Poi3dHelpers.setDisplayStyle("#labAnnDlg_BgColVal","none");
    };
  }

  labAnnDlg.selectedEntity = objectToHandle;
  labAnnDlg.onSwitchBgCol(document.getElementById("labAnnDlg_hasBgColVal"));

  labAnnDlg.showDialog(parentDlg);

  function labAnnDlgCbk(btnName)
  {
    var annotations = poi3dConnector.getLeftDocument().getAnnotations();

    var layerName = document.getElementById("labAnnDlg_LayVal").value;
    var toolTip  = document.getElementById("labAnnDlg_TlTipVal").value;
    var textValue = document.getElementById("labAnnDlg_TxtVal").value;
    var colorVal = document.getElementById("labAnnDlg_ColVal").value;
    var oglColor = Poi3dHelpers.hexToOgl(colorVal);
    var bgColorVal = document.getElementById("labAnnDlg_BgColVal").value;
    var bgOglColor = Poi3dHelpers.hexToOgl(bgColorVal);
    var hasBgCol = document.getElementById("labAnnDlg_hasBgColVal").checked;

    if (btnName == 'repos')
    {
      if(pickPoints.length > 0)
      {
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      switchMouseMode("pick");
      if(labAnnDlg.selectedEntity != null)
        interactionMode = "labPickEdit";
      else
        interactionMode = "labPick";

      handleSelectionSettings();
      setStatusText(poi3dConnector.getStatusText(17));//"select lower left point"

      return;
    }
    else if (btnName == 'ok')
    {
      if(toolTip.length == 0) toolTip=" "; //to be selectable
      if (textValue.length == 0) textValue=" ";

      var annotation = null;

      if(labAnnDlg.selectedEntity != null)
      {
        annotation = labAnnDlg.selectedEntity;
      }
      else
      {
        annotation = new CmiTextObject(myCmiWindow);
        annotation.entityName = "ann"+(annotations.length+1).toString()+"_"+Date.now().toString(36);
        annotation.setFontName("Segoe UI");
        annotation.setAutoSizeWidth(true);
        annotation.fromPoi3d = true;
        annotation.setPropertyValue("annTyp","txtLab");
      }

      annotation.setLayer(layerName);
      annotation.setColor([oglColor.r,oglColor.g,oglColor.b,1.0]);

      if(hasBgCol)
        annotation.setBgColor([bgOglColor.r,bgOglColor.g,bgOglColor.b,1.0]);
      else
        annotation.setBgColor([1.0,1.0,1.0,0.0]);

      annotation.setText(textValue);
      annotation.setSelectionInfo(toolTip);
      annotation.setPropertyValue("pageRef",currentPageNr)

      if(pickPoints.length > 0)
      {
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let loc2 = leftModel.getEntityByName(pickPoints[1]);
        let globalOrigin1=loc1.getGlobalOrigin();
        let globalOrigin2=loc2.getGlobalOrigin();
        annotation.calculateTextObject(globalOrigin1,globalOrigin2,myCmiWindow.getCurrentInvModelViewAngles(),0.01);
      }
      else
        annotation.reCalculateTextObject();

      if(labAnnDlg.selectedEntity != null)
      {
        let foundIndex = annotations.findIndex((ent) => ent.eNm === labAnnDlg.selectedEntity.entityName);
        if(foundIndex != -1 ) annotations[foundIndex] = labAnnDlg.selectedEntity.getJsonObject();
      }
      else
      {
        leftModel.addAnnotationToModel(annotation,layerName,toolTip,"",true);
        var jObj = annotation.getJsonObject();
        jObj.fromPoi3d = true;
        annotations.push(jObj);
      }

      layerBrowser.buildLayerList(leftModel,true,0);
      layerBrowser.rebuildLayerViewTable();
      resizeWindow(false);
      if(viewingMode == "2d")
      {
        openCurrentMultipageImage();
        updatePageBrowser();
      }

      poi3dConnector.getLeftDocument().getAnnotationObject().setLocalChangeFlag(true);
    }//if (btnName == 'ok')

    if(viewingMode == "VR+")
      switchMouseMode("zoom");
    else
      switchMouseMode("rotate");

    interactionMode = "";
    handleSelectionSettings();
    if(pickPoints.length > 0)
    {
      leftModel.removeLocatorsFromModelByNames(pickPoints);
      pickPoints = new Array();
    }
  }//function labAnnDlgCbk(btnName)
}//function showLabAnnDlg()

function showImgAnnDlg(parentDlg,objectToHandle)
{
  if (!imgAnnDlg)
  {
    imgAnnDlg = new DialogBox('imgAnnDlg', imgAnnDlgCbk, cmiCanvas);

    imgAnnDlg.calcWidthVal = function()
    {
      if(pickPoints.length > 0)
      {
        let loc1 = leftModel.getEntityByName(pickPoints[0]);
        let loc2 = leftModel.getEntityByName(pickPoints[1]);
        let globalOrigin1=loc1.getGlobalOrigin();
        let globalOrigin2=loc2.getGlobalOrigin();
        let initialWidth = CmiHelpers.calculateProjectedDistance(globalOrigin1,globalOrigin2,myCmiWindow.getCurrentInvModelViewAngles())*0.6;
        document.getElementById("imgAnnDlg_WidthVal").value = (initialWidth).toFixed(3);
      }
    }

    imgAnnDlg.onImgSelected = function()
    {
      if(imgOpenDlg.isImageSelected == true)
        document.getElementById("imgAnnDlg_ImgVal").src = imgOpenDlg.imageElement.src;
      else
        document.getElementById('imgAnnDlg_ImgVal').src = "./CmiBitmaps/GenericTexture.jpg";
    }

    imgAnnDlg.calcWidthVal();
  }

  imgAnnDlg.selectedEntity = objectToHandle;

  imgAnnDlg.showDialog(parentDlg);

  function imgAnnDlgCbk(btnName)
  {
    var annotations = poi3dConnector.getLeftDocument().getAnnotations();

    var layerName = document.getElementById("imgAnnDlg_LayVal").value;
    var toolTip  = document.getElementById("imgAnnDlg_TlTipVal").value;
    var imageObject = document.getElementById("imgAnnDlg_ImgVal");
    var widthValue = parseFloat(document.getElementById("imgAnnDlg_WidthVal").value);
    var colorVal = document.getElementById("imgAnnDlg_ColVal").value;
    var oglColor = Poi3dHelpers.hexToOgl(colorVal);

    if (btnName == 'repos')
    {
      if(pickPoints.length > 0)
      {
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      switchMouseMode("pick");
      if(imgAnnDlg.selectedEntity != null)
        interactionMode = "tiPickEdit";
      else
        interactionMode = "tiPick";

      handleSelectionSettings();
      setStatusText(poi3dConnector.getStatusText(3));//"select first position"

      return;
    }
    else if (btnName == 'ok')
    {
      if(toolTip.length == 0) toolTip=" "; //to be selectable

      var img = new Image;
      img.onload = function ()
      {
        var annotation = null;
        var aspect = this.naturalWidth/this.naturalHeight;

        if(imgAnnDlg.selectedEntity != null)
        {
          annotation = imgAnnDlg.selectedEntity;
        }
        else
        {
          var annotation = new CmiImageLabelObject(myCmiWindow);
          annotation.entityName = "ann"+(annotations.length+1).toString()+"_"+Date.now().toString(36);
          annotation.setBorderStyle(3);
          annotation.fromPoi3d = true;
          annotation.setPropertyValue("annTyp","imgLab");
        }

        annotation.setLayer(layerName);
        annotation.setColor([oglColor.r,oglColor.g,oglColor.b,1.0]);
        annotation.setSelectionInfo(toolTip);
        annotation.setImageWidth(widthValue);
        annotation.setImageheight(widthValue/aspect);
        annotation.setArrowSize(widthValue/aspect*0.3);
        annotation.setImage(this);
        annotation.setPropertyValue("pageRef",currentPageNr)

        if(pickPoints.length > 0)
        {
          let loc1 = leftModel.getEntityByName(pickPoints[0]);
          let loc2 = leftModel.getEntityByName(pickPoints[1]);
          let globalOrigin1=loc1.getGlobalOrigin();
          let globalOrigin2=loc2.getGlobalOrigin();

          annotation.setOrientation(myCmiWindow.getCurrentInvModelViewAngles());
          annotation.setLineStartPoint(globalOrigin1);
          annotation.setLineEndPoint(globalOrigin2,true);
          annotation.setImagePoint(globalOrigin2,true);
        }
        annotation.buildLabel(false);

        if(imgAnnDlg.selectedEntity != null)
        {
          let foundIndex = annotations.findIndex((ent) => ent.eNm === imgAnnDlg.selectedEntity.entityName);
          if(foundIndex != -1 ) annotations[foundIndex] = imgAnnDlg.selectedEntity.getJsonObject();
        }
        else
        {
          leftModel.addAnnotationToModel(annotation,layerName,toolTip,"",true);
          var jObj = annotation.getJsonObject();
          jObj.fromPoi3d = true;
          annotations.push(jObj);
        }

        layerBrowser.buildLayerList(leftModel,true,0);
        layerBrowser.rebuildLayerViewTable();
        resizeWindow(false);
        if(viewingMode == "2d")
        {
          openCurrentMultipageImage();
          updatePageBrowser();
        }

        if(viewingMode == "VR+")
          switchMouseMode("zoom");
        else
          switchMouseMode("rotate");

        interactionMode = "";
        handleSelectionSettings();
        if(pickPoints.length > 0)
        {
          leftModel.removeLocatorsFromModelByNames(pickPoints);
          pickPoints = new Array();
        }

      }//img.onload = function ()
      img.src = imageObject.src;
    }//else if (btnName == 'ok')
    else
    {
      if(viewingMode == "VR+")
        switchMouseMode("zoom");
      else
        switchMouseMode("rotate");

      interactionMode = "";
      handleSelectionSettings();
      if(pickPoints.length > 0)
      {
        leftModel.removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }
    }
  }//function imgAnnDlgCbk(btnName)
}//function showImgAnnDlg()

function selectMobileImage(inputObject,imageElementName,maxSize)
{
  document.getElementById(imageElementName).src="./CmiBitmaps/GenericTexture.jpg";

  var oFReader = new FileReader();

  oFReader.onload = function (oFREvent)
  {
    var tmpImg = new Image();

    tmpImg.imageElement = this.imageElement;
    tmpImg.maxSize = this.maxSize;

    tmpImg.src = oFREvent.target.result;
    tmpImg.onload = function ()
    {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");

      var MAX_WIDTH = this.maxSize;
      var MAX_HEIGHT = this.maxSize;
      var width = tmpImg.width;
      var height = tmpImg.height;

      if (width > height)
      {
        if (width > MAX_WIDTH)
        {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      }
      else
      {
        if (height > MAX_HEIGHT)
        {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(tmpImg, 0, 0, width, height);

      this.imageElement.src = canvas.toDataURL("image/png");
      //img = document.getElementById("imgAnnDlg_ImgVal");
      //img.src = canvas.toDataURL("image/png");
     }
  };

  if((inputObject.files.length > 0)&&(inputObject.files[0].type.includes("image")))
  {
    oFReader.imageElement = document.getElementById(imageElementName);
    oFReader.maxSize = maxSize;
    oFReader.readAsDataURL(inputObject.files[0]);
  }

  mobFopenDlg.selectedFile = inputObject.files[0];
  document.getElementById("mobFopenDlg_ImgName").innerHTML=mobFopenDlg.selectedFile.name.toLowerCase();
}

function showMobFopenDlg(parentDlg)
{
  if (!mobFopenDlg)
    mobFopenDlg = new DialogBox('mobFopenDlg', mobFopenDlgCbk, cmiCanvas);

  document.getElementById("mobFopenDlg_Img").src="./CmiBitmaps/GenericTexture.jpg";
  document.getElementById("mobFopenDlg_ImgName").innerHTML="";

  mobFopenDlg.selectedFile = null;

  mobFopenDlg.showDialog(parentDlg);

  function mobFopenDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      if(mobFopenDlg.selectedFile != null)
      {
        exifr.parse(mobFopenDlg.selectedFile)
        .then(metadata =>
        {
          Poi3dDocumentLoader.createLeftDocumentFromFileTarget(mobFopenDlg.selectedFile, metadata);      
        })
        .catch(error =>
        {
          Poi3dDocumentLoader.createLeftDocumentFromFileTarget(mobFopenDlg.selectedFile,null);      
        });
        //Poi3dDocumentLoader.createLeftDocumentFromFileTarget(mobFopenDlg.selectedFile);
      }
    }//if (btnName == 'ok')
  }
}//function showMobFopenDlg()

function showImageOpenDlg(parentDlg,maxSize,callback)
{
  if (!imgOpenDlg)
  {
    imgOpenDlg = new DialogBox('imgOpenDlg', imgOpenDlgCbk, cmiCanvas);
    imgOpenDlg.imageElement = document.getElementById("imgOpenDlg_Img");
    imgOpenDlg.isImageSelected = false;
    imgOpenDlg.imageElement.src="./CmiBitmaps/GenericTexture.jpg";
    document.getElementById("imgOpenDlg_ImgName").innerHTML="";

    imgOpenDlg.selectImage = function()
    {
      imgOpenDlg.isImageSelected = false;
      var oFReader = new FileReader();
      var inputObject = document.getElementById("imgOpenDlg_FlInp");

      oFReader.onload = function (oFREvent)
      {
        Poi3dHelpers.shrinkImage(imgOpenDlg.imageElement,oFREvent.target.result,imgOpenDlg.maxSize);
      };

      if(inputObject.files[0].type.includes("image"))
      {
        oFReader.readAsDataURL(inputObject.files[0]);
        document.getElementById("imgOpenDlg_ImgName").innerHTML=inputObject.files[0].name.toLowerCase();
        imgOpenDlg.isImageSelected = true;
      }
    };

    imgOpenDlg.reset = function()
    {
      imgOpenDlg.isImageSelected = false;
      document.getElementById("imgOpenDlg_Img").src="./CmiBitmaps/GenericTexture.jpg";
      document.getElementById("imgOpenDlg_ImgName").innerHTML="";
    };

    imgOpenDlg.takeScreenShot  = function()
    {
      imgOpenDlg.isImageSelected = false;
      document.getElementById("imgOpenDlg_ImgName").innerHTML="";

      var modelImage = myCmiWindow.getImageObjectFromWebGlWindow();  //Gets the webgl content as an image
      modelImage.onload = function ()
      {
        Poi3dHelpers.shrinkImage(imgOpenDlg.imageElement,modelImage.src,imgOpenDlg.maxSize);
        imgOpenDlg.isImageSelected = true;
      }
    };
  }

  imgOpenDlg.callback = callback;
  imgOpenDlg.maxSize = maxSize;

  imgOpenDlg.showDialog(parentDlg);

  function imgOpenDlgCbk(btnName)
  {
    if((btnName == 'ok')&&(imgOpenDlg.callback != null))
    {
      imgOpenDlg.callback();
    }
  }
}//function showImageOpenDlg()

function showClbMsmtDlg(parentDlg)
{
  if (!clbMsmtDlg)
    clbMsmtDlg = new DialogBox('clbMsmtDlg', clbMsmtDlgCbk, cmiCanvas);

  var loc1 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[0]);
  var loc2 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[1]);
  var globalOrigin1=loc1.getGlobalOrigin();
  var globalOrigin2=loc2.getGlobalOrigin();
  var dX =   Math.abs(globalOrigin1[0]-globalOrigin2[0]);
  var dY =   Math.abs(globalOrigin1[1]-globalOrigin2[1]);
  var dZ =   Math.abs(globalOrigin1[2]-globalOrigin2[2]);

  this.realDist = Math.sqrt((dX * dX) + (dY * dY) + (dZ * dZ));
  document.getElementById("clbMsmtDlg_DimIsVal").innerHTML = this.realDist.toFixed(2);

  clbMsmtDlg.showDialog(parentDlg);

  function clbMsmtDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      var dimValue = document.getElementById("clbMsmtDlg_DimSetVal").value;
      measurementScale = parseFloat(dimValue)/this.realDist;
    }//if (btnName == 'ok')


    if(viewingMode == "VR+")
      switchMouseMode("zoom");
    else
      switchMouseMode("rotate");

    interactionMode = "";
    handleSelectionSettings();
    if(pickPoints.length > 0)
    {
      pdmConnector.LeftModel.removeLocatorsFromModelByNames(pickPoints);
      pickPoints = new Array();
    }
  }//function clbMsmtDlgCbk(btnName)
}//function showClbMsmtDlg(aName)

function showPlCutDlg(parentDlg)
{
  if (!plCutDlg)
  {
    plCutDlg = new DialogBox('plCutDlg', plCutDlgCbk, cmiCanvas);

    plCutDlg.PlaneSldrValTxt = document.getElementById("plCutDlg_PlaneSldrValTxt");
    plCutDlg.plCutDlg_PlaneSldrValVal = document.getElementById("plCutDlg_PlaneSldrValVal");
    plCutDlg.percentDist = 0.0;
    plCutDlg.modelCenter = null;
  }

  //init dialog

  var activateButt = document.getElementById("planeCutDlgActivateValue");
  if(myCmiWindow.clipPlaneActive == true)
    activateButt.checked = true;
  else
    activateButt.checked = false;

  var cutDirLeft = document.getElementById("plCutDlg_DirLeft");
  var cutDirRight = document.getElementById("plCutDlg_DirRight");
  var cutDirUp = document.getElementById("plCutDlg_DirUp");
  var cutDirDown = document.getElementById("plCutDlg_DirDwn");
  var cutDirFront = document.getElementById("plCutDlg_DirFront");
  var cutDirBack = document.getElementById("plCutDlg_DirBack");

  switch(currentCutDirection)
  {
    case "Left":
      cutDirLeft.checked=true;cutDirRight.checked=false;cutDirUp.checked=false;cutDirDown.checked=false;cutDirFront.checked=false;cutDirBack.checked=false;
      break;
    case "Right":
      cutDirLeft.checked=false;cutDirRight.checked=true;cutDirUp.checked=false;cutDirDown.checked=false;cutDirFront.checked=false;cutDirBack.checked=false;
      break;
    case "Up":
      cutDirLeft.checked=false;cutDirRight.checked=false;cutDirUp.checked=true;cutDirDown.checked=false;cutDirFront.checked=false;cutDirBack.checked=false;
      break;
    case "Down":
      cutDirLeft.checked=false;cutDirRight.checked=false;cutDirUp.checked=false;cutDirDown.checked=true;cutDirFront.checked=false;cutDirBack.checked=false;
      break;
    case "Front":
      cutDirLeft.checked=false;cutDirRight.checked=false;cutDirUp.checked=false;cutDirDown.checked=false;cutDirFront.checked=true;cutDirBack.checked=false;
      break;
    case "Back":
      cutDirLeft.checked=false;cutDirRight.checked=false;cutDirUp.checked=false;cutDirDown.checked=false;cutDirFront.checked=false;cutDirBack.checked=true;
      break;
  }

  //Dialog Methods
  plCutDlg.initDialogValues = function()
  {
    if(leftModel != null)
    {
      var urp = leftModel.getUpperRightBdryPoint();
      var llp = leftModel.getLowerLeftBdryPoint();
      var distUrp = CmiHelpers.calculate3dDistance(urp,myCmiWindow.clipPlanePoint);
      var distLlp = CmiHelpers.calculate3dDistance(llp,myCmiWindow.clipPlanePoint);
      var totalLength = distUrp+distLlp;
      var sliderVal=(distUrp/totalLength)*100-50;

      plCutDlg.plCutDlg_PlaneSldrValVal.value = sliderVal;
      plCutDlg.PlaneSldrValTxt.innerHTML = Math.floor(plCutDlg.plCutDlg_PlaneSldrValVal.value).toString() + "%";
      plCutDlg.percentDist = totalLength/100.0;
      plCutDlg.modelCenter = leftModel.getModelCenterPoint();
    }
  }

  plCutDlg.onActivateClick = function(activateButt)
  {
    if(activateButt.checked)
      myCmiWindow.clipPlaneActive = true;
    else
      myCmiWindow.clipPlaneActive = false;

    myCmiWindow.drawScene();
  }

  plCutDlg.onPlaneCutDirClick = function(dir)
  {
    currentCutDirection = dir;

    switch(dir)
    {
      case "Left":
        myCmiWindow.clipPlaneDir[0]=1.0;
        myCmiWindow.clipPlaneDir[1]=0.0;
        myCmiWindow.clipPlaneDir[2]=0.0;
        break;
      case "Right":
        myCmiWindow.clipPlaneDir[0]=-1.0;
        myCmiWindow.clipPlaneDir[1]=0.0;
        myCmiWindow.clipPlaneDir[2]=0.0;
        break;
      case "Up":
        myCmiWindow.clipPlaneDir[0]=0.0;
        myCmiWindow.clipPlaneDir[1]=-1.0;
        myCmiWindow.clipPlaneDir[2]=0.0;
        break;
      case "Down":
        myCmiWindow.clipPlaneDir[0]=0.0;
        myCmiWindow.clipPlaneDir[1]=1.0;
        myCmiWindow.clipPlaneDir[2]=0.0;
        break;
      case "Front":
        myCmiWindow.clipPlaneDir[0]=0.0;
        myCmiWindow.clipPlaneDir[1]=0.0;
        myCmiWindow.clipPlaneDir[2]=-1.0;
        break;
      case "Back":
        myCmiWindow.clipPlaneDir[0]=0.0;
        myCmiWindow.clipPlaneDir[1]=0.0;
        myCmiWindow.clipPlaneDir[2]=1.0;
        break;
    }
    myCmiWindow.drawScene();
  }

  plCutDlg.onPlaneSliderChanged = function(slider)
  {
    plCutDlg.PlaneSldrValTxt.innerHTML = slider.value + "%";
    if(leftModel == null)
      return;
    if(plCutDlg.modelCenter == null)
      plCutDlg.initDialogValues();

    switch(currentCutDirection)
    {
      case "Left":
      case "Right":
        myCmiWindow.clipPlanePoint[0]=plCutDlg.modelCenter[0]+slider.value*plCutDlg.percentDist;
        break;
      case "Up":
      case "Down":
        myCmiWindow.clipPlanePoint[1]=plCutDlg.modelCenter[1]+slider.value*plCutDlg.percentDist;
        break;
      case "Front":
      case "Back":
        myCmiWindow.clipPlanePoint[2]=plCutDlg.modelCenter[2]+slider.value*plCutDlg.percentDist;
        break;
    }
    myCmiWindow.drawScene();
  }

  function plCutDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "close":
        break;
    }//switch(btnName)
  }

  plCutDlg.initDialogValues();

  plCutDlg.showDialog(parentDlg);

}//showPlCutDlg

function showPropDlg(parentDlg,entityArray,context,currentBom)
{
  if (!propDlg)
  {
    propDlg = new DialogBox('propDlg', propDlgCbk, cmiCanvas);
    propDlg.attTable = null;
    propDlg.clickedBomCol = 0;
    propDlg.colCopy = null;
    propDlg.enableCellEdit = true;
    propDlg.entityArray = null;
    propDlg.keyColumn = -1;
    propDlg.currentBom = null;
    propDlg.currentCmp = null;
    propDlg.branch = new Array();

    htmlTable = document.getElementById("propDlg_DoBoPropTab");

    htmlTable.addEventListener("paste", (ev) =>
    {
      const text = ev.clipboardData.getData('text/plain');
      document.execCommand("insertHTML", false, text);
      ev.preventDefault();
    });

    htmlTable.addEventListener("keydown", (ev) =>
    {
      let cell = ev.target;

      if(cell.nodeName.toLowerCase()=="td")
      {
        let row = cell.parentElement;
        let cellIndex = cell.cellIndex;
        let rowIndex = row.rowIndex-1;
        let table = row.parentElement;
        let rowCount = table.childNodes.length;
        let textContent = cell.childNodes[0];
        let cursorPosition = getCursorPosition(textContent);

        switch(ev.code)
        {
          case "ArrowDown":
            if(rowIndex < rowCount-1)
            {
              cell = table.childNodes[rowIndex+1].childNodes[cellIndex];
              cell.focus();
              ev.preventDefault();
            }
            break;
          case "ArrowUp":
            if((rowIndex < rowCount)&&(rowIndex > 0))
            {
              cell = table.childNodes[rowIndex-1].childNodes[cellIndex];
              cell.focus();
              ev.preventDefault();
            }
            break;
          case "ArrowLeft":
            if((cell.cellIndex > 1)&&(cell.previousElementSibling != null)&&(cursorPosition == 0))
            {
              cell = cell.previousElementSibling;
              cell.focus();
              ev.preventDefault();
            }
            break;
          case "ArrowRight":
            if((cell.cellIndex < propDlg.attTable.length-1)&&(cell.nextElementSibling != null)&&(cursorPosition == textContent.length))
            {
              cell = cell.nextElementSibling;
              cell.focus();
              ev.preventDefault();
            }
            break;
        }
      }
    });

    function getCursorPosition(element) //https://stackoverflow.com/questions/53668771/html-table-editable-td-cell-get-cursor-position
    {
      var caretOffset = 0;
      if(!element) return 0;
      var doc = element.ownerDocument || element.document;
      var win = doc.defaultView || doc.parentWindow;
      var sel;
      if (typeof win.getSelection != "undefined")
      {
        sel = win.getSelection();
        if (sel.rangeCount > 0)
        {
          var range = win.getSelection().getRangeAt(0);
          var preCaretRange = range.cloneRange();
          preCaretRange.selectNodeContents(element);
          preCaretRange.setEnd(range.endContainer, range.endOffset);
          caretOffset = preCaretRange.toString().length;
          //preCaretRange.setEnd(range.endContainer,2);
        }
      }
      else if ((sel = doc.selection) && sel.type != "Control")
      {
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
      }
      return caretOffset;
    };

    propDlg.onTabSelectionChange = function(sectionToActivate)
    {
      if(sectionToActivate == "propDlg_ModelSect")
      {
        Poi3dHelpers.setDisplayStyle("propDlg_ModelSect","block");
        Poi3dHelpers.setDisplayStyle("propDlg_DoBoSection","none");

        Poi3dHelpers.setDisplayStyle("propDlg_SaveBtn","none");
      }
      else if(sectionToActivate == "propDlg_DoBoSection")
      {
        Poi3dHelpers.setDisplayStyle("propDlg_ModelSect","none");
        Poi3dHelpers.setDisplayStyle("propDlg_DoBoSection","block");

        Poi3dHelpers.setDisplayStyle("propDlg_SaveBtn","inline-block");
      }
    };//propDlg.onTabSelectionChange

    propDlg.onCellValueChanged = function(ev)
    {
      if((propDlg.enableCellEdit == false)||(ev.type != "focusout"))
        return;

      var cell = ev.target;
      var psAtt = cell.psAtt;

      if(cell.nodeName.toLowerCase()=="td")
        psAtt.setValue(cell.innerHTML);
      else
      {
        var currEntry = null;
        var currAtt = null;
        for ( let i = 0; i<propDlg.attTable.length; i++)
        {
          currEntry = propDlg.attTable[i];
          currAtt = currEntry.attributes[cell.cellIndex-1];
          currAtt.setKey(cell.innerHTML);
        };
      }

      //events are swallowed -> perform action after focusout
      if(ev.relatedTarget != null)
      {
        if(ev.relatedTarget.id == "propDlg_SaveBtn")
          propDlgCbk(ev.relatedTarget.name);
        else if(ev.relatedTarget.id == "propDlg_CloseBtn")
          propDlgCbk(ev.relatedTarget.name);
      }

    };//propDlg.onCellValueChanged
    propDlg.importModelAttribute = function(modelAttTtlArray)
    {
      var model = null;
      var attVal = null;
      var attIndex = propDlg.clickedBomCol;
      var docAttributeObject = poi3dConnector.getLeftDocument().getDocAttributeObject();
      var docAttrSet = null;
      var modelName = "";

      for ( let i = 0; i<propDlg.attTable.length; i++)//all components
      {
        currEntry = propDlg.attTable[i];

        model = currEntry.entity.getModelRef();//CmiStructureNode

        if(model != null)
        {
          modelName = model.getModelName();
          docAttrSet = docAttributeObject.getTemplateAttributes(modelName,false);

          for ( let k = 0; k<modelAttTtlArray.length; k++)//all titles
          {
            //model attributes
            newAtt = new CmiProperty();
            newAtt.setKey(modelAttTtlArray[k]);

            if(modelAttTtlArray[k] == "Model-Name")
              attVal = model.getModelName();
            else
              attVal = model.getPropertyValue(modelAttTtlArray[k]);

            if(attVal != undefined)//found in model
              newAtt.setValue(attVal);
            else//search in doc attributes
            {
              for ( let m = 0; m<docAttrSet.length; m++)//component attributes from document
              {
                if(docAttrSet[m].getKey() == modelAttTtlArray[k])
                  newAtt.setValue(docAttrSet[m].getValue());
              }
            }

            currEntry.attributes.splice(attIndex+k, 0, newAtt);
          };//for ( let k = 0; i<modelAttTtlArray.length; k++)//all titles
        }//if(model != null)
      };//for ( let i = 0; i<propDlg.attTable.length; i++)//all components

      if((propDlg.keyColumn >= 0)&&(attIndex <= propDlg.keyColumn))
        propDlg.keyColumn = propDlg.keyColumn + modelAttTtlArray.length;

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;
    };

    propDlg.addNewAttribute = function()
    {
      var newAtt = null;
      var attIndex = propDlg.clickedBomCol;
      var attKey = "New_" + Math.random().toString(36).slice(2, 5);

      for ( let i = 0; i<propDlg.attTable.length; i++)
      {
        currEntry = propDlg.attTable[i];
        newAtt = new CmiProperty();
        newAtt.setKey(attKey);

        currEntry.attributes.splice(attIndex, 0, newAtt);
      };

      if((propDlg.keyColumn >= 0)&&(attIndex <= propDlg.keyColumn))
        propDlg.keyColumn++;

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;
    };//propDlg.addNewAttribute

    propDlg.setkeyColumn = function()
    {
      if((propDlg.clickedBomCol == 0)||(propDlg.keyColumn == propDlg.clickedBomCol-1))
        propDlg.keyColumn = -2;
      else
        propDlg.keyColumn = propDlg.clickedBomCol-1;

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;
    }

    propDlg.deleteAttribute = function()
    {
      if(propDlg.clickedBomCol == 0) return;

      var attIndex = propDlg.clickedBomCol-1;

      for ( let i = 0; i<propDlg.attTable.length; i++)
      {
        currEntry = propDlg.attTable[i];
        currEntry.attributes.splice(attIndex, 1);
      };

      if(propDlg.keyColumn == attIndex)
        propDlg.keyColumn = -1;
      else if((propDlg.keyColumn > 0)&&(attIndex < propDlg.keyColumn))
        propDlg.keyColumn--;

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;
    };//propDlg.addNewAttribute

    propDlg.copyAttribute = function()
    {
      propDlg.colCopy = new Array();
      var attIndex = propDlg.clickedBomCol-1;

      propDlg.colCopy = new Array();

      for ( let i = 0; i<propDlg.attTable.length; i++)
      {
        currEntry = propDlg.attTable[i];
        propDlg.colCopy.push(currEntry.attributes[attIndex]);
      };
      propDlg.enableCellEdit = true;
    };//propDlg.addNewAttribute

    propDlg.cutAttribute = function()
    {
      if(propDlg.clickedBomCol == 0) return;
      var attIndex = propDlg.clickedBomCol-1;

      propDlg.colCopy = new Array();

      for ( let i = 0; i<propDlg.attTable.length; i++)
      {
        currEntry = propDlg.attTable[i];
        propDlg.colCopy.push(currEntry.attributes[attIndex]);
        currEntry.attributes.splice(attIndex, 1);
      };

      if(propDlg.keyColumn == attIndex)
        propDlg.keyColumn = -1;
      else if((propDlg.keyColumn > 0)&&(attIndex < propDlg.keyColumn))
        propDlg.keyColumn--;

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;
    };//propDlg.addNewAttribute

    propDlg.pasteAttribute = function()
    {
      if((!propDlg.colCopy)||(propDlg.colCopy.length == 0)) return;

      var attIndex = propDlg.clickedBomCol;
      var attKey = "";

      for ( let i = 0; i<propDlg.attTable.length; i++)
      {
        currEntry = propDlg.attTable[i];
        propCopy = propDlg.colCopy[i].createCopy();
        if(i == 0) attKey = propCopy.getKey() + "_" + Math.random().toString(36).slice(2, 5);
        propCopy.setKey(attKey);

        currEntry.attributes.splice(attIndex, 0, propCopy);
      };

      if((propDlg.keyColumn >= 0)&&(attIndex <= propDlg.keyColumn))
        propDlg.keyColumn++;

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;
    };//propDlg.addNewAttribute

    propDlg.sort = function(dir)
    {
      var attIndex = propDlg.clickedBomCol;
      if(attIndex == 0)//Model name
      {
        if(dir == "asc")
        {
          if(propDlg.context == "bom")
          {
            propDlg.attTable.sort(function(a, b)
            {
              let x = a.entity.getTitle().toLowerCase();
              let y = b.entity.getTitle().toLowerCase();
              if (x < y) {return -1;}
              if (x > y) {return 1;}
              return 0;
            });
          }
          else//doc
          {
            propDlg.attTable.sort(function(a, b)
            {
              if(a.entity == myCmiWindow.getCmiModel()) {return -1;}
              if(b.entity == myCmiWindow.getCmiModel()) {return 1;}

              let x = a.entity.getModelName().toLowerCase();
              let y = b.entity.getModelName().toLowerCase();
              if (x < y) {return -1;}
              if (x > y) {return 1;}
              return 0;
            });
          }
        }
        else
        {
          if(propDlg.context == "bom")
          {
            propDlg.attTable.sort(function(a, b)
            {
              let x = a.entity.getTitle().toLowerCase();
              let y = b.entity.getTitle().toLowerCase();
              if (x < y) {return 1;}
              if (x > y) {return -1;}
              return 0;
            });
          }
          else
          {
            propDlg.attTable.sort(function(a, b)
            {
              let x = a.entity.getModelName().toLowerCase();
              let y = b.entity.getModelName().toLowerCase();
              if (x < y) {return 1;}
              if (x > y) {return -1;}
              return 0;
            });
          }
        }
      }//if(attIndex == 0)
      else
      {
        if(dir == "asc")
        {
          propDlg.attTable.sort(function(a, b)
          {
            let x = a.attributes[attIndex-1].getValue().toLowerCase();
            let y = b.attributes[attIndex-1].getValue().toLowerCase();

            if(x.length == 0) {return 1;}
            if(y.length == 0) {return -1;}
            if (x < y) {return -1;}
            if (x > y) {return 1;}
            return 0;
          });
        }
        else
        {
          propDlg.attTable.sort(function(a, b)
          {
            let x = a.attributes[attIndex-1].getValue().toLowerCase();
            let y = b.attributes[attIndex-1].getValue().toLowerCase();
            if(x.length == 0) {return 1;}
            if(y.length == 0) {return -1;}
            if (x < y) {return 1;}
            if (x > y) {return -1;}
            return 0;
          });
        }
      }

      propDlg.initialize(null);
      propDlg.enableCellEdit = true;

    };//propDlg.sort

    propDlg.showInBrowser = function(direction)
    {
      if(propDlg.currentCmp.getClassName() == "cmiComponentObject")
      {
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        rightAssemblyBrowser.switchHighlightStateForAll(false);
        currentHighlightedEntity = propDlg.currentCmp;
        handleCmpCtxCommand("CmpCtxSelectInBrowserCmd");
      }
      else if(propDlg.currentCmp.getClassName() == "cmiModel")
      {
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        rightAssemblyBrowser.switchHighlightStateForAll(false);
        myCmiWindow.drawScene();

        if(document.getElementById("leftBrowserArea").style.visibility != 'visible')
          showLeftTable(true);
      }
    };

    propDlg.moveInStructure = function(direction)
    {
      idx = propDlg.branch.findIndex(x => x === propDlg.currentCmp);
      switch(direction)
      {
        case "up":
          if(idx < propDlg.branch.length-1)
          {
            propDlg.currentCmp = propDlg.branch[idx+1];
            propDlg.initialize([propDlg.currentCmp]);
          }
          break;
        case "down":
          if(idx > 0)
          {
            propDlg.currentCmp = propDlg.branch[idx-1];
            propDlg.initialize([propDlg.currentCmp]);
          }
          break;
      }
    };//propDlg.moveInStructure

    propDlg.initialize = function(entArray) //entityArray can be a CmiComponent, a CmiStructureLink or a CmiTemplateModel array
    {
      var htmlTable = null;

      if(propDlg.context == "doc")
      {
        Poi3dHelpers.setDisplayStyle("#DoBoPropCtxImportPropCmd","none");
        Poi3dHelpers.setDisplayStyle("#DoBoPropCtxDefineAsExtKeyCmd","none");
      }
      else
      {
        Poi3dHelpers.setDisplayStyle("#DoBoPropCtxImportPropCmd","");
        Poi3dHelpers.setDisplayStyle("#DoBoPropCtxDefineAsExtKeyCmd","");
      }

      if((propDlg.context == "bom")||(propDlg.context == "doc"))
      {
        Poi3dHelpers.setDisplayStyle("propDlg_ModelSect","none");
        Poi3dHelpers.setDisplayStyle("propDlg_DoBoSection","block");
        Poi3dHelpers.setDisplayStyle("propDlg_SaveBtn","inline-block");
        Poi3dHelpers.setDisplayStyle("#propDlg_ModPropStruct","none");

        htmlTable = document.getElementById("propDlg_DoBoPropTab");
      }
      else
      {
        Poi3dHelpers.setDisplayStyle("propDlg_ModelSect","block");
        Poi3dHelpers.setDisplayStyle("propDlg_DoBoSection","none");
        Poi3dHelpers.setDisplayStyle("propDlg_SaveBtn","none");
        Poi3dHelpers.setDisplayStyle("#propDlg_ModPropStruct","inline-block");

        htmlTable = document.getElementById("propDlg_ModPropTab");
      }

      var row,cell;
      var currEntry = null;

      if(entArray != null)
      {
        propDlg.entityArray = entArray;
        propDlg.attTable = poi3dConnector.getAttributeTableFromEntityArray(propDlg.entityArray,propDlg.context);
      }
      else if(propDlg.currentCmp != null)
      {
        propDlg.entityArray = [propDlg.currentCmp];
        propDlg.attTable = poi3dConnector.getAttributeTableFromEntityArray(propDlg.entityArray,propDlg.context);
      }

      if(propDlg.attTable.length == 0) return;

      if((propDlg.context == "bom")||(propDlg.context == "doc"))
      {
        var rowCount = htmlTable.rows.length;
        for ( var i = 0; i<rowCount; i++)
        {
          htmlTable.deleteRow(-1);
        };

        var structureNode = null;
        var maxWdtLeftCol = "80px";

        currEntry = propDlg.attTable[0];

        if((propDlg.keyColumn == -1)&&(propDlg.context == "bom")) //check saved bom
        {
          let keyName = propDlg.currentBom.getAttributeNameForExternalKey();
          if(keyName.length > 0)
            propDlg.keyColumn = currEntry.attributes.findIndex(att => att.getKey() === keyName);
        }

        var header = htmlTable.createTHead();
        row = header.insertRow(0);
        var headerCell = document.createElement("TH");
        headerCell.style.position = 'sticky';
        headerCell.style.left = '0px';
        headerCell.style.top = '0px';
        headerCell.style.zIndex = '100';
        headerCell.style.maxWidth = maxWdtLeftCol;
        row.appendChild(headerCell);

        for ( let i = 0; i<currEntry.attributes.length; i++)
        {
          headerCell = document.createElement("TH");
          headerCell.style.position = 'sticky';
          headerCell.style.top = '0px';
          if(i == propDlg.keyColumn)
            headerCell.style.fontStyle = "italic";

          //headerCell.style.width = 'auto';
          headerCell.innerHTML = currEntry.attributes[i].getKey();
          headerCell.psAtt = currEntry.attributes[i];

          headerCell.setAttribute("contenteditable", true);
            
          headerCell.addEventListener('focusout', propDlg.onCellValueChanged);

          row.appendChild(headerCell);
        };

        var body = htmlTable.createTBody()
        var brdCol = "";

        //fill table
        for ( let i = 0; i<propDlg.attTable.length; i++)
        {
          currEntry = propDlg.attTable[i];
          structureNode = currEntry.entity; //CmiTemplateModel or CmiStructureLink

          row = body.insertRow(-1);
          cell = row.insertCell(0);
          if(propDlg.context == "bom")//add structure link title
          {
            cell.innerHTML = structureNode.getTitle();
            cell.title = structureNode.getTitle();
          }
          else
          {
            cell.innerHTML = structureNode.getModelName();
            cell.title = structureNode.getModelName();
          }

          cell.style.fontWeight = 'bold';
          cell.style.position = 'sticky';
          cell.style.left = '0px';
          cell.style.maxWidth = maxWdtLeftCol
          cell.style.overflow = 'hidden';
          cell.style.textOverflow = 'ellipsis';

          if(i % 2 == 0)
            cell.style.backgroundColor = "var(--MainBgCol)";
          else
            cell.style.backgroundColor = "var(--MenuBarBgCol)";

          for ( let k = 0; k<currEntry.attributes.length; k++)
          {
            cell = row.insertCell(-1);
            cell.innerHTML = currEntry.attributes[k].getValue();
            cell.psAtt = currEntry.attributes[k];
            if(k == propDlg.keyColumn)
            {
              cell.style.fontStyle = "italic";
              if(k % 2 == 0)
                brdCol = " var(--TableHdBgCol2)";
              else
                brdCol = " var(--TableHdBgCol1)";

              cell.style.borderRight = "3px solid"+brdCol;
              cell.style.borderLeft = "3px solid"+brdCol;
            }

            cell.setAttribute("contenteditable", true);
            cell.addEventListener('focusout', propDlg.onCellValueChanged);
          };
        };
      }
      else//if(propDlg.context == "bom")
      {
        var rowCount = htmlTable.rows.length;
        for ( var i = 1; i<rowCount; i++)//keep header
        {
          htmlTable.deleteRow(-1);
        };
        currEntry = propDlg.attTable[0];//only the first entity considered -> two column table
        //var model = currEntry.entity;

        for ( let i = 0; i<currEntry.attributes.length; i++)
        {
          row = htmlTable.insertRow(-1);
          cell = row.insertCell(0);
          cell.innerHTML = currEntry.attributes[i].getKey();

          cell = row.insertCell(1);
          cell.innerHTML = currEntry.attributes[i].getValue();
        };
      }//if(propDlg.context == "bom") else
    };//propDlg.initialize
  }//if (!propDlg)

  propDlg.context = context;

  if(currentBom  != undefined)
    propDlg.currentBom = currentBom;

  propDlg.branch = new Array();
  propDlg.currentCmp = null;
  if(propDlg.context == "model")
  {
    if((entityArray != null)&&(entityArray.length > 0))
    {
      propDlg.currentCmp = entityArray[0];
      propDlg.branch.push(propDlg.currentCmp);
      let upperComponent = propDlg.currentCmp.getParentComponent();
      while (upperComponent != null)
      {
        propDlg.branch.push(upperComponent);
        upperComponent = upperComponent.getParentComponent();
      }
    }
    propDlg.branch.push(myCmiWindow.getCmiModel());
    propDlg.currentCmp = propDlg.branch[0];
  }

  propDlg.initialize(entityArray);

  propDlg.showDialog(parentDlg);

  function propDlgCbk(btnName)
  {
    if (btnName == 'save')
    {
      if((propDlg.attTable != null)&&(propDlg.attTable.length > 0))
      {
        if(propDlg.context == "bom")
        {
          let keyName = "";
          if(propDlg.keyColumn >= 0)
          {
            keyName = propDlg.attTable[0].attributes[propDlg.keyColumn].getKey();
          }

          poi3dConnector.saveAttributeTableToProductStructure(propDlg.attTable,keyName,propDlg.currentBom);
        }
        else if(propDlg.context == "doc")
        {
          poi3dConnector.saveAttributeTableToDocumentAttributes(propDlg.attTable);
        }
      }
      propDlg.dialog.style.display = 'block';
    }
    else
      propDlg.dialog.style.display = 'none';

    propDlg.keyName = "";
    propDlg.keyColumn = -1;
  }

}//function showPropDlg(entity)

function showAccLogDlg(parentDlg,poi3dDocument,context,filterName)
{
  if (!accLogDlg)
  {
    accLogDlg = new DialogBox('accLogDlg', accLogDlgCbk, cmiCanvas);
    accLogDlg.header = document.getElementById("accLogDlg_Ttl").innerHTML;
    accLogDlg.entries = document.getElementById("accLogDlg_PropTab");

    accLogDlg.logUpdated = function()
    {
      accLogDlg.initialize();
    };

    poi3dConnector.registerCallback("updateLog",accLogDlg.logUpdated);

    accLogDlg.initialize = function()
    {
      var row,cell1,cell2;
      var rowCount = accLogDlg.entries.rows.length;

      for ( var i = 2; i<rowCount; i++)
      {
        accLogDlg.entries.deleteRow(-1);
      }

      var accessArray = null;
      if(accLogDlg.context == "docAccess")
      {
        accessArray = accLogDlg.poi3dDocument.getAccessLogEntries();
        for ( let i = 0; i<accessArray.length; i++)
        {
          row = accLogDlg.entries.insertRow(-1);
          cell1 = row.insertCell(0);
          cell1.innerHTML = accessArray[i].getFileAccessDate();

          cell1 = row.insertCell(1);
          cell1.innerHTML = accessArray[i].getFileAccessUserName();
        }
      }
      else if(accLogDlg.context == "fatchAccess")
      {
        accessArray = accLogDlg.poi3dDocument.getFileAttachmentsLogEntries();

        for ( let i = 0; i<accessArray.length; i++)
        {
          if(accessArray[i].getFileName() == accLogDlg.filterName)
          {
            row = accLogDlg.entries.insertRow(-1);
            cell1 = row.insertCell(0);
            cell1.innerHTML = accessArray[i].getFileAccessDate();

            cell1 = row.insertCell(1);
            cell1.innerHTML = accessArray[i].getFileAccessUserName();
          }
        }
      }

      let dlgTitle = document.getElementById("accLogDlg_Ttl");
      if(accLogDlg.filterName.length >0)
        dlgTitle.innerHTML = accLogDlg.header +" (" + accLogDlg.filterName + ")";
      else
        dlgTitle.innerHTML = accLogDlg.header;

    };//accLogDlg.initialize
  }

  accLogDlg.poi3dDocument = poi3dDocument;
  accLogDlg.context = context;
  accLogDlg.filterName = filterName;

  accLogDlg.initialize();

  if(context == "docAccess")
  {
    let accessLog = accLogDlg.poi3dDocument.getAccessLog();
    accessLog.reload();
  }
  else if(accLogDlg.context == "fatchAccess")
  {
    let accessLog = accLogDlg.poi3dDocument.getFileAttachmentsLog();
    accessLog.reload();
  }

  accLogDlg.showDialog(parentDlg);

  function accLogDlgCbk(btnName)
  {
  }

}//function showAccLogDlg(entity)

function showMeasDlg(parentDlg)
{
  if (!measDlg)
  {
    measDlg = new DialogBox('measDlg', measDlgCbk, cmiCanvas);

    measDlg.calculate3dAngle = function(p1,p2,p3)
    {
      const d12 = CmiHelpers.calculate3dDistance(p1, p2);
      const d23 = CmiHelpers.calculate3dDistance(p2, p3);
      const d13 = CmiHelpers.calculate3dDistance(p1, p3);

      const angle = (Math.pow(d12, 2) + Math.pow(d23, 2) - Math.pow(d13, 2)) / (2 * d12 * d23);
      return Math.acos(angle) * (180 / Math.PI);
    };//measDlg.calculate3dAngle

    measDlg.calculate3dRadius = function(A,B,C)
    {
      const va = vec3.create(A);
      const vb = vec3.create(B);
      const vc = vec3.create(C);

      const a = CmiHelpers.calculate3dDistance(B, C);
      const b = CmiHelpers.calculate3dDistance(A, C);
      const c = CmiHelpers.calculate3dDistance(A, B);

      const AB = vec3.subtract(B, A);
      const AC = vec3.subtract(C, A);

      // Area of triangle = 0.5 * |AB x AC|
      const cross = vec3.cross(AB, AC);
      const tarea = vec3.length(cross);

      if (tarea === 0)
        return 0;

      // Radius from circumradius formula
      const radius = (a * b * c) / (2 * tarea);
      return radius;
    };//measDlg.calculate3dRadius

    measDlg.onPickPoint = function ()
    {
      let measDlg_MdtSel = document.getElementById("measDlg_MdtSel");
      let currSel = measDlg_MdtSel.options[measDlg_MdtSel.selectedIndex ].value

      if(pickPoints.length > 0)
      {
        myCmiWindow.getCmiModel().removeLocatorsFromModelByNames(pickPoints);
        pickPoints = new Array();
      }

      switchMouseMode("pick");

      switch(currSel)
      {
        case "dist":
          interactionMode = "measureDist";
          setStatusText(poi3dConnector.getStatusText(0));
          break;
        case "ang":
          interactionMode = "measureAng";
          setStatusText(poi3dConnector.getStatusText(8));
          break;
          break;
        case "rad":
          interactionMode = "measureRad";
          setStatusText(poi3dConnector.getStatusText(0));
          break;
      }

      measDlgVisible = false;
      measDlg.dialog.style.display = 'none';
    };//measDlg.onPickPoint

    measDlg.updateInformation = function ()
    {
      let loc1 = null;
      let loc2 = null;
      let loc3 = null;
      let globalOrigin1 = null;
      let globalOrigin2 = null;
      let globalOrigin3 = null;
      let val1 = 0.0;
      let val2 = 0.0;
      let val3 = 0.0;
      let val4 = 0.0;
      let val5 = 0.0;
      let tbl = document.getElementById("measDlg_InfoTbl");
      let body = document.getElementById("measDlg_InfoTblBdy");
      let row = null;
      let cell = null;

      let rowCount = tbl.rows.length;
      for ( var i = 1; i<rowCount; i++) //keep header
        tbl.deleteRow(-1);

      switch(interactionMode)
      {
        case "measureDist":
          loc1 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[0]);
          loc2 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[1]);
          globalOrigin1=loc1.getGlobalOrigin();
          globalOrigin2=loc2.getGlobalOrigin();

          globalOrigin1[0]=globalOrigin1[0]*measurementScale;
          globalOrigin1[1]=globalOrigin1[1]*measurementScale;
          globalOrigin1[2]=globalOrigin1[2]*measurementScale;

          globalOrigin2[0]=globalOrigin2[0]*measurementScale;
          globalOrigin2[1]=globalOrigin2[1]*measurementScale;
          globalOrigin2[2]=globalOrigin2[2]*measurementScale;

          val1 = Math.abs(globalOrigin1[0]-globalOrigin2[0]);//dX
          val2 = Math.abs(globalOrigin1[1]-globalOrigin2[1]);//dY
          val3 = Math.abs(globalOrigin1[2]-globalOrigin2[2]);//dZ
          val4 = Math.sqrt((val1 * val1) + (val2 * val2) + (val3 * val3));//dist

          body = document.getElementById("measDlg_InfoTblBdy");

          row = body.insertRow(0);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 1:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin1[0]).toFixed(2)+", "+parseFloat(globalOrigin1[1]).toFixed(2)+", "+parseFloat(globalOrigin1[2]).toFixed(2);

          row = body.insertRow(1);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 2:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin2[0]).toFixed(2)+", "+parseFloat(globalOrigin2[1]).toFixed(2)+", "+parseFloat(globalOrigin2[2]).toFixed(2);

          row = body.insertRow(2);
          cell = row.insertCell(0);
          cell.innerHTML = "DX:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(val1).toFixed(2);

          row = body.insertRow(3);
          cell = row.insertCell(0);
          cell.innerHTML = "DY:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(val2).toFixed(2);

          row = body.insertRow(4);
          cell = row.insertCell(0);
          cell.innerHTML = "DZ:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(val3).toFixed(2);

          row = body.insertRow(5);
          cell = row.insertCell(0);
          cell.innerHTML = poi3dConnector.getUiText("measDlg_DistTtl") + ":";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(val4).toFixed(2);
          break;
        case "measureRad":
          loc1 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[0]);
          loc2 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[1]);
          loc3 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[2]);
          globalOrigin1=loc1.getGlobalOrigin();
          globalOrigin2=loc2.getGlobalOrigin();
          globalOrigin3=loc3.getGlobalOrigin();

          row = body.insertRow(0);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 1:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin1[0]).toFixed(2)+", "+parseFloat(globalOrigin1[1]).toFixed(2)+", "+parseFloat(globalOrigin1[2]).toFixed(2);

          row = body.insertRow(1);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 2:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin2[0]).toFixed(2)+", "+parseFloat(globalOrigin2[1]).toFixed(2)+", "+parseFloat(globalOrigin2[2]).toFixed(2);

          row = body.insertRow(2);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 3:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin3[0]).toFixed(2)+", "+parseFloat(globalOrigin3[1]).toFixed(2)+", "+parseFloat(globalOrigin3[2]).toFixed(2);

          row = body.insertRow(3);
          cell = row.insertCell(0);
          cell.innerHTML = "Radius:";
          cell = row.insertCell(1);
          cell.innerHTML = (measDlg.calculate3dRadius(globalOrigin1,globalOrigin2,globalOrigin3) * measurementScale).toFixed(2);
          break;
        case "measureAng":
          loc1 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[0]);
          loc2 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[1]);
          loc3 = myCmiWindow.getCmiModel().getEntityByName(pickPoints[2]);
          globalOrigin1=loc1.getGlobalOrigin();
          globalOrigin2=loc2.getGlobalOrigin();
          globalOrigin3=loc3.getGlobalOrigin();

          row = body.insertRow(0);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 1 (Center):";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin1[0]).toFixed(2)+", "+parseFloat(globalOrigin1[1]).toFixed(2)+", "+parseFloat(globalOrigin1[2]).toFixed(2);

          row = body.insertRow(1);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 2:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin2[0]).toFixed(2)+", "+parseFloat(globalOrigin2[1]).toFixed(2)+", "+parseFloat(globalOrigin2[2]).toFixed(2);

          row = body.insertRow(2);
          cell = row.insertCell(0);
          cell.innerHTML = "Pos 3:";
          cell = row.insertCell(1);
          cell.innerHTML = parseFloat(globalOrigin3[0]).toFixed(2)+", "+parseFloat(globalOrigin3[1]).toFixed(2)+", "+parseFloat(globalOrigin3[2]).toFixed(2);

          row = body.insertRow(3);
          cell = row.insertCell(0);
          cell.innerHTML = "Angle:";
          cell = row.insertCell(1);
          cell.innerHTML = measDlg.calculate3dAngle(globalOrigin2,globalOrigin1,globalOrigin3).toFixed(2) + "&deg;";
          break;
      }
    };//measDlg.updateInformation
  };//if (!measDlg)

  measDlg.showDialog(parentDlg);
  measDlg.updateInformation();
  measDlgVisible = true;

  function measDlgCbk(btnName)
  {

    if(btnName == 'close')
    {
      if(viewingMode == "VR+")
        switchMouseMode("zoom");
      else
        switchMouseMode("rotate");

      interactionMode = "";
      handleSelectionSettings();
    }

    if(pickPoints.length > 0)
    {
      myCmiWindow.getCmiModel().removeLocatorsFromModelByNames(pickPoints);
      pickPoints = new Array();
    }
    measDlgVisible = false;
  }
}//function showMeasDlg()

function showMsgDlg(parentDlg,message,context)
{
  if (!msgDlg)
    msgDlg = new DialogBox('msgDlg', msgDlgCbk, cmiCanvas);

  document.getElementById("msgDlg_MsgVal").innerHTML = message;

  if(parentDlg == null)
    msgDlg.dialog.style.zIndex = 100;

  msgDlg.showDialog(parentDlg);

  function msgDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      if(context == "docDeleted")
      {
        resetViewer();
        poi3dConnector.setLeftDocument(null);
        poi3dConnector.getPoi3dUser().reLoadWorkGroups();
      }
    }
  }
}//function showMsgDlg(message)

function showYesNoDlg(parentDlg,message,context)
{
  if (!yesNoDlg)
  {
    yesNoDlg = new DialogBox('yesNoDlg', yesNoDlgCbk, cmiCanvas);
    yesNoDlg.ringTone = new Audio("./Poi3d/Ressources/ring.mp3");
    yesNoDlg.ringTone.loop = true;
    yesNoDlg.context = context;
  }

  document.getElementById("yesNoDlg_Question").innerHTML = message;

  yesNoDlg.context = context;

  yesNoDlg.showDialog(parentDlg);

  if(context == "incomingCall")
    yesNoDlg.ringTone.play();

  function yesNoDlgCbk(btnName)
  {
    if (btnName == 'yes')
    {
      switch(yesNoDlg.context)
      {
        case "incomingCall":
          yesNoDlg.ringTone.pause();
          yesNoDlg.ringTone.currentTime = 0;

          showCommDlg(yesNoDlg);
          commDlg.acceptCall();
          break;
        case "annChanged":
        case "annLocked":
          poi3dConnector.getLeftDocument().getAnnotationObject().readFromStorage();
          break;
        case "locChanged":
        case "locLocked":
          poi3dConnector.getLeftDocument().getViewLocationObject().readFromStorage();
          break;
        case "instrChanged":
        case "instrLocked":
          poi3dConnector.getLeftDocument().getInstructionObject().readFromStorage();
          break;
        case "mSetsChanged":
        case "mSetsLocked":
          poi3dConnector.getLeftDocument().getMaterialSetObject().readFromStorage();
          break;
        case "fAttChanged":
        case "fAttLocked":
          poi3dConnector.getLeftDocument().getFileAttachmentObject().readFromStorage();
          break;
        case "bomsChanged":
        case "bomsLocked":
          poi3dConnector.getLeftDocument().getBomStructureObject().readFromStorage();
          break;
        case "sensorsChanged":
        case "sensorsLocked":
          poi3dConnector.getLeftDocument().getSensorObject().readFromStorage();
          break;
      }
    }
    else if (btnName == 'no')
    {
      switch(context)
      {
        case "incomingCall":
          yesNoDlg.ringTone.pause();
          yesNoDlg.ringTone.currentTime = 0;
          poi3dConnector.rejectUserCall();
          break;
      }
    }
  }
}//function showYesNoDlg(message)

function showVidHlpDlg(parentDlg,helpCmd)
{
  if (!vidHlpDlg)
    vidHlpDlg = new DialogBox('vidHlpDlg', vidHlpDlgCbk, cmiCanvas);

  document.getElementById("vidHlpDlg_Video").src = helpCmd;

  vidHlpDlg.showDialog(parentDlg);

  function vidHlpDlgCbk(btnName)
  {
    document.getElementById("vidHlpDlg_Video").pause();
  }
}//function showVidHlpDlg()

function showAnimDlg(parentDlg)
{
  if (!animDlg)
    animDlg = new DialogBox('animDlg', animDlgCbk, cmiCanvas);

  var animDlg_Sel = document.getElementById("animDlg_Sel");
  animDlg_Sel.options.length = 0;

  for ( var i =0; i< modelAnimations.length; i++)
  {
    var option = document.createElement("option");
    option.text = modelAnimations[i].getAnimationName();
    animDlg_Sel.add(option);
  }

  animDlg.showDialog(parentDlg);

  function animDlgCbk(btnName)
  {
    var animDlg_Sel = document.getElementById("animDlg_Sel");
    var currentAnimation = null;

    if(modelAnimations.length >0)
      currentAnimation = modelAnimations[animDlg_Sel.selectedIndex];

    switch(btnName)
    {
      case "start":
        animDlg.dialog.style.display = 'block';
        if(modelAnimations.length >0)
        {
          currentAnimation.run(1);
        }
        break;
      case "stop":
        animDlg.dialog.style.display = 'block';
        if(modelAnimations.length >0)
        {
          currentAnimation.stopAnim();
          currentAnimation.resetEntites(true);
        }
        break;
      case "loop":
        animDlg.dialog.style.display = 'block';
        if(modelAnimations.length >0)
        {
          currentAnimation.runInLoop();
        }
        break;
      case "close":
        break;
    }
  }//function animDlgCbk(btnName)
}//function showAnimDlg()

function showUMgmDlg(parentDlg)
{
  if (!uMgmDlg)
  {
    uMgmDlg = new DialogBox('uMgmDlg', uMgmDlgCbk, cmiCanvas);
    uMgmDlg.statusOutput = document.getElementById("uMgmDlg_StateVal");
    uMgmDlg.selectedUsers = new Array();

    uMgmDlg.selectUser  = function()
    {
      showUSelDlg(uMgmDlg,"uMgmDlg",[],poi3dConnector.getUsers());
    }

    uMgmDlg.updateUserSettings  = function()
    {
      if(uMgmDlg.selectedUsers.length == 1)
        poi3dConnector.readUserAccessData(uMgmDlg.selectedUsers[0]);
      else if(uMgmDlg.selectedUsers.length > 1)
      {
        document.getElementById("uMgmDlg_UserNameVal").innerHTML = uMgmDlg.selectedUsers[0].aliasName + ",... (" + uMgmDlg.selectedUsers.length +")";
        //default values
        document.getElementById("uMgmDlg_MaxDocsVal").value = 3;
        document.getElementById("uMgmDlg_MaxWgVal").value = 1;
        document.getElementById("uMgmDlg_MaxFattVal").value = 3;
        document.getElementById("uMgmDlg_TypeSel").value = "u";
        document.getElementById("uMgmDlg_AuthorExpDateVal").value = "2000-01-01";

        Poi3dHelpers.canBeUsed("uMgmDlg_UserNameVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxDocsVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxWgVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxFattVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_TypeSel",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_AuthorExpDateVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_IsPermanentVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_IsLockedVal",true);
      }
      else
      {
        Poi3dHelpers.canBeUsed("uMgmDlg_UserNameVal",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxDocsVal",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxWgVal",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxFattVal",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_TypeSel",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_AuthorExpDateVal",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_IsPermanentVal",false);
        Poi3dHelpers.canBeUsed("uMgmDlg_IsLockedVal",false);
      }
    }

    uMgmDlg.userAccessUpdated  = function(message,infoObject)
    {
      if(message.length > 0)
      {
        showMsgDlg(uMgmDlg,message);
      }
      else
      {
        let uMgmDlg_TypeSel = document.getElementById("uMgmDlg_TypeSel");
        if(uMgmDlg.selectedUsers.length == 1)
          document.getElementById("uMgmDlg_UserNameVal").innerHTML = uMgmDlg.selectedUsers[0].aliasName;
        else
          document.getElementById("uMgmDlg_UserNameVal").innerHTML = uMgmDlg.selectedUsers[0].aliasName + ",... (" + uMgmDlg.selectedUsers.length +")";

        document.getElementById("uMgmDlg_MaxDocsVal").value = infoObject.nDoc;
        document.getElementById("uMgmDlg_MaxWgVal").value = infoObject.nWg;
        document.getElementById("uMgmDlg_MaxFattVal").value = infoObject.nFatt;
        document.getElementById("uMgmDlg_AuthorExpDateVal").value = infoObject.aExpDt.split('T')[0];

        for(let i=0; i<uMgmDlg_TypeSel.options.length; i++)
        {
          if(uMgmDlg_TypeSel.options[i].value == infoObject.tyP)
          {
            uMgmDlg_TypeSel.selectedIndex = i;
            break;
          }
        }
        document.getElementById("uMgmDlg_IsPermanentVal").checked = false;

        if(infoObject.lck == true)
          document.getElementById("uMgmDlg_IsLockedVal").checked = true;
        else
          document.getElementById("uMgmDlg_IsLockedVal").checked = false;

        Poi3dHelpers.canBeUsed("uMgmDlg_UserNameVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxDocsVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxWgVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_MaxFattVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_TypeSel",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_AuthorExpDateVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_IsPermanentVal",true);
        Poi3dHelpers.canBeUsed("uMgmDlg_IsLockedVal",true);
      }
    }

    poi3dConnector.registerCallback("userAccessUpdated",uMgmDlg.userAccessUpdated);

    uMgmDlg.updateUserAccess  = function()
    {
      if(uMgmDlg.selectedUsers.length > null)
      {
        let userTyp = uMgmDlg_TypeSel.value;
        let maxDocs = parseInt(document.getElementById("uMgmDlg_MaxDocsVal").value);
        let maxWg = parseInt(document.getElementById("uMgmDlg_MaxWgVal").value);
        let maxFa = parseInt(document.getElementById("uMgmDlg_MaxFattVal").value);
        let expDate = new Date(document.getElementById("uMgmDlg_AuthorExpDateVal").value).toISOString();
        let isLocked = document.getElementById("uMgmDlg_IsLockedVal").checked;
        let isPermanent = document.getElementById("uMgmDlg_IsPermanentVal").checked;

        poi3dConnector.updateUserAccess(uMgmDlg.selectedUsers,userTyp,maxDocs,maxWg,maxFa,expDate,isLocked,isPermanent);
      }
    }
  }//if (!uMgmDlg)

  //initialize dialog ------------------------------------------------
  uMgmDlg.updateUserSettings();
  uMgmDlg.showDialog(parentDlg);

  function uMgmDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "close":
      case "umClose":
        break;
      default:
        uMgmDlg.dialog.style.display = 'block';
        break;
    }
  }
}//showUMgmDlg()

function showUSetDlg(parentDlg)
{
  if (!uSetDlg)
  {
    uSetDlg = new DialogBox('uSetDlg', uSetDlgCbk, cmiCanvas);
    uSetDlg.statusOutput = document.getElementById("uSetDlg_StateVal");

    if(poi3dConnector.isPoi3dEnv() == false)
      Poi3dHelpers.setDisplayStyle("uSetDlg_TrmOfUseTtl","none");

    uSetDlg.onColorSelectionChange = function(selectionOject)
    {
      var hasChanged=false;

      switch(selectionOject.options[selectionOject.selectedIndex].value)
      {
        case "LightColorSelectionValue":
          poi3dConnector.getUserSettings().colorScheme = "light";
          document.querySelector('body').setAttribute('data-theme', 'light');
          hasChanged=true;
          break;
        case "DarkColorSelectionValue":
          poi3dConnector.getUserSettings().colorScheme = "dark";
          document.querySelector('body').setAttribute('data-theme', 'dark');
          hasChanged=true;
          break;
        case "GrayColorSelectionValue":
          poi3dConnector.getUserSettings().colorScheme = "gray";
          document.querySelector('body').setAttribute('data-theme', 'gray');
          hasChanged=true;
          break;
      }

      if(hasChanged)
      {
        var cmpColor3D = getComputedStyle(document.querySelector('body')).getPropertyValue('--CmpCol3d').match(/\d+/g).map(Number);
        var bgColor3D = getComputedStyle(document.querySelector('body')).getPropertyValue('--MainBgCol').match(/\d+/g).map(Number);
        if(myCmiWindow != undefined)
        {
          myCmiWindow.setBgColorRGB(bgColor3D[0],bgColor3D[1],bgColor3D[2]);
          myCmiWindow.setCompareColorRGB(cmpColor3D[0],cmpColor3D[1],cmpColor3D[2]);
        }
      }
      if(myCmiWindow != undefined)
        myCmiWindow.drawScene();
    }

    uSetDlg.deleteUser = function()
    {
      showVerifyDlg(uSetDlg,'deleteUser',null);
    }

    uSetDlg.onLanguageSelectionChange = function(selectionOject)
    {
      poi3dConnector.getUserSettings().uiLanguage = selectionOject.options[selectionOject.selectedIndex].value;
      poi3dConnector.translate();
      if(myCmiWindow != undefined)
        myCmiWindow.drawScene();
    }

    uSetDlg.onTabSelectionChange = function(sectionToActivate)
    {
      if(sectionToActivate == "uSetDlg_ViewSection")
      {
        Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","block");
        Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","none");

        Poi3dHelpers.setDisplayStyle("uSetDlg_SaveBtn","inline-block");
      }
      else if(sectionToActivate == "uSetDlg_UserSection")
      {
        Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","block");
        Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","none");

        Poi3dHelpers.setDisplayStyle("uSetDlg_SaveBtn","inline-block");
      }
      else if(sectionToActivate == "uSetDlg_PwdSection")
      {
        Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","block");
        Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","none");

        Poi3dHelpers.setDisplayStyle("uSetDlg_SaveBtn","none");

        document.getElementById("uSetDlg_TwoFacAuthTypeVal").checked = poi3dConnector.getPoi3dUser().get2FA();
      }
      else if(sectionToActivate == "uSetDlg_DelSection")
      {
        Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","block");
        Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","none");

        Poi3dHelpers.setDisplayStyle("uSetDlg_SaveBtn","none");
      }
      else
      {
        Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","none");
        Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","block");

        Poi3dHelpers.setDisplayStyle("uSetDlg_SaveBtn","none");

        if((poi3dConnector.getPoi3dUser().hasAdminProxy())||(poi3dConnector.hasUserAdminRights()))
        {

          document.getElementById("uSetDlg_MaxDocsVal").innerHTML = poi3dConnector.getPoi3dUser().getMaxNrOfDocuments();
          document.getElementById("uSetDlg_MaxWgVal").innerHTML = poi3dConnector.getPoi3dUser().getMaxNrOfWorkGroups();
          document.getElementById("uSetDlg_MaxFattVal").innerHTML = poi3dConnector.getPoi3dUser().getMaxNrOfFileAttachements();
          document.getElementById("uSetDlg_AuthorExpDateVal").value = poi3dConnector.getPoi3dUser().getAuthorExpirationDate().split('T')[0];

          let uType = poi3dConnector.getPoi3dUser().getUserType();
          for(let i=0; i<uSetDlg_TypeSel.options.length; i++)
          {
            if(uSetDlg_TypeSel.options[i].value == uType)
            {
              uSetDlg_TypeSel.selectedIndex = i;
              break;
            }
          }
        }
      }
    };//uSetDlg.onTabSelectionChange

    uSetDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      uSetDlg.statusOutput.innerHTML = textToDisplay;
      switch(currentStatus)
      {
        case "updateUserSuccess":
          poi3dConnector.getPoi3dUser().savePhoto(document.getElementById("uSetDlg_ImgVal"));
          break;
        case "updatePwdSuccess":
          document.getElementById("uSetDlg_OldPwdVal").value="";
          document.getElementById("uSetDlg_NewPwdVal").value="";
          document.getElementById("uSetDlg_RepNewPwdVal").value="";
          break;
      }
    };//uSetDlg.onStatusUpdate

    uSetDlg.changeUserPassword = function()
    {
      var oldPwd = document.getElementById("uSetDlg_OldPwdVal").value;
      var newPwd = document.getElementById("uSetDlg_NewPwdVal").value;
      var newPwd2 = document.getElementById("uSetDlg_RepNewPwdVal").value;
      if(newPwd != newPwd2)
      {
        uSetDlg.statusOutput.innerHTML = "new passwords do not match";
        return;
      }
      if(poi3dConnector.isValidPassword(newPwd) == false)
      {
        uSetDlg.statusOutput.innerHTML = "a new passwords must be at least<br> 8 characters long and must not contain<br> \" & ' -> ,";
        return;
      }

      poi3dConnector.getPoi3dUser().updatePwd(oldPwd, newPwd);
    }//uSetDlg.changeUserPassword

    uSetDlg.changeTwoFactor = function()
    {
      var twoFA = document.getElementById("uSetDlg_TwoFacAuthTypeVal").checked;

      poi3dConnector.getPoi3dUser().set2FA(twoFA);
    };//uSetDlg.changeTwoFactor

    uSetDlg.onImgSelected = function()
    {
      if(imgOpenDlg.isImageSelected == true)
        document.getElementById("uSetDlg_ImgVal").src = imgOpenDlg.imageElement.src;
      else
        document.getElementById('uSetDlg_ImgVal').src = poi3dConnector.getPoi3dUser().getPhotoUrl();
    };//uSetDlg.onImgSelected

    poi3dConnector.registerCallback("userSettingsDlgStatusUpdate",uSetDlg.onStatusUpdate);

  }//if (!uSetDlg)

  //initialize dialog ------------------------------------------------

  var useDynamicStdSelbox = document.getElementById("uSetDlg_dynSelStdVal");
  var useDynamicVrSelbox = document.getElementById("uSetDlg_dynSelVrVal");
  var zAxisDirUpSelbox = document.getElementById("uSetDlg_ZAxisDirUpVal");
  var zAxisDirToSelbox = document.getElementById("uSetDlg_ZAxisDirToVal");
  var colorSelection = document.getElementById("uSetDlg_ColSel");
  var languageSelection = document.getElementById("uSetDlg_LangSel");
  var posNrDltaValue = document.getElementById("uSetDlg_PosNrDltaVal");
  var bomSendAddressValue = document.getElementById("uSetDlg_BomSendAddrVal");
  var uSetDlg_TypeSel = document.getElementById("uSetDlg_TypeSel");

  useDynamicStdSelbox.checked = poi3dConnector.getUserSettings().useDynamicStdSelection;
  useDynamicVrSelbox.checked = poi3dConnector.getUserSettings().useDynamicVrSelection;

  /*
  if(poi3dConnector.getPoi3dUser().isLoggedIn() == false)
    Poi3dHelpers.setDisplayStyle("uSetDlg_LangSel","none");
  else
    Poi3dHelpers.setDisplayStyle("uSetDlg_LangSel","block");
  */
  posNrDltaValue.value = poi3dConnector.getUserSettings().deltaValPosNr;
  bomSendAddressValue.value = poi3dConnector.getUserSettings().bomSendAddress;

  if(poi3dConnector.getUserSettings().useFrontAsTop == false)
    zAxisDirUpSelbox.checked = true;
  else
    zAxisDirToSelbox.checked = true;

  switch(poi3dConnector.getUserSettings().colorScheme)
  {
    case "light":
      colorSelection.selectedIndex = 0;
      break;
    case "dark":
      colorSelection.selectedIndex = 1;
      break;
    case "gray":
      colorSelection.selectedIndex = 2;
      break;
  }

  languageSelection.value = poi3dConnector.getUserSettings().uiLanguage;

  if(poi3dConnector.checkUserAccess() == false)
  {
    Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","block");
    document.getElementById("uSetDlg_ViewTabVal").checked = "checked";

    Poi3dHelpers.setDisplayStyle("uSetDlg_userTabLab","none");
    Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","none");

    Poi3dHelpers.setDisplayStyle("uSetDlg_pwdTabLab","none");
    Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","none");

    Poi3dHelpers.setDisplayStyle("uSetDlg_delTabLab","none");
    Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","none");

    Poi3dHelpers.setDisplayStyle("uSetDlg_infoTabLab","none");
    Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","none");
  }
  else
  {
    var userProps = poi3dConnector.getUserProperties();

    document.getElementById("uSetDlg_AliasVal").innerHTML = userProps.aliasName;
    document.getElementById("uSetDlg_EmailVal").value = userProps.email;
    document.getElementById("uSetDlg_PhoneVal").value = userProps.telNr;
    document.getElementById("uSetDlg_FirstNmeVal").value = userProps.firstName;
    document.getElementById("uSetDlg_LastNmeVal").value = userProps.lastName;

    var photoUrl = poi3dConnector.getPoi3dUser().getPhotoUrl();
    if(photoUrl.length > 0)
    {
      photoUrl = photoUrl+"?t=" + new Date().getTime();
      document.getElementById("uSetDlg_ImgVal").src = photoUrl;
    }
    else
      document.getElementById("uSetDlg_ImgVal").src="./Poi3d/Images/Person.png"

    document.getElementById("uSetDlg_MaxDocsVal").innerHTML = poi3dConnector.getPoi3dUser().getMaxNrOfDocuments();
    document.getElementById("uSetDlg_MaxWgVal").innerHTML = poi3dConnector.getPoi3dUser().getMaxNrOfWorkGroups();
    document.getElementById("uSetDlg_MaxFattVal").innerHTML = poi3dConnector.getPoi3dUser().getMaxNrOfFileAttachements();
    document.getElementById("uSetDlg_AuthorExpDateVal").value = poi3dConnector.getPoi3dUser().getAuthorExpirationDate().split('T')[0];

    let uType = poi3dConnector.getPoi3dUser().getUserType();
    for(let i=0; i<uSetDlg_TypeSel.options.length; i++)
    {
      if(uSetDlg_TypeSel.options[i].value == uType)
      {
        uSetDlg_TypeSel.selectedIndex = i;
        break;
      }
    }

    Poi3dHelpers.setDisplayStyle("uSetDlg_ViewSection","block");
    document.getElementById("uSetDlg_ViewTabVal").checked = "checked";
    Poi3dHelpers.setDisplayStyle("uSetDlg_SaveBtn","inline-block");

    Poi3dHelpers.setDisplayStyle("uSetDlg_userTabLab","inline-block");
    Poi3dHelpers.setDisplayStyle("uSetDlg_UserSection","none");

    Poi3dHelpers.setDisplayStyle("uSetDlg_pwdTabLab","inline-block");
    Poi3dHelpers.setDisplayStyle("uSetDlg_PwdSection","none");

    Poi3dHelpers.setDisplayStyle("uSetDlg_delTabLab","inline-block");
    Poi3dHelpers.setDisplayStyle("uSetDlg_DelSection","none");

    Poi3dHelpers.setDisplayStyle("uSetDlg_infoTabLab","inline-block");
    Poi3dHelpers.setDisplayStyle("uSetDlg_InfoSection","none");

  }

  uSetDlg.showDialog(parentDlg);

  function uSetDlgCbk(btnName)
  {
    var useDynamicStdSelbox = document.getElementById("uSetDlg_dynSelStdVal");
    var useDynamicVrSelbox = document.getElementById("uSetDlg_dynSelVrVal");
    var zAxisDirUpSelbox = document.getElementById("uSetDlg_ZAxisDirUpVal");

    if(btnName != "close")
      uSetDlg.dialog.style.display = 'block';
    else
      uSetDlg.onStatusUpdate("","");

    if (btnName == 'save')
    {
      uSetDlg.dialog.style.display = 'block';

      poi3dConnector.getUserSettings().deltaValPosNr = parseInt(posNrDltaValue.value);
      poi3dConnector.getUserSettings().useDynamicStdSelection = useDynamicStdSelbox.checked;
      poi3dConnector.getUserSettings().useDynamicVrSelection = useDynamicVrSelbox.checked;
      poi3dConnector.getUserSettings().bomSendAddress = bomSendAddressValue.value;

      if(zAxisDirUpSelbox.checked == true)
        poi3dConnector.getUserSettings().useFrontAsTop = false;
      else
        poi3dConnector.getUserSettings().useFrontAsTop = true;

      if(poi3dConnector.checkUserAccess() == true)
      {
        poi3dConnector.copySettingsToUser();
        var userProperties = new Poi3dUserProperties();

        userProperties.email = document.getElementById("uSetDlg_EmailVal").value;
        userProperties.telNr = document.getElementById("uSetDlg_PhoneVal").value;
        userProperties.firstName = document.getElementById("uSetDlg_FirstNmeVal").value;
        userProperties.lastName = document.getElementById("uSetDlg_LastNmeVal").value;
        poi3dConnector.setUserProperties(userProperties);

        poi3dConnector.saveUserSettings();
      }
      else
      {
        poi3dConnector.saveUserSettingsToLocalStorage();
        uSetDlg.onStatusUpdate("settings locally saved","");
        if(myCmiWindow != undefined)
          myCmiWindow.useFrontAsTop = poi3dConnector.getUserSettings().useFrontAsTop;
      }
      handleSelectionSettings();
    }//if (btnName == 'save')
  }//function uSetDlgCbk(btnName)
}//function showUSetDlg()

function showDocMgmtDlg(parentDlg,context)
{
  if (!docMgmtDlg)
  {
    docMgmtDlg = new DialogBox('docMgmtDlg', docMgmtDlgCbk, cmiCanvas);

    docMgmtDlg.selectedPoi3dDocument = null;
    docMgmtDlg.selectedWorkGroup1 = null;
    docMgmtDlg.selectedWorkGroup2 = null;
    docMgmtDlg.selectedCtlgEntry = null;
    docMgmtDlg.statusOutput = document.getElementById("docMgmtDlg_StateVal");
    docMgmtDlg.activeSection = "";
    docMgmtDlg.previewUpdated = false;
    docMgmtDlg.currGroupFeatures = null;
    docMgmtDlg.internalCatalog = poi3dConnector.getInternalCatalog();

    docMgmtDlg.onTabSelectionChange = function(sectionToActivate)
    {
      docMgmtDlg.activeSection = sectionToActivate;
      if(sectionToActivate == "docMgmtDlg_OwnDocSect")
      {
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_OwnDocSect","block");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_WGSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_GrpDocSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_CtlgSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_ReloadBut","none");
      }
      else if(sectionToActivate == "docMgmtDlg_WGSect")
      {
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_OwnDocSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_WGSect","block");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_GrpDocSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_CtlgSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_ReloadBut","inline-block");
      }
      else if(sectionToActivate == "docMgmtDlg_GrpDocSect")
      {
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_OwnDocSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_WGSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_GrpDocSect","block");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_CtlgSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_ReloadBut","none");
      }
      else
      {
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_OwnDocSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_WGSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_GrpDocSect","none");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_CtlgSect","block");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_ReloadBut","inline-block");
      }
      docMgmtDlg.statusOutput.innerHTML = "";
    }//docMgmtDlg.onTabSelectionChange = function(sectionToActivate)

    //Own doc tab ---------------------

    docMgmtDlg.onDocSelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        docMgmtDlg.selectedPoi3dDocument = selectObject[selectObject.selectedIndex].poi3dDoc;
        docMgmtDlg.updateDocProperties();
      }
    }//docMgmtDlg.onDocSelect

    docMgmtDlg.copyAccessUrlToClipboard = function()
    {
       navigator.clipboard.writeText(poi3dConnector.getCurrentDocumentAccessUrl(docMgmtDlg.selectedPoi3dDocument));
    }//docMgmtDlg.copyAccessUrlToClipboard

    docMgmtDlg.updateCurrentDocument = function()
    {
      if(docMgmtDlg.selectedPoi3dDocument != null)
      {
        docMgmtDlg.selectedPoi3dDocument.setTitle(document.getElementById("docMgmtDlg_DocTitleVal").value);
        docMgmtDlg.selectedPoi3dDocument.setDescription(document.getElementById("docMgmtDlg_DocDescInp").textContent);

        if(document.getElementById("docMgmtDlg_ZAxisToVal").checked == true)
          docMgmtDlg.selectedPoi3dDocument.setUseFrontAsTop(true);
        else
          docMgmtDlg.selectedPoi3dDocument.setUseFrontAsTop(false);

        if(document.getElementById("docMgmtDlg_isPubVal").checked == true)
          docMgmtDlg.selectedPoi3dDocument.setPublicState(true);
        else
          docMgmtDlg.selectedPoi3dDocument.setPublicState(false);

        if(document.getElementById("docMgmtDlg_AccessExpDateVal").value.length == 0)
          docMgmtDlg.selectedPoi3dDocument.setAccessExpDate("");
        else
          docMgmtDlg.selectedPoi3dDocument.setAccessExpDate(new Date(document.getElementById("docMgmtDlg_AccessExpDateVal").value).toISOString());

        if(docMgmtDlg.previewUpdated == true)
        {
          poi3dConnector.savePreviewToStorage(docMgmtDlg.selectedPoi3dDocument,document.getElementById("docMgmtDlg_PrevImg"));
          docMgmtDlg.previewUpdated = false;
        }

        docMgmtDlg.selectedPoi3dDocument.setDocState("changed");

        docMgmtDlg.statusOutput.innerHTML = "document locally updated";
      }
    }//docMgmtDlg.updateCurrentDocument

    docMgmtDlg.showCurrentDocumentLog  = function()
    {
      if(docMgmtDlg.selectedPoi3dDocument != null)
        showAccLogDlg(docMgmtDlg,docMgmtDlg.selectedPoi3dDocument,"docAccess","");
    }//docMgmtDlg.showLog

    docMgmtDlg.deleteCurrentDocument = function()
    {
      showVerifyDlg(docMgmtDlg,"deleteCurrentDocument",docMgmtDlg.selectedPoi3dDocument);
    }//docMgmtDlg.deleteCurrentDocument

    docMgmtDlg.onImgSelected = function()
    {
      if(imgOpenDlg.isImageSelected == true)
      {
        document.getElementById("docMgmtDlg_PrevImg").src = imgOpenDlg.imageElement.src;
        docMgmtDlg.previewUpdated = true;
      }
      else
      {
        var previewUrl = docMgmtDlg.selectedPoi3dDocument.getPreviewUrl(poi3dConnector.getPoi3dUser(),"read");
        if(previewUrl.length > 0)
          previewUrl = previewUrl+"&t=" + new Date().getTime();
        else
          previewUrl ="./CmiBitmaps/GenericTexture.jpg";

        document.getElementById('docMgmtDlg_PrevImg').src = previewUrl;
      }
    }

    docMgmtDlg.updateDocProperties = function()
    {
      if(docMgmtDlg.selectedPoi3dDocument != null)
      {
        document.getElementById("docMgmtDlg_DocTitleVal").value = docMgmtDlg.selectedPoi3dDocument.getTitle();
        document.getElementById("docMgmtDlg_DocDescInp").innerHTML = docMgmtDlg.selectedPoi3dDocument.getDescription();

        var previewUrl = docMgmtDlg.selectedPoi3dDocument.getPreviewUrl(poi3dConnector.getPoi3dUser(),"read");
        if(previewUrl.length > 0)
          previewUrl = previewUrl+"&t=" + new Date().getTime();
        else
          previewUrl ="./CmiBitmaps/GenericTexture.jpg";

        document.getElementById('docMgmtDlg_PrevImg').src = previewUrl;

        if(docMgmtDlg.selectedPoi3dDocument.getUseFrontAsTop() == false)
          document.getElementById("docMgmtDlg_ZAxisUpVal").checked = true;
        else
          document.getElementById("docMgmtDlg_ZAxisToVal").checked = true;

        if(docMgmtDlg.selectedPoi3dDocument.getPublicState() == false)
          document.getElementById("docMgmtDlg_isPubVal").checked = false;
        else
          document.getElementById("docMgmtDlg_isPubVal").checked = true;

        let expDate = docMgmtDlg.selectedPoi3dDocument.getAccessExpDate();
        if(expDate.length == 0)
          document.getElementById("docMgmtDlg_AccessExpDateVal").value = "";
        else
          document.getElementById("docMgmtDlg_AccessExpDateVal").value = expDate.split('T')[0];

        var showLogButton = document.getElementById("docMgmtDlg_ShLogBut");

        document.getElementById("docMgmtDlg_ShLogBut").value
      }
    }//docMgmtDlg.updateDocProperties = function()

    //Group doc tab ---------------------

    docMgmtDlg.onGroupSelect1 = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        docMgmtDlg.selectedWorkGroup1 = selectObject[selectObject.selectedIndex].poi3dWg;
        docMgmtDlg.updateDocGroupSelection();
      }
    }//docMgmtDlg.onGroupSelect1

    docMgmtDlg.addDocsToWg = function()
    {
      var poi3dDocument=null;
      var ownerModelSelection2 = document.getElementById("docMgmtDlg_DocSel2");
      docMgmtDlg.statusOutput.innerHTML = "";

      if(docMgmtDlg.selectedWorkGroup1 == null) return;

      for ( var i =0; i<ownerModelSelection2.options.length; i++)
      {
        if(ownerModelSelection2.options[i].selected == true)
        {
          poi3dDocument = ownerModelSelection2.options[i].poi3dDoc;
          if(docMgmtDlg.selectedWorkGroup1.getGroupDocuments().some(e => e.getDocId() === poi3dDocument.getDocId()) == false)
          {
            docMgmtDlg.selectedWorkGroup1.getGroupDocuments().push(ownerModelSelection2.options[i].poi3dDoc);
            docMgmtDlg.selectedWorkGroup1.setDocState("changed");
          }
        }
      }//for ( var i =0; i<ownerModelSelection2.options.length; i++)

      if(docMgmtDlg.selectedWorkGroup1.getDocState() == "changed")
        docMgmtDlg.selectedWorkGroup1.getGroupDocuments().sort(function(a, b)
        {
          let x = a.getTitle().toLowerCase();
          let y = b.getTitle().toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

      docMgmtDlg.updateDocGroupSelection();
    }//docMgmtDlg.addDocsToWg = function()

    docMgmtDlg.removeDocsFromWg = function()
    {
      var poi3dDocument=null;
      var wgModelSelection = document.getElementById("docMgmtDlg_WgDocSel");
      docMgmtDlg.statusOutput.innerHTML = "";

      if(docMgmtDlg.selectedWorkGroup1 == null) return;

      for ( var i =0; i<wgModelSelection.options.length; i++)
      {
        if(wgModelSelection.options[i].selected == true)
        {
          poi3dDocument = wgModelSelection.options[i].poi3dDoc;
          docMgmtDlg.selectedWorkGroup1.setGroupDocuments(docMgmtDlg.selectedWorkGroup1.getGroupDocuments().filter(function(item) {return item !== poi3dDocument}));
          docMgmtDlg.selectedWorkGroup1.setDocState("changed");
        }
      }//for ( var i =0; i<wgModelSelection.options.length; i++)

      if(docMgmtDlg.selectedWorkGroup1.getDocState() == "changed")
        docMgmtDlg.selectedWorkGroup1.getGroupDocuments().sort(function(a, b)
        {
          let x = a.getTitle().toLowerCase();
          let y = b.getTitle().toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

      docMgmtDlg.updateDocGroupSelection();
    }//docMgmtDlg.removeDocsFromWg = function()

    docMgmtDlg.resetWgDocs = function()
    {
      if(docMgmtDlg.selectedWorkGroup1 == null) return;

      docMgmtDlg.selectedWorkGroup1.resetDocumentListWithServerEntries(poi3dConnector.getPoi3dUser());
      docMgmtDlg.updateDocGroupSelection();
    }//docMgmtDlg.resetWgDocs

    docMgmtDlg.sendMessage = function()
    {
      var userSelection = document.getElementById("docMgmtDlg_UserSel");
      var userList = new Array();
      if(docMgmtDlg.selectedWorkGroup1 == null) return;

      for ( var i =0; i<userSelection.options.length; i++)
      {
        if(userSelection.options[i].selected == true)
        {
          userList.push(userSelection.options[i].groupUser);
        }
      }
      if(userList.length >0)
        showTxtInputDlg(docMgmtDlg,"SendMail",userList);
    }//docMgmtDlg.sendMessage

    docMgmtDlg.updateDocGroupSelection = function()
    {
      var modSelDlg_GrpDocSel = document.getElementById("docMgmtDlg_WgDocSel");
      var groupDocument = null;
      modSelDlg_GrpDocSel.options.length = 0;

      if(docMgmtDlg.selectedWorkGroup1 == null) return;

      for ( var i =0; i< docMgmtDlg.selectedWorkGroup1.getGroupDocuments().length; i++)
      {
        groupDocument = docMgmtDlg.selectedWorkGroup1.getGroupDocuments()[i];

        if(groupDocument.isOwnDoc(poi3dConnector.getPoi3dUser()))
        {
          var option = document.createElement("option");
          option.text = groupDocument.getTitle();
          option.poi3dDoc = groupDocument;
          modSelDlg_GrpDocSel.add(option);
        }
      }
    }//docMgmtDlg.updateDocGroupSelection = function()

    docMgmtDlg.updateDocSelLists = function()
    {
      var poi3dDocument=null;
      var modSelDlg_OwnDocSel = document.getElementById("docMgmtDlg_OwnDocSel");
      var userDocuments = poi3dConnector.getUserDocuments();
      var currentSelection1 = modSelDlg_OwnDocSel.selectedIndex;
      modSelDlg_OwnDocSel.options.length = 0;

      //owner documents
      for ( var i =0; i<userDocuments.length; i++)
      {
        poi3dDocument = userDocuments[i];

        var option = document.createElement("option");
        option.text = poi3dDocument.getTitle();
        option.poi3dDoc = poi3dDocument;
        modSelDlg_OwnDocSel.add(option);
      }

      if((currentSelection1 >= 0)&&(modSelDlg_OwnDocSel.options.length > currentSelection1))
        modSelDlg_OwnDocSel.selectedIndex = currentSelection1;

      if(userDocuments.length > 0)
      {
        docMgmtDlg.selectedPoi3dDocument = modSelDlg_OwnDocSel.options[modSelDlg_OwnDocSel.selectedIndex].poi3dDoc;
        docMgmtDlg.updateDocProperties();
      }

      //group documents
      poi3dDocument=null;
      var docSelection2 = document.getElementById("docMgmtDlg_DocSel2");
      var currentSelection2 = docSelection2.selectedIndex;
      docSelection2.options.length = 0;

      for ( var i =0; i<userDocuments.length; i++)
      {
        poi3dDocument = userDocuments[i];

        var option = document.createElement("option");
        option.text = poi3dDocument.getTitle();
        option.poi3dDoc = poi3dDocument;
        docSelection2.add(option);
      }

      //catalog documents
      poi3dDocument=null;
      var docSelection3 = document.getElementById("docMgmtDlg_DocSel3");
      var currentSelection3 = docSelection3.selectedIndex;
      docSelection3.options.length = 0;

      for ( var i =0; i<userDocuments.length; i++)
      {
        poi3dDocument = userDocuments[i];

        var option = document.createElement("option");
        option.text = poi3dDocument.getTitle();
        option.poi3dDoc = poi3dDocument;
        docSelection3.add(option);
      }
    }//docMgmtDlg.updateDocSelLists

    docMgmtDlg.updateWorkGroupSelectionList = function()
    {
      var poi3dWorkGroup=null;
      var wgSelection1 = document.getElementById("docMgmtDlg_WgSel1");
      var wgSelection2 = document.getElementById("docMgmtDlg_WgSel2");
      var optionEntry;
      var wgUserState = "";
      var userWorkGroups = poi3dConnector.getUserWorkGroups();
      var currentSelection1 = wgSelection1.selectedIndex;
      var currentSelection2 = wgSelection2.selectedIndex;

      wgSelection1.options.length = 0;
      wgSelection2.options.length = 0;


      for ( var i =0; i<userWorkGroups.length; i++)
      {
        poi3dWorkGroup = userWorkGroups[i];
        wgUserState = poi3dWorkGroup.getWorkGroupUserState(poi3dConnector.getPoi3dUser());

        if((poi3dWorkGroup.getWgState() != "deleted")&&(poi3dWorkGroup.getWgState() != "error"))
        {
          if(poi3dWorkGroup.getWgState() != "created") //add to wgSelection1 (exclude unsaved new work groups)
          {
            optionEntry = document.createElement("option");
            optionEntry.text = poi3dWorkGroup.getTitle();
            optionEntry.poi3dWg = poi3dWorkGroup;
            if(poi3dWorkGroup.isOwner(poi3dConnector.getPoi3dUser()))
            {
              optionEntry.style.fontStyle = "normal";
              optionEntry.style.fontWeight = "bold";
            }
            else
            {
              switch(wgUserState)
              {
                case "accepted":
                  optionEntry.style.fontStyle = "normal";
                  break;
                case "pending":
                  optionEntry.style.fontStyle = "italic";
                  break;
                case "rejected":
                  optionEntry.style.fontStyle = "italic";
                  break;
              }
            }

            wgSelection1.add(optionEntry);
          }//if(poi3dWorkGroup.wgState != "created")

          //add to wgSelection2
          optionEntry = document.createElement("option");
          optionEntry.text = poi3dWorkGroup.getTitle();
          optionEntry.poi3dWg = poi3dWorkGroup;
          if(poi3dWorkGroup.isOwner(poi3dConnector.getPoi3dUser()))
          {
            optionEntry.style.fontStyle = "normal";
            optionEntry.style.fontWeight = "bold";
          }
          else
          {
            switch(wgUserState)
            {
              case "accepted":
                optionEntry.style.fontStyle = "normal";
                break;
              case "pending":
                optionEntry.style.fontStyle = "italic";
                break;
              case "rejected":
                optionEntry.style.fontStyle = "italic";
                break;
            }
          }

          wgSelection2.add(optionEntry);
        }//if((poi3dWorkGroup.getWgState() != "deleted")&&(userWorkGroups.getWgState() != "error"))
      }//for ( var i =0; i<userWorkGroups.length; i++)

      if(userWorkGroups.length > 0)
      {
        let wgSelection1 = document.getElementById("docMgmtDlg_WgSel1");

        if((currentSelection1 >= 0)&&(wgSelection1.options.length > currentSelection1))
          wgSelection1.selectedIndex = currentSelection1;
        else
          wgSelection1.selectedIndex = 0;

        docMgmtDlg.onGroupSelect1(wgSelection1);

        let wgSelection2 = document.getElementById("docMgmtDlg_WgSel2");

        if((currentSelection2 >= 0)&&(wgSelection2.options.length > currentSelection2))
          wgSelection2.selectedIndex = currentSelection2;
        else
          wgSelection2.selectedIndex = 0;

        docMgmtDlg.onGroupSelect2(wgSelection2);
      }
      else
      {
        document.getElementById("docMgmtDlg_WgTtlVal").value ="";
        document.getElementById("docMgmtDlg_UserSel").options.length = 0;
        document.getElementById("docMgmtDlg_WgDocSel").options.length = 0;
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_DelWgBut",'none');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_UpdWgSetBut",'none');
      }

    }//docMgmtDlg.updateWorkGroupSelectionList

    //Group tab ---------------------

    docMgmtDlg.onGroupSelect2 = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        docMgmtDlg.selectedWorkGroup2 = selectObject[selectObject.selectedIndex].poi3dWg;
        document.getElementById("docMgmtDlg_WgTtlVal").value = docMgmtDlg.selectedWorkGroup2.getTitle();
        docMgmtDlg.updateUserList();
        if(docMgmtDlg.selectedWorkGroup2.isOwnGroup(poi3dConnector.getPoi3dUser()))
          Poi3dHelpers.canBeUsed("docMgmtDlg_WgFeatBut",true);
        else
          Poi3dHelpers.canBeUsed("docMgmtDlg_WgFeatBut",false);          
      }
    }

    docMgmtDlg.updateUserList = function()
    {
      var poi3dGroupUser=null;
      var wgUserSelection = document.getElementById("docMgmtDlg_UserSel");
      var userActionSection = document.getElementById("docMgmtDlg_UserAct");
      var optionEntry;
      wgUserSelection.options.length = 0;

      Poi3dHelpers.setDisplayStyle("docMgmtDlg_UpdWgSetBut",'none');
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_CrWgBut",'none');
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_DelWgBut",'none');
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_AcptWgInvitBut",'none');
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_RejWgInvitBut",'none');
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_RemWgInvitBut",'none');

      if(poi3dConnector.hasUserAuthorRights()==true)
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_CrWgBut",'inline-block');

      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      for ( var i =0; i<docMgmtDlg.selectedWorkGroup2.getGroupUsers().length; i++)
      {
        poi3dGroupUser = docMgmtDlg.selectedWorkGroup2.getGroupUsers()[i];
        if(poi3dGroupUser.userId != poi3dConnector.getCurrentUserId())
        {
          optionEntry = document.createElement("option");

          if(docMgmtDlg.selectedWorkGroup2.isOwnGroup(poi3dGroupUser))
            optionEntry.text = poi3dGroupUser.aliasName + " (" + poi3dGroupUser.firstName + " " + poi3dGroupUser.lastName +", owner)";
          else
            optionEntry.text = poi3dGroupUser.aliasName + " (" + poi3dGroupUser.firstName + " " + poi3dGroupUser.lastName +")";

          optionEntry.groupUser = poi3dGroupUser;

          switch(poi3dGroupUser.groupState)
          {
            case "accepted":
              optionEntry.style.fontStyle = "normal";
              optionEntry.style.textDecoration="none";
              break;
            case "pending":
              optionEntry.style.fontStyle = "italic";
              optionEntry.style.textDecoration="none";
              break;
            case "rejected":
              optionEntry.style.fontStyle = "normal";
              optionEntry.style.textDecoration="line-through";
              break;
            default:
              optionEntry.style.fontStyle = "italic";
              optionEntry.style.textDecoration="none";
              break;
          }

          wgUserSelection.add(optionEntry);
        }
      }//for ( var i =0; i<docMgmtDlg.selectedWorkGroup2.getGroupUsers().length; i++)

      if(docMgmtDlg.selectedWorkGroup2.isOwnGroup(poi3dConnector.getPoi3dUser()) == false)
      {
        userActionSection.style.display = 'none';

        switch(docMgmtDlg.selectedWorkGroup2.getWorkGroupUserState(poi3dConnector.getPoi3dUser()))
        {
          case "accepted":
            Poi3dHelpers.setDisplayStyle("docMgmtDlg_AcptWgInvitBut",'none');
            Poi3dHelpers.setDisplayStyle("docMgmtDlg_RejWgInvitBut",'inline-block');
            break;
          case "pending":
          case "rejected":
            Poi3dHelpers.setDisplayStyle("docMgmtDlg_AcptWgInvitBut",'inline-block');
            Poi3dHelpers.setDisplayStyle("docMgmtDlg_RejWgInvitBut",'none');
            Poi3dHelpers.setDisplayStyle("docMgmtDlg_RemWgInvitBut",'none');//ToDo
            break;
        }
      }
      else
      {
        userActionSection.style.display = 'block';

        Poi3dHelpers.setDisplayStyle("docMgmtDlg_UpdWgSetBut",'inline-block');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_CrWgBut",'inline-block');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_DelWgBut",'inline-block');
      }
    }//docMgmtDlg.updateUserList = function()

    docMgmtDlg.showUserSelectionToAdd = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      showUSelDlg(docMgmtDlg,"docMgmtDlg",docMgmtDlg.selectedWorkGroup2.getGroupUsers(),poi3dConnector.getUsers());
    }

    docMgmtDlg.addUsersToWg = function(userList)
    {
      var poi3dGroupUser=null;
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      for ( var i =0; i<userList.length; i++)
      {
        poi3dUser = userList[i];
        if(docMgmtDlg.selectedWorkGroup2.getGroupUsers().some(item => item.userId === poi3dUser.userId) == false)
        {
          var userEntry = new Poi3dUserSelectionEntry();
          userEntry.userId = poi3dUser.userId;
          userEntry.aliasName = poi3dUser.aliasName;
          userEntry.firstName = poi3dUser.firstName;
          userEntry.lastName = poi3dUser.lastName;
          userEntry.groupState = "pending";

          docMgmtDlg.selectedWorkGroup2.getGroupUsers().push(userEntry);
          if(docMgmtDlg.selectedWorkGroup2.getWgState() == "")
            docMgmtDlg.selectedWorkGroup2.setWgState("changed");
        }
      }
      docMgmtDlg.updateUserList();
    }//docMgmtDlg.addUsersToWg

    docMgmtDlg.removeUserFromWg = function()
    {
      var poi3dUser=null;
      var userSelection = document.getElementById("docMgmtDlg_UserSel");

      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      for ( var i =0; i<userSelection.options.length; i++)
      {
        if(userSelection.options[i].selected == true)
        {
          poi3dUser = userSelection.options[i].groupUser;
          docMgmtDlg.selectedWorkGroup2.setGroupUsers(docMgmtDlg.selectedWorkGroup2.getGroupUsers().filter(function(item) {return item.userId !== poi3dUser.userId}));
          docMgmtDlg.selectedWorkGroup2.setWgState("changed");
        }
      }
      docMgmtDlg.updateUserList();
    }//docMgmtDlg.removeUserFromWg

    docMgmtDlg.resetWg = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      docMgmtDlg.selectedWorkGroup2.resetUserListWithServerEntries();
      docMgmtDlg.updateUserList();
    }//docMgmtDlg.resetWg

    docMgmtDlg.updateCurrentWorkGroup = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      docMgmtDlg.selectedWorkGroup2.setTitle(document.getElementById("docMgmtDlg_WgTtlVal").value);
      if(docMgmtDlg.selectedWorkGroup2.getWgState() != "created")
        docMgmtDlg.selectedWorkGroup2.setWgState("changed");

      docMgmtDlg.updateWorkGroupSelectionList();
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(35),"");//"work group locally saved"
    }//docMgmtDlg.updateCurrentWorkGroup

    docMgmtDlg.deleteCurrentWorkGroup = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      if(docMgmtDlg.selectedWorkGroup2.getWgState() == "created")
        poi3dConnector.deleteWorkGroupFromUserLocally(docMgmtDlg.selectedWorkGroup2.getGroupId());
      else
        docMgmtDlg.selectedWorkGroup2.setWgState("deleted");

      docMgmtDlg.updateWorkGroupSelectionList();

      if(document.getElementById("docMgmtDlg_WgSel2").options.length >0)
      {
        docMgmtDlg.selectedWorkGroup1 = poi3dConnector.getUserWorkGroups()[0];
        document.getElementById("docMgmtDlg_WgSel2").selectedIndex = 0;
        docMgmtDlg.onGroupSelect2(document.getElementById("docMgmtDlg_WgSel2"));
      }
      else
      {
        document.getElementById("docMgmtDlg_WgTtlVal").value ="";
        document.getElementById("docMgmtDlg_UserSel").options.length = 0;
        document.getElementById("docMgmtDlg_WgDocSel").options.length = 0;
      }
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(36),"");//"work group locally deleted"
    }//docMgmtDlg.deleteCurrentWorkGroup

    docMgmtDlg.deleteWorkGroup = function()
    {
      showVerifyDlg(docMgmtDlg,'deleteWorkGroup',null);
    }

    docMgmtDlg.createWorkGroup = function()
    {
      if(poi3dConnector.isMaximumReached("maxWg"))
      {
        showMsgDlg(docMgmtDlg,poi3dConnector.getMessage(11));//"Max. number of work groups reached"
        return;
      }
      var newWorkGroup = new Poi3dWorkGroup();
      var grpSelList = document.getElementById("docMgmtDlg_WgSel2");
      var userProps = poi3dConnector.getUserProperties();

      newWorkGroup.setTitle("new WorkGroup");
      newWorkGroup.setOwnerName(userProps.aliasName);
      newWorkGroup.setOwnerId(userProps.userId);
      newWorkGroup.setWgState("created");
      newWorkGroup.addOwnerToUserList(poi3dConnector.getPoi3dUser());
      poi3dConnector.getUserWorkGroups().push(newWorkGroup);

      docMgmtDlg.updateWorkGroupSelectionList();
      docMgmtDlg.selectedWorkGroup1 = poi3dConnector.getUserWorkGroups()[0];
      grpSelList.selectedIndex = grpSelList.options.length-1;
      docMgmtDlg.onGroupSelect2(grpSelList);

      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(37),"");//"work group locally created"
    }//docMgmtDlg.createWorkGroup

    docMgmtDlg.setWorkGroupFeatures = function()
    {
      if((docMgmtDlg.selectedWorkGroup2 == null)||(document.getElementById("docMgmtDlg_WgFeatBut").disabled)) return;
      docMgmtDlg.currGroupFeatures = docMgmtDlg.selectedWorkGroup2.getGroupRights();
      showFeatDlg(docMgmtDlg,"groupSettings");
    }

    docMgmtDlg.joinCurrentWorkGroup = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      docMgmtDlg.selectedWorkGroup2.userJoin(poi3dConnector.getPoi3dUser());
      docMgmtDlg.updateUserList();
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(38),"");//"work group locally changed"
    }

    docMgmtDlg.leaveCurrentWorkGroup  = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      docMgmtDlg.selectedWorkGroup2.userLeave(poi3dConnector.getPoi3dUser());
      docMgmtDlg.updateUserList();
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(38),"");//"work group locally changed"
    }

    docMgmtDlg.removeCurrentWorkGroup  = function()
    {
      if(docMgmtDlg.selectedWorkGroup2 == null) return;

      //ToDo
      docMgmtDlg.selectedWorkGroup2.userLeave(poi3dConnector.getPoi3dUser());
      docMgmtDlg.updateUserList();
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(39),"");//"work group locally removed"
    }

    //Catalog tab ---------------------
    docMgmtDlg.updateCtlgEntrySelList = function()
    {
      var poi3dCatalog=null;
      var ctlgSelection = document.getElementById("docMgmtDlg_CtlgSel");
      var optionEntry;
      var ctlgEntries = poi3dConnector.getCatalogEntries(true);
      var currentIndex = ctlgSelection.selectedIndex;

      ctlgSelection.options.length = 0;

      for ( var i =0; i<ctlgEntries.length; i++)
      {
        poi3dCatalog = ctlgEntries[i];
        wgUserState = poi3dCatalog.getWorkGroupUserState(poi3dConnector.getPoi3dUser());

        if((poi3dCatalog.getWgState() != "deleted")&&(poi3dCatalog.getWgState() != "error"))
        {
          optionEntry = document.createElement("option");
          optionEntry.text = poi3dCatalog.getTitle();
          optionEntry.poi3dCtlg = poi3dCatalog;
          if(poi3dCatalog.isOwner(poi3dConnector.getPoi3dUser()))
          {
            optionEntry.style.fontStyle = "normal";
            optionEntry.style.fontWeight = "bold";
          }

          ctlgSelection.add(optionEntry);
        }//if((poi3dCatalog.getWgState() != "deleted")
      }//for ( var i =0; i<ctlgEntries.length; i++)

      if(ctlgSelection.options.length > 0)
      {
        if((currentIndex >= 0)&&(ctlgSelection.options.length > currentIndex))
          ctlgSelection.selectedIndex = currentIndex;
        else
          ctlgSelection.selectedIndex = 0;

        Poi3dHelpers.setDisplayStyle("docMgmtDlg_DelCtlgBut",'');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_UpdCtlgBut",'');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_PubCtlgBut",'');
      }
      else
      {
        document.getElementById("docMgmtDlg_CtlgTtlVal").value ="";
        document.getElementById("docMgmtDlg_CtlgDocSel").options.length = 0;
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_DelCtlgBut",'none');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_UpdCtlgBut",'none');
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_PubCtlgBut",'none');
      }

      docMgmtDlg.onCtlgEntrySelect(ctlgSelection);
    };//docMgmtDlg.updateCtlgEntrySelList

    docMgmtDlg.updateCtlgEntryDocList = function()
    {
      var ctlgDocSel = document.getElementById("docMgmtDlg_CtlgDocSel");
      var ctlgDocument = null;
      var optionEntry;
      ctlgDocSel.options.length = 0;

      if(docMgmtDlg.selectedCtlgEntry == null) return;

      for ( var i =0; i< docMgmtDlg.selectedCtlgEntry.getGroupDocuments().length; i++)
      {
        groupDocument = docMgmtDlg.selectedCtlgEntry.getGroupDocuments()[i];

        optionEntry = document.createElement("option");
        optionEntry.text = groupDocument.getTitle();
        optionEntry.poi3dDoc = groupDocument;
        ctlgDocSel.add(optionEntry);
      }
    }//docMgmtDlg.updateCtlgEntryDocList = function()

    docMgmtDlg.onCtlgEntrySelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        docMgmtDlg.selectedCtlgEntry = selectObject[selectObject.selectedIndex].poi3dCtlg;
        document.getElementById("docMgmtDlg_CtlgTtlVal").value = docMgmtDlg.selectedCtlgEntry.getTitle();
        docMgmtDlg.updateCtlgEntryDocList();
      }
      else
      {
        docMgmtDlg.selectedCtlgEntry = null;
        document.getElementById("docMgmtDlg_CtlgTtlVal").value ="";
        document.getElementById("docMgmtDlg_CtlgDocSel").options.length = 0;
      }
    }

    docMgmtDlg.addDocsToCtlg = function()
    {
      var poi3dDocument=null;
      var docSelection3 = document.getElementById("docMgmtDlg_DocSel3");
      docMgmtDlg.statusOutput.innerHTML = "";

      if(docMgmtDlg.selectedCtlgEntry == null) return;

      for ( var i =0; i<docSelection3.options.length; i++)
      {
        if(docSelection3.options[i].selected == true)
        {
          poi3dDocument = docSelection3.options[i].poi3dDoc;
          if(docMgmtDlg.selectedCtlgEntry.getGroupDocuments().some(e => e.getDocId() === poi3dDocument.getDocId()) == false)
          {
            docMgmtDlg.selectedCtlgEntry.getGroupDocuments().push(docSelection3.options[i].poi3dDoc);
            docMgmtDlg.selectedCtlgEntry.setDocState("changed");
          }
        }
      }//for ( var i =0; i<docSelection3.options.length; i++)

      if(docMgmtDlg.selectedCtlgEntry.getDocState() == "changed")
        docMgmtDlg.selectedCtlgEntry.getGroupDocuments().sort(function(a, b)
        {
          let x = a.getTitle().toLowerCase();
          let y = b.getTitle().toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

      docMgmtDlg.updateCtlgEntryDocList();
    };//docMgmtDlg.addDocsToCtlg

    docMgmtDlg.removeDocsFromCtlg = function()
    {
      var poi3dDocument=null;
      var ctlgDocSelection = document.getElementById("docMgmtDlg_CtlgDocSel");
      docMgmtDlg.statusOutput.innerHTML = "";

      if(docMgmtDlg.selectedCtlgEntry == null) return;

      for ( var i =0; i<ctlgDocSelection.options.length; i++)
      {
        if(ctlgDocSelection.options[i].selected == true)
        {
          poi3dDocument = ctlgDocSelection.options[i].poi3dDoc;
          docMgmtDlg.selectedCtlgEntry.setGroupDocuments(docMgmtDlg.selectedCtlgEntry.getGroupDocuments().filter(function(item) {return item !== poi3dDocument}));
          docMgmtDlg.selectedCtlgEntry.setDocState("changed");
        }
      }//for ( var i =0; i<ctlgDocSelection.options.length; i++)

      if(docMgmtDlg.selectedCtlgEntry.getDocState() == "changed")
        docMgmtDlg.selectedCtlgEntry.getGroupDocuments().sort(function(a, b)
        {
          let x = a.getTitle().toLowerCase();
          let y = b.getTitle().toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

      docMgmtDlg.updateCtlgEntryDocList();

    };//docMgmtDlg.removeDocsFromCtlg

    docMgmtDlg.resetCtlgDocs = function()
    {
      if(docMgmtDlg.selectedCtlgEntry == null) return;

      docMgmtDlg.selectedCtlgEntry.resetDocumentListWithServerEntries(poi3dConnector.getPoi3dUser());
      docMgmtDlg.updateCtlgEntryDocList();
    };//docMgmtDlg.resetCtlgDocs

    docMgmtDlg.updateCurrentCatalog = function()
    {
      if(docMgmtDlg.selectedCtlgEntry == null) return;

      docMgmtDlg.selectedCtlgEntry.setTitle(document.getElementById("docMgmtDlg_CtlgTtlVal").value);
      if(docMgmtDlg.selectedCtlgEntry.getWgState() != "created")
        docMgmtDlg.selectedCtlgEntry.setWgState("changed");

      docMgmtDlg.updateCtlgEntrySelList();
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(35),"");//"work group locally saved"
    };//docMgmtDlg.updateCurrCtlgEntry

    docMgmtDlg.exportCatalog = function()
    {
      let ctlgEntries = poi3dConnector.getCatalogEntries(true);
      if(ctlgEntries.length > 0)
        showMultSelDlg(docMgmtDlg,"exportCatalog",ctlgEntries,null);
    };//docMgmtDlg.exportCatalog

    docMgmtDlg.deleteCtlgEntry = function()
    {
      showVerifyDlg(docMgmtDlg,'deleteCtlgEntry',null);
    }

    docMgmtDlg.createCtlgEntry = function()
    {
      if(poi3dConnector.isMaximumReached("maxWg"))
      {
        showMsgDlg(docMgmtDlg,poi3dConnector.getMessage(11));//"Max. number of work groups reached"
        return;
      }
      var ctlgSelList = document.getElementById("docMgmtDlg_CtlgSel");

      docMgmtDlg.internalCatalog.createEntry(poi3dConnector.getPoi3dUser());

      docMgmtDlg.updateCtlgEntrySelList();
      docMgmtDlg.selectedCtlgEntry = poi3dConnector.getCatalogEntries(true)[0];
      ctlgSelList.selectedIndex = ctlgSelList.options.length-1;
      docMgmtDlg.onCtlgEntrySelect(ctlgSelList);

      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(37),"");//"work group locally created"
    };//docMgmtDlg.createCtlgEntry

    docMgmtDlg.deleteCurrCtlgEntry = function()
    {
      if(docMgmtDlg.selectedCtlgEntry == null) return;
      docMgmtDlg.internalCatalog.deleteEntry(docMgmtDlg.selectedCtlgEntry);

      docMgmtDlg.updateCtlgEntrySelList();
      docMgmtDlg.onStatusUpdate(poi3dConnector.getMessage(36),"");//"work group locally deleted"
    };//docMgmtDlg.deleteCurrCtlgEntry

    docMgmtDlg.downloadCtlgHelp = function()
    {
      let cfg = poi3dConnector.getPortalConfiguration();
      window.open(cfg.downloadDir+'/Catalog-Export.pdf','_blank');
    };//docMgmtDlg.downloadCtlgHelp

    docMgmtDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      docMgmtDlg.statusOutput.innerHTML = textToDisplay;
      switch(currentStatus)
      {
        case "loadWorkGroupSuccess":
          docMgmtDlg.initSelections();
          break;
        case "deleteDocumentSuccess":
        case "saveUserDocumentsSuccess":
          docMgmtDlg.updateDocSelLists();
          docMgmtDlg.updateWorkGroupSelectionList();
          docMgmtDlg.updateCtlgEntrySelList();
          break;
        case "updateWorkGroupSuccess":
          docMgmtDlg.updateWorkGroupSelectionList();
          docMgmtDlg.updateCtlgEntrySelList();
          docMgmtDlg.updateUserList();
          break;
      }
    }//docMgmtDlg.onStatusUpdate

    docMgmtDlg.initSelections = function()
    {
      docMgmtDlg.updateDocSelLists();
      docMgmtDlg.updateWorkGroupSelectionList();
      docMgmtDlg.updateCtlgEntrySelList();
      docMgmtDlg.updateUserList();
    }

    Poi3dHelpers.setDisplayStyle("docMgmtDlg_OwnDocSect","block");
    poi3dConnector.registerCallback("mgmtDlgStatusUpdate",docMgmtDlg.onStatusUpdate);
  }//if (!docMgmtDlg)

  if(poi3dConnector.getPoi3dUser() == null)
  {
    showMsgDlg(docMgmtDlg,poi3dConnector.getMessage(3));
    return;
  }
  if(context == "talkflow")
  {
    Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabOwnDocLab","none");
    Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabGrpDocLab","none");
    Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabCtlgLab","none");
    docMgmtDlg.onTabSelectionChange("docMgmtDlg_WGSect");
  }
  else
  {
    let uType = poi3dConnector.getPoi3dUser().getUserType();
    if((uType == "p")||(uType == "a"))
    {
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabCtlgLab","");
    }
    else
    {
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabCtlgLab","none");
    }
  
    if(poi3dConnector.getUserWorkGroups().length > 0)
    {
      docMgmtDlg.selectedWorkGroup1 = poi3dConnector.getUserWorkGroups()[0];
      docMgmtDlg.updateDocGroupSelection();
  
      docMgmtDlg.selectedWorkGroup2 = poi3dConnector.getUserWorkGroups()[0];
      document.getElementById("docMgmtDlg_WgTtlVal").value = docMgmtDlg.selectedWorkGroup2.getTitle();
      docMgmtDlg.updateUserList();
    }
    if(poi3dConnector.hasUserAuthorRights() == false)
    {
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabOwnDocLab","none");
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabGrpDocLab","none");
  
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_ReloadBut","inline-block");
  
      let nrOfUserDocuments = 0;
      if(poi3dConnector.checkUserAccess() == true)
        nrOfUserDocuments = poi3dConnector.getUserDocuments().length;
  
      if(nrOfUserDocuments > 0)
      {
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_OwnDocSect","block");
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabOwnDocLab","inline-block");
        document.getElementById("docMgmtDlg_TabOwnDoc").checked = true;
        docMgmtDlg.onTabSelectionChange("docMgmtDlg_OwnDocSect");
      }
      else
      {
        Poi3dHelpers.setDisplayStyle("docMgmtDlg_WGSect","block");
        document.getElementById("docMgmtDlg_TabWrkGrp").checked = true;
        docMgmtDlg.onTabSelectionChange("docMgmtDlg_WGSect");
      }
    }
    else
    {
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabOwnDocLab","inline-block");
      Poi3dHelpers.setDisplayStyle("docMgmtDlg_TabGrpDocLab","inline-block");
  
      document.getElementById("docMgmtDlg_TabOwnDoc").checked = true;
      docMgmtDlg.onTabSelectionChange("docMgmtDlg_OwnDocSect");
    }
  }//if(context == "talkflow")else
  docMgmtDlg.initSelections();
  docMgmtDlg.showDialog(parentDlg);

  function docMgmtDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "reload":
        docMgmtDlg.dialog.style.display = 'block';
        poi3dConnector.getPoi3dUser().reLoadWorkGroups();
        poi3dConnector.updateDocumentUsers();
        poi3dConnector.reloadCatalogs();
        break;
      case "close":
        break;
      case "save":
        docMgmtDlg.dialog.style.display = 'block';
        if(docMgmtDlg.activeSection == "docMgmtDlg_OwnDocSect")
          poi3dConnector.saveDocumentListToStorage("docMgmtDlg");
        else if(docMgmtDlg.activeSection == "docMgmtDlg_GrpDocSect")
          poi3dConnector.saveWorkGroupDocsListToStorage("docMgmtDlg");
        else if(docMgmtDlg.activeSection == "docMgmtDlg_WGSect")
          poi3dConnector.saveWorkGroupsToStorage("docMgmtDlg");
        else if(docMgmtDlg.activeSection == "docMgmtDlg_CtlgSect")
          poi3dConnector.saveCatalogEntriesToStorage("docMgmtDlg");

        poi3dConnector.updateDocumentUsers();
        break;
      default:
        docMgmtDlg.dialog.style.display = 'block';
        break;
    }
  }
}//function showDocMgmtDlg()

function showModSelDlg(parentDlg,context)
{
  if (!modSelDlg)
  {
    modSelDlg = new DialogBox('modSelDlg', modSelDlgCbk, cmiCanvas);
    modSelDlg.selectedPoi3dDocument = null;
    modSelDlg.selectedWorkGroup = null;
    modSelDlg.selectedCatalogEntry = null;
    modSelDlg.context = context;
    modSelDlg.ActiveSection = "";

    modSelDlg.onTabSelectionChange = function(sectionToActivate)
    {
      modSelDlg.ActiveSection = sectionToActivate;
      if(sectionToActivate == "modSelDlg_OwnDocSection")
      {
        document.getElementById("modSelDlg_OwnDocTabVal").checked = true;
        Poi3dHelpers.setDisplayStyle("modSelDlg_OwnDocSection","block");
        Poi3dHelpers.setDisplayStyle("modSelDlg_WgDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_CtlgDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_SplDocSection","none");

        if(document.getElementById("modSelDlg_OwnDocSel").options.length > 0)
        {
          let sel = document.getElementById("modSelDlg_OwnDocSel");
          sel.selectedIndex = 0;
          modSelDlg.selectedPoi3dDocument = sel[0].poi3dDoc;
        }
        else
          modSelDlg.selectedPoi3dDocument = null;

        modSelDlg.selectedWorkGroup = null;
        modSelDlg.selectedCatalogEntry = null;
      }
      else if(sectionToActivate == "modSelDlg_WgDocSection")
      {
        document.getElementById("modSelDlg_WgDocTabVal").checked = true;
        Poi3dHelpers.setDisplayStyle("modSelDlg_OwnDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_WgDocSection","block");
        Poi3dHelpers.setDisplayStyle("modSelDlg_CtlgDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_SplDocSection","none");

        if(document.getElementById("modSelDlg_GrpSel").options.length > 0)
        {
          let sel = document.getElementById("modSelDlg_GrpSel");
          sel.selectedIndex = 0;
          modSelDlg.selectedWorkGroup = sel[0].poi3dWg;

          if(document.getElementById("modSelDlg_GrpDocSel").options.length > 0)
          {
            let sel = document.getElementById("modSelDlg_GrpDocSel");
            sel.selectedIndex = 0;
            modSelDlg.selectedPoi3dDocument = sel[0].poi3dDoc;
          }
          else
            modSelDlg.selectedPoi3dDocument = null;
        }
        else
        {
          modSelDlg.selectedWorkGroup = null;
          modSelDlg.selectedPoi3dDocument = null;
        }
        modSelDlg.selectedCatalogEntry = null;
      }
      else if(sectionToActivate == "modSelDlg_CtlgDocSection")
      {
        document.getElementById("modSelDlg_CtlgDocTabVal").checked = true;
        Poi3dHelpers.setDisplayStyle("modSelDlg_OwnDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_WgDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_CtlgDocSection","block");
        Poi3dHelpers.setDisplayStyle("modSelDlg_SplDocSection","none");

        if(document.getElementById("modSelDlg_CtlgEntrySel").options.length > 0)
        {
          let sel = document.getElementById("modSelDlg_CtlgEntrySel");
          sel.selectedIndex = 0;
          modSelDlg.selectedCatalogEntry = sel[0].poi3dCtlgEntry;

          if(document.getElementById("modSelDlg_CtlgDocSel").options.length > 0)
          {
            let sel = document.getElementById("modSelDlg_CtlgDocSel");
            sel.selectedIndex = 0;
            modSelDlg.selectedPoi3dDocument = sel[0].poi3dDoc;
          }
          else
            modSelDlg.selectedPoi3dDocument = null;
        }
        else
        {
          modSelDlg.selectedWorkGroup = null;
          modSelDlg.selectedPoi3dDocument = null;
        }

        modSelDlg.selectedWorkGroup = null;
      }
      else if(sectionToActivate == "modSelDlg_SplDocSection")
      {
        document.getElementById("modSelDlg_SplDocTabVal").checked = true;
        Poi3dHelpers.setDisplayStyle("modSelDlg_OwnDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_WgDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_CtlgDocSection","none");
        Poi3dHelpers.setDisplayStyle("modSelDlg_SplDocSection","block");

        if(document.getElementById("modSelDlg_SplDocSel").options.length > 0)
        {
          let sel = document.getElementById("modSelDlg_SplDocSel");
          sel.selectedIndex = 0;
          modSelDlg.selectedPoi3dDocument = sel[0].poi3dDoc;
        }
        else
          modSelDlg.selectedPoi3dDocument = null;
      }
      modSelDlg.updateProperties();

    };//modSelDlg.onTabSelectionChange

    modSelDlg.onSelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        modSelDlg.selectedWorkGroup = null;
        modSelDlg.selectedPoi3dDocument = selectObject[selectObject.selectedIndex].poi3dDoc;
        modSelDlg.updateProperties();
      }
    }

    modSelDlg.onGrpDocSelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        modSelDlg.selectedPoi3dDocument = selectObject[selectObject.selectedIndex].poi3dDoc;
        modSelDlg.updateProperties();
      }
    }

    modSelDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      switch(currentStatus)
      {
        case "loadWorkGroupSuccess":
          modSelDlg.initSelections();
          break;
      }
    }//modSelDlg.onStatusUpdate

    modSelDlg.onCtlgEntrySelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        modSelDlg.selectedCatalogEntry = selectObject[selectObject.selectedIndex].poi3dCtlgEntry;
        modSelDlg.updateDocCtlgEntrySelection();
        if(modSelDlg.selectedCatalogEntry.getGroupDocuments().length >0)
        {
          modSelDlg.selectedPoi3dDocument = modSelDlg.selectedCatalogEntry.getGroupDocuments()[0]
          modSelDlg.updateProperties();
        }
      }
    }

    modSelDlg.onCtlgDocSelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        modSelDlg.selectedPoi3dDocument = selectObject[selectObject.selectedIndex].poi3dDoc;
        modSelDlg.updateProperties();
      }
    }

    modSelDlg.onGroupSelect = function(selectObject)
    {
      if(selectObject.options.length > 0)
      {
        modSelDlg.selectedWorkGroup = selectObject[selectObject.selectedIndex].poi3dWg;
        modSelDlg.updateDocGroupSelection();
        if(modSelDlg.selectedWorkGroup.getGroupDocuments().length >0)
        {
          modSelDlg.selectedPoi3dDocument = modSelDlg.selectedWorkGroup.getGroupDocuments()[0]
          modSelDlg.updateProperties();
        }
      }
    }

    modSelDlg.updateDocGroupSelection = function()
    {
      var modSelDlg_GrpDocSel = document.getElementById("modSelDlg_GrpDocSel");
      var groupDocument = null;
      modSelDlg_GrpDocSel.options.length = 0;

      for ( var i =0; i< modSelDlg.selectedWorkGroup.getGroupDocuments().length; i++)
      {
        groupDocument = modSelDlg.selectedWorkGroup.getGroupDocuments()[i];

        var option = document.createElement("option");
        option.text = groupDocument.getTitle();
        option.poi3dDoc = groupDocument;
        if(groupDocument.isOwnDoc(poi3dConnector.getPoi3dUser()))
          option.style.fontWeight = "bold";
        modSelDlg_GrpDocSel.add(option);
      }
    }

    modSelDlg.updateDocCtlgEntrySelection = function()
    {
      var modSelDlg_CtlgDocSel = document.getElementById("modSelDlg_CtlgDocSel");
      var catalogDocument = null;
      modSelDlg_CtlgDocSel.options.length = 0;

      if(modSelDlg.selectedCatalogEntry.isExternalGroup() == true)
        document.getElementById("modSelDlg_CtlgSrcVal").innerHTML = modSelDlg.selectedCatalogEntry.getCatalog().getTitle();
      else
        document.getElementById("modSelDlg_CtlgSrcVal").innerHTML = "internal";

      for ( var i =0; i< modSelDlg.selectedCatalogEntry.getGroupDocuments().length; i++)
      {
        catalogDocument = modSelDlg.selectedCatalogEntry.getGroupDocuments()[i];

        var option = document.createElement("option");
        option.text = catalogDocument.getTitle();
        option.poi3dDoc = catalogDocument;
        modSelDlg_CtlgDocSel.add(option);
      }
    }

    modSelDlg.updateProperties = function()
    {
      if(modSelDlg.selectedPoi3dDocument != null)
      {
        document.getElementById("modSelDlg_DocTitleVal").value = modSelDlg.selectedPoi3dDocument.getTitle();
        document.getElementById("modSelDlg_DocDescVal").innerHTML = modSelDlg.selectedPoi3dDocument.getDescription();
        document.getElementById("modSelDlg_OwnerVal").innerHTML = modSelDlg.selectedPoi3dDocument.getOwnerName();

        var previewUrl = modSelDlg.selectedPoi3dDocument.getPreviewUrl(poi3dConnector.getPoi3dUser(),"read");

        if(modSelDlg.selectedPoi3dDocument.getDocLocation() == 0)
        {
          if(previewUrl.length > 0)
            previewUrl = previewUrl+"&t=" + new Date().getTime();
        }

        if(previewUrl.length > 0)
        {
          document.getElementById("modSelDlg_PvImg").src = previewUrl;
        }
        else
          document.getElementById("modSelDlg_PvImg").src="./CmiBitmaps/GenericTexture.jpg"

      }
      else
      {
        document.getElementById("modSelDlg_DocTitleVal").value = "";
        document.getElementById("modSelDlg_DocDescVal").innerHTML = "";
        document.getElementById("modSelDlg_OwnerVal").innerHTML = "";
        document.getElementById("modSelDlg_PvImg").src="./CmiBitmaps/GenericTexture.jpg";
      }
    }
    modSelDlg.openImageGallery = function(docArea)
    {
      switch(docArea)
      {
        case "ownModSel":
          showImgGalDlg(modSelDlg,modSelDlg.context,poi3dConnector.getUserDocuments(),null);
          break;
        case "grpModSel":
          showImgGalDlg(modSelDlg,modSelDlg.context,modSelDlg.selectedWorkGroup.getGroupDocuments(),modSelDlg.selectedWorkGroup);
          break;
        case "catModSel":
          showImgGalDlg(modSelDlg,modSelDlg.context,modSelDlg.selectedCatalogEntry.getGroupDocuments(),modSelDlg.selectedCatalogEntry);
          break;
        case "splModSel":
          showImgGalDlg(modSelDlg,modSelDlg.context,poi3dConnector.getSampleDocs(),null);
          break;
      }
      modSelDlg.dialog.style.display = 'none';
    }

    modSelDlg.initSelections = function()
    {
      //sample models
      var modSelDlg_SplDocSel = document.getElementById("modSelDlg_SplDocSel");
      var demoModels = poi3dConnector.getSampleDocs();

      modSelDlg_SplDocSel.options.length = 0;

      for ( var i =0; i< demoModels.length; i++)
      {
        var option = document.createElement("option");
        option.text = demoModels[i].getTitle();
        option.poi3dDoc = demoModels[i];
        modSelDlg_SplDocSel.add(option);
      }

      //user models
      var modSelDlg_OwnDocSel = document.getElementById("modSelDlg_OwnDocSel");
      var userDocuments = new Array();

      modSelDlg_OwnDocSel.options.length = 0;

      if(poi3dConnector.checkUserAccess() == true)
      {
        userDocuments = poi3dConnector.getUserDocuments();
        for ( var i =0; i< userDocuments.length; i++)
        {
          var option = document.createElement("option");
          option.text = userDocuments[i].getTitle();
          option.poi3dDoc = userDocuments[i];
          modSelDlg_OwnDocSel.add(option);
        }
      }
      if(userDocuments.length == 0)
        Poi3dHelpers.setDisplayStyle("modSelDlg_OwnDocTabLab","none");
      else
        Poi3dHelpers.setDisplayStyle("modSelDlg_OwnDocTabLab","");

      //work groups
      var modSelDlg_GrpSel = document.getElementById("modSelDlg_GrpSel");
      var userWorkGroups = new Array();

      modSelDlg_GrpSel.options.length = 0;

      if(poi3dConnector.checkUserAccess() == true)
      {
        userWorkGroups = poi3dConnector.getUserWorkGroups();
        for ( var i =0; i< userWorkGroups.length; i++)
        {
          if((userWorkGroups[i].getWgState() != "rejected")&&(userWorkGroups[i].getWgState() != "deleted")&&(userWorkGroups[i].getWgState() != "error"))
          {
            var option = document.createElement("option");
            option.text = userWorkGroups[i].getTitle();
            option.poi3dWg = userWorkGroups[i];

            if(userWorkGroups[i].isOwner(poi3dConnector.getPoi3dUser()))
              option.style.fontWeight = "bold";

            modSelDlg_GrpSel.add(option);
          }
        }
        //work group models
        if(userWorkGroups.length >0)
        {
          modSelDlg.selectedWorkGroup = userWorkGroups[0];
          modSelDlg.updateDocGroupSelection();
        }
      }

      if(userWorkGroups.length == 0)
        Poi3dHelpers.setDisplayStyle("modSelDlg_WgDocTabLab","none");
      else
      {
        Poi3dHelpers.setDisplayStyle("modSelDlg_WgDocTabLab","");
        modSelDlg.selectedWorkGroup = userWorkGroups[0];
        modSelDlg.updateDocGroupSelection();
      }

      //catalogs
      var modSelDlg_CtlgEntrySel = document.getElementById("modSelDlg_CtlgEntrySel");
      var catalogEntries = poi3dConnector.getCatalogEntries(false);

      modSelDlg_CtlgEntrySel.options.length = 0;

      for ( var i =0; i< catalogEntries.length; i++)
      {
        var option = document.createElement("option");
        option.text = catalogEntries[i].getTitle();
        option.poi3dCtlgEntry = catalogEntries[i];

        modSelDlg_CtlgEntrySel.add(option);
      }

      //catalog entry models
      if(catalogEntries.length == 0)
        Poi3dHelpers.setDisplayStyle("modSelDlg_CtlgDocTabLab","none");
      else
      {
        Poi3dHelpers.setDisplayStyle("modSelDlg_CtlgDocTabLab","");
        modSelDlg.selectedCatalogEntry = catalogEntries[0];
        modSelDlg.updateDocCtlgEntrySelection();
      }

      if(poi3dConnector.checkUserAccess()== false)
        Poi3dHelpers.setDisplayStyle("modSelDlg_ReloadBut",'none');
      else
        Poi3dHelpers.setDisplayStyle("modSelDlg_ReloadBut",'inline-block');

      if(modSelDlg_OwnDocSel.options.length > 0)
        modSelDlg.onTabSelectionChange("modSelDlg_OwnDocSection");
      else
        modSelDlg.onTabSelectionChange("modSelDlg_SplDocSection");

    }//modSelDlg.initSelections

    poi3dConnector.registerCallback("docSelDlgStatusUpdate",modSelDlg.onStatusUpdate);
  }//if (!modSelDlg)

  //initialize dialog
  modSelDlg.context = context;
  modSelDlg.initSelections();

  //show dialog
  modSelDlg.showDialog(parentDlg);

  function modSelDlgCbk(btnName)
  {
    if(btnName == "reload")
    {
      modSelDlg.dialog.style.display = 'block';
      if(poi3dConnector.checkUserAccess() == true)
        poi3dConnector.getPoi3dUser().reLoadWorkGroups();
      poi3dConnector.reloadCatalogs();
      return;
    }

    if(modSelDlg.selectedPoi3dDocument == null) return;

    switch(btnName)
    {
      case "open":
        if(modSelDlg.selectedPoi3dDocument != null)
        {
          if(modSelDlg.context == "secondary")
            Poi3dDocumentLoader.loadSecondaryDocument(myCmiWindow,modSelDlg.selectedPoi3dDocument);
          else
          {
            Poi3dDocumentLoader.loadPrimaryDocument(myCmiWindow,modSelDlg.selectedPoi3dDocument);
            if(modSelDlg.ActiveSection == "modSelDlg_WgDocSection")
              poi3dConnector.setCurrentWgOrCatalog(modSelDlg.selectedWorkGroup);
            else if(modSelDlg.ActiveSection == "modSelDlg_CtlgDocSection")
              poi3dConnector.setCurrentWgOrCatalog(modSelDlg.selectedCatalogEntry);
            else
              poi3dConnector.setCurrentWgOrCatalog(null);
          }
        }
        break;
      case "close":
        break;
    }
  }//function modSelDlgCbk(btnName)
}//function showModSelDlg()

function showHdlFattDlg(parentDlg,context,entity)
{
  if (!hdlFattDlg)
  {
    hdlFattDlg = new DialogBox('hdlFattDlg', hdlFattDlgCbk, cmiCanvas);
    hdlFattDlg.selectedFileAttachment = null;
    hdlFattDlg.entRef = null;

    hdlFattDlg.onSelect = function(selectObject)
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();
      if(selectObject.options.length > 0)
      {
        hdlFattDlg.selectedFileAttachment = fileAttachments[selectObject.selectedIndex];
        hdlFattDlg.updateProperties();
      }
    }

    hdlFattDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      switch(currentStatus)
      {
        case "loadFileAttachmentsSuccess":
          hdlFattDlg.initialize();
          break;
      }
    }//hdlFattDlg.onStatusUpdate

    hdlFattDlg.updateProperties = function()
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();

      if(fileAttachments.length == 0) return;

      if(hdlFattDlg.selectedFileAttachment != null)
      {
        document.getElementById("hdlFattDlg_FlNmVal").innerHTML = hdlFattDlg.selectedFileAttachment.getFileName();
        document.getElementById("hdlFattDlg_FlTitleVal").value = hdlFattDlg.selectedFileAttachment.getTitle();
        document.getElementById("hdlFattDlg_DescVal").innerHTML = hdlFattDlg.selectedFileAttachment.getDesc();
      }
      poi3dConnector.getLeftDocument().getFileAttachmentObject().setLocalChangeFlag(true);
    }

    hdlFattDlg.saveCurrent = function()
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();

      if(fileAttachments.length == 0) return;

      let val = document.getElementById("hdlFattDlg_FlTitleVal").value;
      hdlFattDlg.selectedFileAttachment.setTitle(val);
      val = document.getElementById("hdlFattDlg_DescVal").textContent;
      hdlFattDlg.selectedFileAttachment.setDesc(val);
      poi3dConnector.getLeftDocument().getFileAttachmentObject().setLocalChangeFlag(true);

      hdlFattDlg.initialize();
    };

    hdlFattDlg.deleteCurrent = function()
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();

      if(fileAttachments.length == 0) return;

      if(poi3dConnector.hasUserAuthorRights() == false)
        showMsgDlg(hdlFattDlg,poi3dConnector.getMessage(4));//"You must be logged in as an author to use this function"
      else
      {
        for (var i=0; i<fileAttachments.length; i++)
        {
          if(fileAttachments[i].getId() == hdlFattDlg.selectedFileAttachment.getId())
          {
            fileAttachments = fileAttachments.filter(function(item) {return item !== fileAttachments[i]});
            i = fileAttachments.length;
          }
        }
      }
      poi3dConnector.getLeftDocument().setFileAttachments(fileAttachments);
      hdlFattDlg.initialize();
    };//hdlFattDlg.deleteCurrent

    hdlFattDlg.downloadCurrent = function()
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();
      if(fileAttachments.length == 0) return;

      if(hdlFattDlg.selectedFileAttachment != null)
        hdlFattDlg.selectedFileAttachment.downloadFile(poi3dConnector.getPoi3dUser());
    };//hdlFattDlg.downloadCurrent

    hdlFattDlg.showCurrentFatchLog = function()
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();
      if(fileAttachments.length == 0) return;

      if(hdlFattDlg.selectedFileAttachment != null)
        showAccLogDlg(hdlFattDlg,poi3dConnector.getLeftDocument(),"fatchAccess",hdlFattDlg.selectedFileAttachment.getFileName());
    }

    hdlFattDlg.initialize = function()
    {
      document.getElementById("hdlFattDlg_FlNmVal").innerHTML = "";
      document.getElementById("hdlFattDlg_FlTitleVal").value = "";
      document.getElementById("hdlFattDlg_DescVal").innerHTML = "";

      var fileAttachmentSelection = document.getElementById("hdlFattDlg_AttSel");
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();

      fileAttachmentSelection.options.length = 0;

      fileAttachments.sort(function(a, b)
      {
        let x = a.getTitle().toLowerCase();
        let y = b.getTitle().toLowerCase();
        if (x < y) {return -1;}
        if (x > y) {return 1;}
        return 0;
      });

      let entityRef = hdlFattDlg.entRef;

      for ( var i =0; i< fileAttachments.length; i++)
      {
        if(((entityRef != null)&&(fileAttachments[i].hasEntity(entityRef) == true))||(entityRef == null))
        {
          var option = document.createElement("option");
          option.text = fileAttachments[i].getTitle();
          option.ref = fileAttachments[i];
          fileAttachmentSelection.add(option);
        }
      }

      if(fileAttachmentSelection.length > 0)
      {
        fileAttachmentSelection.selectedIndex = 0;
        hdlFattDlg.selectedFileAttachment = fileAttachmentSelection.options[0].ref;
        hdlFattDlg.updateProperties();
      }
      else
        hdlFattDlg.selectedFileAttachment = null;
    }//hdlFattDlg.initialize
  }//if (!hdlFattDlg)


  hdlFattDlg.entRef = entity;

  //initialize dialog
  switch(context)
  {
    case "FileAttShow":
      hdlFattDlg.initialize();
      break;
    case "FileAttDefine":
      break;
    default:
      hdlFattDlg.initialize();
      break;
  }

  //show dialog
  hdlFattDlg.showDialog(parentDlg);

  function hdlFattDlgCbk(btnName)
  {
    if(hdlFattDlg.selectedFileAttachment == null)
    {
      return;
    }

    switch(btnName)
    {
      case "close":
        break;
      default:
        hdlFattDlg.dialog.style.display = 'block';
        break;
    }
  }//function hdlFattDlgCbk(btnName)
};//function showHdlFattDlg()

function showFAttUpldDlg(parentDlg,fileTarget)
{
  if (!fAttUpldDlg)
  {
    fAttUpldDlg = new DialogBox('fAttUpldDlg', fAttUpldDlgCbk, cmiCanvas);
    fAttUpldDlg.statusOutput = document.getElementById("fAttUpldDlg_StateVal");

    fAttUpldDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();
      fAttUpldDlg.statusOutput.innerHTML = textToDisplay;
      switch(currentStatus)
      {
        case "uploadFileAtchProgressSuccess":
          fAttUpldDlg.dialog.style.display = 'none';
          fileAttachments.push(fAttUpldDlg.poi3dFatch);
          poi3dConnector.saveFileAttachmentsToStorage();
          showMsgDlg(fAttUpldDlg,poi3dConnector.getMessage(18));//"file successfully saved"
          break;
      }
    }//fAttUpldDlg.onStatusUpdate

    poi3dConnector.registerCallback("uploadFileAtchDlgStatusUpdate",fAttUpldDlg.onStatusUpdate);
  }//if (!fAttUpldDlg)

  fAttUpldDlg.flName = fileTarget.name;
  fAttUpldDlg.fileTarget = fileTarget;
  fAttUpldDlg.poi3dFatch = null;
  document.getElementById("fAttUpldDlg_FileNameVal").innerHTML = fileTarget.name;

  //show dialog
  fAttUpldDlg.showDialog(parentDlg);

  function fAttUpldDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "upload":
        if(poi3dConnector.isMaximumReached("maxFa"))
        {
          showMsgDlg(fAttUpldDlg,poi3dConnector.getMessage(11));//"Max. number of work groups reached"
          return;
        }

        fAttUpldDlg.dialog.style.display = 'block';

        fAttUpldDlg.poi3dFatch = new Poi3dFileAttachment(poi3dConnector.getLeftDocument());

        let val = document.getElementById("fAttUpldDlg_TitleVal").value;
        fAttUpldDlg.poi3dFatch.setTitle(val);
        val = document.getElementById("fAttUpldDlg_DescVal").textContent;
        fAttUpldDlg.poi3dFatch.setDesc(val);
        fAttUpldDlg.poi3dFatch.setFileName(fAttUpldDlg.flName);
        fAttUpldDlg.poi3dFatch.setOwner(poi3dConnector.getPoi3dUser());

        fAttUpldDlg.poi3dFatch.uploadFile(poi3dConnector.getPoi3dUser(),fAttUpldDlg.fileTarget);
        poi3dConnector.getLeftDocument().getFileAttachmentObject().setLocalChangeFlag(true);
        break;
      case "close":
        break;
    }
  }//function fAttUpldDlgCbk(btnName)
};//function showFAttUpldDlg()

function showLoginDlg(parentDlg)
{
  if (!loginDlg)
    loginDlg = new DialogBox('loginDlg', loginDlgCbk, cmiCanvas);

  loginDlg.onShowPwd = function()
  {
    var pwdInput = document.getElementById("loginDlg_PwdVal");

    if (pwdInput.type === "password")
      pwdInput.type = "text";
    else
      pwdInput.type = "password";
  }

  loginDlg.resetPwd = function()
  {
      var uAlias = document.getElementById("loginDlg_UserNameVal").value;
      poi3dConnector.getPoi3dUser().resetUserPassword(uAlias);
  }

  loginDlg.showDialog(parentDlg);

  function loginDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      var uAlias = document.getElementById("loginDlg_UserNameVal").value;
      var uPwd = document.getElementById("loginDlg_PwdVal").value;
      var uToken = document.getElementById("loginDlg_User2FAVal").value;
      if((uAlias.length == 0)||(uPwd.length == 0))
      {
        showMsgDlg(loginDlg,poi3dConnector.getMessage(29));//Error in user existance check
      }
      else if(poi3dConnector.getPoi3dUser().restore() == false)
      {
        poi3dConnector.getPoi3dUser().loadUserBaseInformation(uAlias,uPwd,uToken);
      }
    }
  }
}//function showLoginDlg()

function showUSelDlg(parentDlg,context,currentUserList,fullUserList)
{
  if (!uSelDlg)
  {
    uSelDlg = new DialogBox('uSelDlg', uSelDlgCbk, cmiCanvas);

    uSelDlg.selectedUsers = new Array();
    uSelDlg.allUsers = fullUserList;

    uSelDlg.updateUserSelectionList = function(currentUserList)
    {
      var poi3dUser=null;
      var userSelection = document.getElementById("uSelDlg_UsrSel");
      var optionEntry;
      var allUsers = uSelDlg.allUsers;

      userSelection.options.length = 0;

      for ( var i =0; i<allUsers.length; i++)
      {
        poi3dUserSelection = allUsers[i];
        if((poi3dUserSelection.userId != poi3dConnector.getCurrentUserId())&&
           (currentUserList.some(item => item.userId === poi3dUserSelection.userId) == false)
        )
        {
          optionEntry = document.createElement("option");

          if((poi3dUserSelection.firstName.length == 0)&&(poi3dUserSelection.lastName.length == 0))
            optionEntry.text = poi3dUserSelection.aliasName;
          else
            optionEntry.text = poi3dUserSelection.aliasName + " (" + poi3dUserSelection.firstName + " " + poi3dUserSelection.lastName +")";

          optionEntry.user = poi3dUserSelection;
          userSelection.add(optionEntry);
        }
      }
    }
  };//if (!uSelDlg)

  uSelDlg.filterUsers = function()
  {
    var filterText = document.getElementById("uSelDlg_FilterVal").value;
    var userSelection = document.getElementById("uSelDlg_UsrSel");

    //dynamic filtering: https://jsfiddle.net/agarwalp/L90hdheg/
    for (var i = 0; i < userSelection.length; i++)
    {
      var txt = userSelection.options[i].text;
      if (txt.substring(0, filterText.length).toLowerCase() !== filterText.toLowerCase() && filterText.trim() !== "")
        userSelection.options[i].style.display = 'none';
      else
        userSelection.options[i].style.display = 'list-item';
    }
  };//uSelDlg.filterUsers = function()

  uSelDlg.context = context;
  uSelDlg.allUsers = fullUserList;

  uSelDlg.updateUserSelectionList(currentUserList);

  uSelDlg.showDialog(parentDlg);

  function uSelDlgCbk(btnName)
  {
    uSelDlg.selectedUsers = new Array();
    if (btnName == 'ok')
    {
      var userSelection = document.getElementById("uSelDlg_UsrSel");

      for ( var i =0; i<userSelection.options.length; i++)
      {
        if(userSelection.options[i].selected == true)
        {
          uSelDlg.selectedUsers.push(userSelection.options[i].user);
        }
      }
      switch(uSelDlg.context)
      {
        case "uMgmDlg":
          uMgmDlg.selectedUsers = new Array();
          for(let i=0; i<uSelDlg.selectedUsers.length; i++)
            uMgmDlg.selectedUsers.push(uSelDlg.selectedUsers[i]);
          uMgmDlg.updateUserSettings();
          break;
        case "docMgmtDlg":
          docMgmtDlg.addUsersToWg(uSelDlg.selectedUsers);
          break;
        case "commDlg":
          for(let i=0; i<uSelDlg.selectedUsers.length; i++)
            commDlg.selectedUsers.push(uSelDlg.selectedUsers[i]);
          commDlg.updateEmailSection();
          break;
      }
    }
  };//function uSelDlgCbk(btnName)
};//function showUSelDlg()

function showVerifyDlg(parentDlg,context,objectToHandle)
{
  if (!verifyDlg)
  {
    verifyDlg = new DialogBox('verifyDlg', verifyDlgCbk, cmiCanvas);
    verifyDlg.objectToHandle = null;
    verifyDlg.context = "";
  }
  verifyDlg.objectToHandle = objectToHandle;
  verifyDlg.context = context;

  verifyDlg.showDialog(parentDlg);

  function verifyDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      var pwd = document.getElementById("verifyDlg_UserPwdVal").value;
      document.getElementById("verifyDlg_UserPwdVal").value = "";
      if(poi3dConnector.getPoi3dUser().checkPassword(pwd)==false)
      {
        showMsgDlg(verifyDlg,poi3dConnector.getMessage(8));//Wrong password
        return;
      }
      switch(verifyDlg.context)
      {
        case "deleteWorkGroup":
          document.getElementById("verifyDlg_UserPwdVal").value = "";
          docMgmtDlg.deleteCurrentWorkGroup();
          break;
        case "deleteCtlgEntry":
          document.getElementById("verifyDlg_UserPwdVal").value = "";
          docMgmtDlg.deleteCurrCtlgEntry();
          break;
        case "deleteUser":
          document.getElementById("verifyDlg_UserPwdVal").value = "";
          uSetDlg.dialog.style.display = 'none';
          poi3dConnector.deleteUser();
          break;
        case "deleteCurrentDocument":
          verifyDlg.objectToHandle.deleteDocument(poi3dConnector.getPoi3dUser());
          break;
      }
    }
  }
}//function showVerifyDlg()

function showGetAutRghtDlg(parentDlg)
{
  if (!getAutRghtDlg)
  {
    getAutRghtDlg = new DialogBox('getAutRghtDlg', getAutRghtDlgCbk, cmiCanvas);
    getAutRghtDlg.oldExpDate = new Date();
    getAutRghtDlg.newExpDate = new Date();

    getAutRghtDlg.onMonthUpdate = function(selectObject)
    {
      let monthValue = parseInt(document.getElementById("getAutRghtDlg_MonthsToAddVal").value);
      let currExpDate = new Date(getAutRghtDlg.oldExpDate);
      let newExpDate = new Date(getAutRghtDlg.oldExpDate);

      newExpDate.setMonth(currExpDate.getMonth() + monthValue);

      getAutRghtDlg.newExpDate = new Date(newExpDate);
      document.getElementById("getAutRghtDlg_NewExpDateVal").innerHTML = getAutRghtDlg.newExpDate.toLocaleDateString();
    }
  }

  //initialize
  let expDate = new Date(poi3dConnector.getPoi3dUser().getAuthorExpirationDate());
  let currDate = new Date();

  if(expDate > currDate) //still valid
  {
    getAutRghtDlg.oldExpDate = expDate;
    document.getElementById("getAutRghtDlg_RevitLicVal").innerHTML = poi3dConnector.getConverterLicense("REVIT");
  }
  else //expired
  {
    getAutRghtDlg.oldExpDate = currDate;
    document.getElementById("getAutRghtDlg_RevitLicVal").innerHTML = "-";
  }

  document.getElementById("getAutRghtDlg_CurrExpDateVal").innerHTML = getAutRghtDlg.oldExpDate.toLocaleDateString();
  getAutRghtDlg.onMonthUpdate(document.getElementById("getAutRghtDlg_MonthsToAddVal"));

  //show
  getAutRghtDlg.showDialog(parentDlg);

  function getAutRghtDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      var requestContent = "{\"user\":\"" + poi3dConnector.getPoi3dUser().getUserId() + "\", \"quantity\":" + document.getElementById("getAutRghtDlg_MonthsToAddVal").value + "}";
      Poi3dHelpers.callPhpFunction("./poi3dPaymentConnector.php?func=PaypalGetQuery", requestContent, paypalQueryStringCallbackSuccess, paypalQueryStringCallbackError, this );
    }
  }

  function paypalQueryStringCallbackSuccess(theEvent)
  {
    var req = theEvent.target;
    if(req.readyState == 4)
    {
      if(!req.response){this.paypalQueryStringCallbackError(theEvent);return;}
      var jsonObject = req.response;
      if(jsonObject.erC != 0)
      {
        _errorMesssage = jsonObject.erT;
        var eventData = {context:"POI3D_ERROR",info:"PaypalGetQuery",calledFrom:this,senderId:"Poi3D.intern"};
        Poi3dHelpers.sendPoi3dNotification(eventData);
        return;
      }
      var eventData = null;
      if(jsonObject.dt.url) {
        eventData = {context:"POI3D_INFO",info:"paypalQueryStringCallbackSuccess",retVal:true,calledFrom:this,senderId:"Poi3D.intern"};
        window.open( jsonObject.dt.url, "paypal", "width=500,height=800" );
      }
      else
        eventData = {context:"POI3D_INFO",info:"paypalQueryStringCallbackSuccess",retVal:false,calledFrom:this,senderId:"Poi3D.intern"};

      Poi3dHelpers.sendPoi3dNotification(eventData);
      return;
    }
  }

  function paypalQueryStringCallbackError(theEvent)
  {
    alert('TODO error handling 1');
  }
}//function showGetAutRghtDlg()


function showModSaveDlg(parentDlg)
{
  if (!modSaveDlg)
  {
    modSaveDlg = new DialogBox('modSaveDlg', modSaveDlgCbk, cmiCanvas);
    modSaveDlg.statusOutput = document.getElementById("modSaveDlg_StateVal");
    modSaveDlg.leftDocument = poi3dConnector.getLeftDocument();

    modSaveDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      modSaveDlg.statusOutput.innerHTML = textToDisplay;
      switch(currentStatus)
      {
        case "saveDocumentSuccess":
          poi3dConnector.addDocumentToUser(poi3dConnector.getLeftDocument());
          poi3dConnector.saveDocumentListToStorage("modSaveDlg");
          if(typeof Poi3dHostInterface != "undefined") //hosted
            Poi3dHostInterface.sendMessageToHost("DocumentSaved");//inform host about save operation
          break;
        case "saveUserDocumentsSuccess":
          poi3dConnector.savePreviewToStorage(poi3dConnector.getLeftDocument(),document.getElementById("modSaveDlg_Canvas"));
          break;
        case "savePreviewSuccess":
          modSaveDlg.statusOutput.innerHTML = poi3dConnector.getMessage(34);//"successfully saved"
          break;
      }

    }//modSaveDlg.onStatusUpdate

    modSaveDlg.onScrnShotClicked = function()
    {
      var canvas = document.getElementById("modSaveDlg_Canvas");
      var imageContext = canvas.getContext('2d');
      //imageContext.fillStyle = myCmiWindow.getBgColorRGBString();
      imageContext.fillStyle = "#FFFFFF";
      imageContext.fillRect(0, 0, canvas.width, canvas.height);

      var modelImage = myCmiWindow.getImageObjectFromWebGlWindow();  //Gets the webgl content as an image
      modelImage.onload = function (drawContext)
      {
        return function()
        {
          var xPos=0;
          var yPos=0;
          var dX=0;
          var dY=0;
          var aspect = this.height/this.width;

          //center image and scale
          if((this.width <= canvas.width)&&(this.height <= canvas.height))
          {
            xPos=parseInt((canvas.width - this.width)/2);
            yPos=parseInt((canvas.height - this.height)/2);
            dX=this.width;
            dY=this.height;
          }
          else
          {
            var xOverflow = this.width-canvas.width;
            var yOverflow = this.height-canvas.height;
            if(xOverflow > yOverflow)
            {
              xPos=0;
              dX=canvas.width;
              dY=dX*aspect;
              yPos=parseInt((canvas.height - dY)/2);
            }
            else
            {
              yPos=0;
              dY=canvas.height;
              dX=dY/aspect;
              xPos=parseInt((canvas.width - dX)/2);
            }
          }//if((this.width <= canvas.width)&&(this.height <= canvas.height)) else
          imageContext.drawImage(this,xPos,yPos,dX,dY);
        }
      }(imageContext,canvas);
    }//modSaveDlg.onScrnShotClicked

    poi3dConnector.registerCallback("saveDlgStatusUpdate",modSaveDlg.onStatusUpdate);
  }//if (!modSaveDlg)

  if(poi3dConnector.hasUserAuthorRights() == false)
  {
    showMsgDlg(modSaveDlg,poi3dConnector.getMessage(4));
    return;
  }

  modSaveDlg.leftDocument = poi3dConnector.getLeftDocument();

  if(modSaveDlg.leftDocument == null)
  {
    showMsgDlg(modSaveDlg,poi3dConnector.getMessage(5));
    return;
  }

  document.getElementById("modSaveDlg_DocTitleVal").value = modSaveDlg.leftDocument.getTitle();
  document.getElementById("modSaveDlg_DescInput").innerHTML = modSaveDlg.leftDocument.getDescription();

  var previewUrl = modSaveDlg.leftDocument.getPreviewUrl(poi3dConnector.getPoi3dUser(),"read");

  if(previewUrl.length > 0)
    previewUrl = previewUrl+"&t=" + new Date().getTime();
  else
    previewUrl = "./CmiBitmaps/GenericTexture.jpg"

  var myCanvas = document.getElementById('modSaveDlg_Canvas');
  var ctx = myCanvas.getContext('2d');
  var img = new Image;
  img.onload = function(){ctx.drawImage(img,0,0);};
  img.src = previewUrl;

  if(modSaveDlg.leftDocument.getUseFrontAsTop() == false)
    document.getElementById("modSaveDlg_ZAxisDirUpVal").checked = true;
  else
    document.getElementById("modSaveDlg_ZAxisDirToVal").checked = true;


  if(modSaveDlg.leftDocument.getLoadState() == false)//save newly
  {
    if(poi3dConnector.getPoi3dUser().isDocHostedAndSaved(modSaveDlg.leftDocument))
    {
      showMsgDlg(modSaveDlg,poi3dConnector.getMessage(66));//document already saved
      return;
    }
  }
  modSaveDlg.showDialog(parentDlg);

  function modSaveDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "save":
        modSaveDlg.dialog.style.display = 'block';

        modSaveDlg.leftDocument.setTitle(document.getElementById("modSaveDlg_DocTitleVal").value);
        modSaveDlg.leftDocument.setDescription(document.getElementById("modSaveDlg_DescInput").textContent);

        if(document.getElementById("modSaveDlg_ZAxisDirToVal").checked == true)
          modSaveDlg.leftDocument.setUseFrontAsTop(true);
        else
          modSaveDlg.leftDocument.setUseFrontAsTop(false);

        myCmiWindow.useFrontAsTop = modSaveDlg.leftDocument.getUseFrontAsTop();

        if(modSaveDlg.leftDocument.getLoadState() == false)//save newly
        {
          if(poi3dConnector.getPoi3dUser().isDocHostedAndSaved(modSaveDlg.leftDocument))
            showMsgDlg(modSaveDlg,poi3dConnector.getMessage(66));//document already saved
          else
            poi3dConnector.saveNewDocumentToStorage(modSaveDlg.leftDocument,poi3dConnector.getLeftFileTarget(),"modSaveDlg");
        }
        else //update
        {
          modSaveDlg.leftDocument.setDocState("changed");
          poi3dConnector.saveDocumentListToStorage("modSaveDlg");
        }
        break;
      case "close":
        document.getElementById("modSaveDlg_StateVal").innerHTML = "";
        break;
      default:
        modSaveDlg.dialog.style.display = 'block';
        break;
    }
  }
}//function showModSaveDlg()

function showMatDlg(parentDlg)
{
  if (!matDlg)
  {
    matDlg = new DialogBox('matDlg', matDlgCbk, cmiCanvas);

    matDlg.dirColSliderText = document.getElementById("matDlg_DirColSldrTxt");
    matDlg.ambientColSliderText = document.getElementById("matDlg_AmbientColSliderTxt");
    matDlg.shineColSliderText = document.getElementById("matDlg_ShineColSliderTxt");
    matDlg.transparencySliderText = document.getElementById("matDlg_TranspSliderTxt");
    matDlg.bumpSliderText = document.getElementById("matDlg_BumpSliderTxt");
    matDlg.reflectionSliderText = document.getElementById("matDlg_ReflectSliderTxt");
    matDlg.texScaleSliderText = document.getElementById("matDlg_TexScaleSliderTxt");

    matDlg.baseColorValue = document.getElementById("matDlg_BaseColVal");
    matDlg.dirColSliderValue = document.getElementById("matDlg_DirColSldrVal");
    matDlg.ambientColSliderValue = document.getElementById("matDlg_AmbientColSliderVal");
    matDlg.shineColSliderValue = document.getElementById("matDlg_ShineColSliderVal");
    matDlg.transparencySliderValue = document.getElementById("matDlg_TranspSliderVal");
    matDlg.bumpSliderValue = document.getElementById("matDlg_BumpSliderVal");
    matDlg.reflectionSliderValue = document.getElementById("matDlg_ReflectSliderVal");
    matDlg.texScaleSliderValue = document.getElementById("matDlg_TexScaleSliderVal");

    matDlg.baseImgRotateValue = document.getElementById("matDlg_BaseImgRotVal");
    matDlg.baseImgRotateValueLabel = document.getElementById("matDlg_BaseImgRotateValLab");
    matDlg.baseImgBwValue = document.getElementById("matDlg_BaseImgBwVal");
    matDlg.baseImgBwValueLabel = document.getElementById("matDlg_BaseImgBwValLab");

    matDlg.baseImgValue = document.getElementById("matDlg_BaseImgVal");
    matDlg.baseImgNameTitle = document.getElementById("matDlg_BaseImgName");
    matDlg.matSelector = document.getElementById("matDlg_IcoSelector");
    matDlg.materials = poi3dConnector.getMaterialDefinitions();

    matDlg.categorySelection = document.getElementById("matDlg_SavedCatSel");
    matDlg.categorySelection.options.length = 0;
    matDlg.currentMaterialCategory = null;
    matDlg.matDlg_SavedMatSetSel = document.getElementById("matDlg_SavedMatSetSel");

    matDlg.previewCheckBox = document.getElementById("matDlg_PreviewCheck");

    matDlg.currentMaterial = new Poi3dMaterial();
    matDlg.selectedEntities = new Array();
    matDlg.isAssigned = false;
    matDlg.matSetBeforeOpened = null;

    matDlg.onTabSelectionChange = function(sectionToActivate)
    {
      if(sectionToActivate == "matDlg_ColorSection")
      {
        Poi3dHelpers.setDisplayStyle("matDlg_ColorSection","block");
        Poi3dHelpers.setDisplayStyle("matDlg_VisSection","none");
      }
      else if(sectionToActivate == "matDlg_VisSection")
      {
        Poi3dHelpers.setDisplayStyle("matDlg_ColorSection","none");
        Poi3dHelpers.setDisplayStyle("matDlg_VisSection","block");
      }
    };//matDlg.onTabSelectionChange

    matDlg.onCategorySelectionChange = function(selectionObject)
    {
      var iconText = "";
      var mat = null;

      if(selectionObject != null)
        matDlg.currentMaterialCategory = matDlg.materials[selectionObject.selectedIndex];

      for ( var i =0; i<matDlg.currentMaterialCategory.entries.length; i++)
      {
        mat = matDlg.currentMaterialCategory.entries[i];
        iconText = iconText + "<img title='" + mat.title + "' src='" + matDlg.currentMaterialCategory.baseDir + "/" + mat.previewFile + "' alt='" + mat.title + "' onclick='matDlg.onTextureClick(this)'>\n";
      }
      matDlg.matSelector.innerHTML = iconText;
    }

    matDlg.onTextureClick = function(imageObject)
    {
      if(imageObject != null)
      {
        var foundMaterial = matDlg.currentMaterialCategory.entries.find(item => item.title === imageObject.title);
        foundMaterial.copyTo(matDlg.currentMaterial);
        matDlg.currentMaterial.textureScale = matDlg.texScaleSliderValue.value;
      }

      matDlg.baseImgValue.onload  = function ()
      {
        if(matDlg.currentMaterial.textureFile.length > 0)
          myCmiWindow.preloadTextureFileFromUrl(matDlg.currentMaterial.textureFile, textureFileName);
        if(matDlg.currentMaterial.structureFile.length > 0)
          myCmiWindow.preloadTextureFileFromUrl(matDlg.currentMaterial.structureFile, structureFileName);
      }

      if(matDlg.currentMaterial.textureFile.length > 0)
      {
        var textureFileName =  matDlg.currentMaterial.imageDirectory + "/" + matDlg.currentMaterial.textureFile;
        var structureFileName =  matDlg.currentMaterial.imageDirectory + "/" + matDlg.currentMaterial.structureFile;

        matDlg.baseImgValue.src = textureFileName;
      }
      else
        matDlg.baseImgValue.src = matDlg.currentMaterial.imageDirectory + "/" + matDlg.currentMaterial.previewFile;


      matDlg.baseImgNameTitle.innerHTML = matDlg.currentMaterial.title;

      matDlg.baseColorValue.value = Poi3dHelpers.oglToHex(matDlg.currentMaterial.baseColor);

      matDlg.dirColSliderValue.value = matDlg.currentMaterial.directFactor;
      matDlg.dirColSliderText.value = matDlg.currentMaterial.directFactor;

      matDlg.ambientColSliderValue.value = matDlg.currentMaterial.ambientFactor;
      matDlg.ambientColSliderText.value = matDlg.currentMaterial.ambientFactor;

      matDlg.shineColSliderValue.value = matDlg.currentMaterial.specularFactor;
      matDlg.shineColSliderText.value = matDlg.currentMaterial.specularFactor;

      matDlg.transparencySliderValue.value = matDlg.currentMaterial.transparency;
      matDlg.transparencySliderText.value = matDlg.currentMaterial.transparency;

      matDlg.bumpSliderValue.value = matDlg.currentMaterial.bumpFactor;
      matDlg.bumpSliderText.value = matDlg.currentMaterial.bumpFactor;

      matDlg.reflectionSliderValue.value = matDlg.currentMaterial.reflectionFactor;
      matDlg.reflectionSliderText.value = matDlg.currentMaterial.reflectionFactor;

      matDlg.texScaleSliderValue.value = matDlg.currentMaterial.textureScale;
      matDlg.texScaleSliderText.value = matDlg.currentMaterial.textureScale;

      //matDlg.currentMaterial.textureScale = matDlg.texScaleSliderValue.value;

      if(matDlg.currentMaterial.structureFile.length == 0)
        Poi3dHelpers.canBeUsed(matDlg.bumpSliderValue,false);
      else
        Poi3dHelpers.canBeUsed(matDlg.bumpSliderValue,true);

      if(matDlg.currentMaterial.textureFile.length == 0)
      {
        Poi3dHelpers.canBeUsed(matDlg.baseImgRotateValue,false);
        Poi3dHelpers.canBeUsed(matDlg.baseImgRotateValueLabel,false);

        Poi3dHelpers.canBeUsed(matDlg.baseImgBwValue,false);
        Poi3dHelpers.canBeUsed(matDlg.baseImgBwValueLabel,false);

        Poi3dHelpers.canBeUsed(matDlg.texScaleSliderValue,false);
      }
      else
      {
        Poi3dHelpers.canBeUsed(matDlg.baseImgRotateValue,true);
        Poi3dHelpers.canBeUsed(matDlg.baseImgRotateValueLabel,true);

        Poi3dHelpers.canBeUsed(matDlg.baseImgBwValue,true);
        Poi3dHelpers.canBeUsed(matDlg.baseImgBwValueLabel,true);

        Poi3dHelpers.canBeUsed(matDlg.texScaleSliderValue,true);
      }
    }

    //init material selection
    for ( var i =0; i<matDlg.materials.length; i++)
    {
      if(i==0)
      {
        matDlg.currentMaterialCategory = matDlg.materials[i];
        matDlg.currentMaterialCategory.entries[0].copyTo(matDlg.currentMaterial);
      }

      optionEntry = document.createElement("option");
      if(poi3dConnector.getUserSettings().uiLanguage == "de")
        optionEntry.text = matDlg.materials[i].titleDe;
      else
        optionEntry.text = matDlg.materials[i].titleEn;

      matDlg.categorySelection.add(optionEntry);
    }
    matDlg.onCategorySelectionChange(null);
    matDlg.onTextureClick(null);

  }//if (!matDlg)

  matDlg.onMaterialSetSelectionChange = function(selectionObject)
  {
    if(leftModel == null) return;
    let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();

    matDlg.deActivateAfterClose = true;

    if(currentMaterialSetRef != null)
      currentMaterialSetRef.deleteFromEntities(leftModel);

    currentMaterialSetRef = materialSets[selectionObject.selectedIndex];
    currentMaterialSetCopy = currentMaterialSetRef.createCopy(true);

    currentMaterialSetRef.applyToEntities(leftModel);
    myCmiWindow.drawScene();
  }

  matDlg.onSliderChanged = function(sliderObject,slider)
  {
    switch(slider)
    {
      case "dirCol":
        matDlg.dirColSliderText.value = sliderObject.value;
        matDlg.currentMaterial.directFactor = sliderObject.value;
        break;
      case "ambCol":
        matDlg.ambientColSliderText.value = sliderObject.value;
        matDlg.currentMaterial.ambientFactor = sliderObject.value;
        break;
      case "shineCol":
        matDlg.shineColSliderText.value = sliderObject.value;
        matDlg.currentMaterial.specularFactor = sliderObject.value;
        break;
      case "transp":
        matDlg.transparencySliderText.value = sliderObject.value;
        matDlg.currentMaterial.transparency = sliderObject.value;
        break;
      case "bump":
        matDlg.bumpSliderText.value = sliderObject.value;
        matDlg.currentMaterial.bumpFactor = sliderObject.value;
        break;
      case "reflect":
        matDlg.reflectionSliderText.value = sliderObject.value;
        matDlg.currentMaterial.reflectionFactor = sliderObject.value;
        break;
      case "scale":
        matDlg.texScaleSliderText.value = sliderObject.value;
        matDlg.currentMaterial.textureScale = sliderObject.value;
        break;
    }
  }

  matDlg.onTextInputChanged = function(inputObject,context)
  {
    switch(context)
    {
      case "dirCol":
        matDlg.dirColSliderValue.value = inputObject.value ;
        matDlg.currentMaterial.directFactor = inputObject.value;
        break;
      case "ambCol":
        matDlg.ambientColSliderValue.value = inputObject.value;
        matDlg.currentMaterial.ambientFactor = inputObject.value;
        break;
      case "shineCol":
        matDlg.shineColSliderValue.value = inputObject.value;
        matDlg.currentMaterial.specularFactor = inputObject.value;
        break;
      case "transp":
        matDlg.transparencySliderValue.value = inputObject.value;
        matDlg.currentMaterial.transparency = inputObject.value;
        break;
      case "bump":
        matDlg.bumpSliderValue.value = inputObject.value;
        matDlg.currentMaterial.bumpFactor = inputObject.value;
        break;
      case "reflect":
        matDlg.reflectionSliderValue.value = inputObject.value;
        matDlg.currentMaterial.reflectionFactor = inputObject.value;
        break;
      case "scale":
        matDlg.texScaleSliderValue.value = inputObject.value;
        matDlg.currentMaterial.textureScale = inputObject.value;
        break;
    }
  }

  matDlg.onTextureMod = function(checkBoxObject,modification)
  {
    switch(modification)
    {
      case "rotate":
        matDlg.currentMaterial.rotated = checkBoxObject.checked;

        if(checkBoxObject.checked == true)
          matDlg.baseImgValue.style.transform = "rotate(270deg)";
        else
          matDlg.baseImgValue.style.transform = "rotate(0deg)";
        break;
      case "gray":
        matDlg.currentMaterial.grayed = checkBoxObject.checked;

        if(checkBoxObject.checked == true)
          matDlg.baseImgValue.style.filter = "grayscale(100%)";
        else
          matDlg.baseImgValue.style.filter = "grayscale(0%)";
        break;
    }


    var textureName = matDlg.currentMaterial.getTextureName();
    var structureName = matDlg.currentMaterial.getStructureName();

    if(textureName.length > 0)
      myCmiWindow.preloadTextureFileFromUrl(textureName, matDlg.currentMaterial.imageDirectory+ "/" + matDlg.currentMaterial.textureFile, matDlg.currentMaterial.rotated, matDlg.currentMaterial.grayed );
    if(structureName.length > 0)
      myCmiWindow.preloadTextureFileFromUrl(structureName, matDlg.currentMaterial.imageDirectory+ "/" + matDlg.currentMaterial.structureFile, matDlg.currentMaterial.rotated, false );
  }

  matDlg.enableCommandButtons = function ()
  {
    let previewButton = document.getElementById("matDlg_PreviewBut");
    let resetButton = document.getElementById("matDlg_ResetBut");
    let assignButton = document.getElementById("matDlg_AssignBut");

    if((leftModel == null)||(currentMaterialSetRef == null))
    {
      if(leftModel == null)
      {
        Poi3dHelpers.canBeUsed(previewButton,false);
        Poi3dHelpers.canBeUsed(matDlg.previewCheckBox,false);
      }
      else
      {
        Poi3dHelpers.canBeUsed(previewButton,true);
        Poi3dHelpers.canBeUsed(matDlg.previewCheckBox,true);
      }
      Poi3dHelpers.canBeUsed(resetButton,false);
      Poi3dHelpers.canBeUsed(assignButton,false);
    }
    else
    {
      Poi3dHelpers.canBeUsed(previewButton,true);
      Poi3dHelpers.canBeUsed(matDlg.previewCheckBox,true);
      Poi3dHelpers.canBeUsed(resetButton,true);
      Poi3dHelpers.canBeUsed(assignButton,true);
    }
  }

  matDlg.onPreviewCheckboxClicked   = function(previewCheckBoxObject)
  {
    if(previewCheckBoxObject.checked == false)
    {
      leftModel.restoreEntityMaterial(matDlg.selectedEntities);
      leftAssemblyBrowser.highlightComponents(matDlg.selectedEntities);
      leftBomBrowser.highlightComponents(matDlg.selectedEntities);
      myCmiWindow.restoreSelectableTypes();
      myCmiWindow.drawScene();

      return;
    }
  }

  matDlg.onPickMaterial = function()
  {
    setStatusText(poi3dConnector.getStatusText(16));//"Select element with material assignment"
    interactionMode = "matPick";
  }

  matDlg.materialPicked = function(cmiEntity)
  {
    if(cmiEntity.poi3dMaterialId)
    {
      var entMaterial = currentMaterialSetRef.getMaterialById(cmiEntity.poi3dMaterialId);
      if(entMaterial != null)
      {
        entMaterial.copyTo(matDlg.currentMaterial);
        matDlg.onTextureClick(null);
      }
    }
  }

  //init
  matDlg.isAssigned = false;
  matDlg.matSetBeforeOpened = currentMaterialSetRef;

  //init material set selection
  let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();
  matDlg.matDlg_SavedMatSetSel.options.length = 0;
  for ( var i =0; i<materialSets.length; i++)
  {
    optionEntry = document.createElement("option");
    optionEntry.text = materialSets[i].getMaterialSetTitle();
    matDlg.matDlg_SavedMatSetSel.add(optionEntry);

    if((i==0)&&(currentMaterialSetRef == null))
      matDlg.matDlg_SavedMatSetSel.selectedIndex = i;
    else if(currentMaterialSetRef ==  materialSets[i])
      matDlg.matDlg_SavedMatSetSel.selectedIndex = i;

  }

  if(currentMaterialSetRef != materialSets[matDlg.matDlg_SavedMatSetSel.selectedIndex])
  {
    if(currentMaterialSetRef != null)
      currentMaterialSetRef.deleteFromEntities(leftModel);

    currentMaterialSetRef = materialSets[matDlg.matDlg_SavedMatSetSel.selectedIndex];
    currentMaterialSetCopy = currentMaterialSetRef.createCopy(true);

    currentMaterialSetRef.applyToEntities(leftModel);
    myCmiWindow.drawScene();
  }

  matDlg.enableCommandButtons();
  matDlg.showDialog(parentDlg);

  function matDlgCbk(btnName)
  {
    var clearSelectionOnPreview = false;
    if(matDlg.previewCheckBox.checked == true)
    {
      myCmiWindow.restoreSelectableTypes();
      matDlg.previewCheckBox.checked = false;
    }
    else
      clearSelectionOnPreview = true;

    switch(btnName)
    {
      case "mdPreview":
        {
          matDlg.dialog.style.display = 'block';

          if(clearSelectionOnPreview == true)
            matDlg.selectedEntities = new Array();

          let mat = matDlg.currentMaterial;
          let selEnts = leftAssemblyBrowser.getHighlightedComponents(true);
          if(selEnts.length > 0)
          {
            selEnts.forEach(value => {
              if (!matDlg.selectedEntities.includes(value)) {
                matDlg.selectedEntities.push(value);
              }
            });
          }

          let colorVal = Poi3dHelpers.hexToOgl(matDlg.baseColorValue.value);

          let diffuseColor = new Array(colorVal.r*mat.directFactor, colorVal.g*mat.directFactor, colorVal.b*mat.directFactor);
          let specularColor = new Array(colorVal.r*mat.specularFactor, colorVal.g*mat.specularFactor, colorVal.b*mat.specularFactor);
          let ambientColor = new Array(colorVal.r*mat.ambientFactor, colorVal.g*mat.ambientFactor, colorVal.b*mat.ambientFactor);

          if((matDlg.selectedEntities.length > 0)&&(leftModel != null))
          {
            matDlg.previewCheckBox.checked = true;

            myCmiWindow.saveSelectableTypes();
            myCmiWindow.makeAllTypesInselectable();

            leftAssemblyBrowser.switchHighlightStateForAll(false);
            leftBomBrowser.switchHighlightStateForAll(false);
            leftModel.setEntityMaterial(matDlg.selectedEntities,mat.getTextureName(),mat.getStructureName(),diffuseColor,specularColor,ambientColor,mat.specularDistrib,mat.transparency,mat.bumpFactor,mat.textureScale,mat.reflectionFactor,true);
            myCmiWindow.drawScene();
          }
        }
        break;
      case "mdAssign":
        {
          matDlg.dialog.style.display = 'block';
          let selEnts = leftAssemblyBrowser.getHighlightedComponents(true);
          if(selEnts.length > 0)
          {
            selEnts.forEach(value => {
              if (!matDlg.selectedEntities.includes(value)) {
                matDlg.selectedEntities.push(value);
              }
            });
          }

          let colorVal = Poi3dHelpers.hexToOgl(matDlg.baseColorValue.value);
          matDlg.currentMaterial.baseColor = new Array(colorVal.r,colorVal.g,colorVal.b);

          currentMaterialSetRef.updateEntities(matDlg.currentMaterial,matDlg.selectedEntities,leftModel);
          matDlg.isAssigned = true;
          matDlg.selectedEntities = new Array();
          leftAssemblyBrowser.switchHighlightStateForAll(false);
          leftBomBrowser.switchHighlightStateForAll(false);
          myCmiWindow.drawScene();
        }
        break;
      case "mdReset":
        matDlg.dialog.style.display = 'block';
        let selEnts = leftAssemblyBrowser.getHighlightedComponents(true);
        if(selEnts.length > 0)
        {
          selEnts.forEach(value => {
            if (!matDlg.selectedEntities.includes(value)) {
              matDlg.selectedEntities.push(value);
            }
          });
        }

        currentMaterialSetRef.updateEntities(null,matDlg.selectedEntities,leftModel);

        matDlg.selectedEntities = new Array();
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        leftBomBrowser.switchHighlightStateForAll(false);

        myCmiWindow.drawScene();
        break;
      case "mdClose":
        if(leftModel == null) return;

        if(matDlg.isAssigned == false)
          leftModel.restoreEntityMaterial(matDlg.selectedEntities);

        if(matDlg.matSetBeforeOpened != null)
        {
          if(currentMaterialSetRef != null)
            currentMaterialSetRef.deleteFromEntities(leftModel);

          currentMaterialSetRef = matDlg.matSetBeforeOpened;
          currentMaterialSetCopy = currentMaterialSetRef.createCopy(true);
          currentMaterialSetRef.applyToEntities(leftModel);
        }
        else
        {
          if(currentMaterialSetRef != null)
            currentMaterialSetRef.deleteFromEntities(leftModel);

          currentMaterialSetRef = null;
          currentMaterialSetCopy = null;
        }

        matDlg.selectedEntities = new Array();
        leftAssemblyBrowser.switchHighlightStateForAll(false);
        leftBomBrowser.switchHighlightStateForAll(false);

        myCmiWindow.drawScene();
        break;
    }
  }//function matDlgCbk(btnName)
}//function showMatDlg(entity)

function showDefMtlSetDlg(parentDlg)
{
  if (!defMtlSetDlg)
  {
    defMtlSetDlg = new DialogBox('defMtlSetDlg', defMtlSetDlgCbk, cmiCanvas);
    defMtlSetDlg.selectedMaterialSet = null;
    defMtlSetDlg.materialSetSelection = document.getElementById("defMtlSetDlg_SetSel");
    defMtlSetDlg.activeSetTitle = document.getElementById("defMtlSetDlg_ActSetNameVal");

    defMtlSetDlg.onSelectionChange = function()
    {
      let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();

      defMtlSetDlg.selectedMaterialSet = materialSets[defMtlSetDlg.materialSetSelection.selectedIndex];
      document.getElementById("defMtlSetDlg_SetNameVal").value = defMtlSetDlg.selectedMaterialSet.getMaterialSetTitle();
    }

    defMtlSetDlg.createNew = function()
    {
      var matSetName = document.getElementById("defMtlSetDlg_SetNameVal").value;
      let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();

      if(matSetName.length == 0)
      {
        matSetName="matSet"+(materialSets.length+1).toString()+"_"+Date.now().toString(36);
        document.getElementById("defMtlSetDlg_SetNameVal").value = matSetName;
      }
      else
      {
        var foundMaterial = materialSets.find(item => item.getMaterialSetTitle() === matSetName);
        if(foundMaterial != null)
        {
          matSetName="matSet"+(materialSets.length+1).toString()+"_"+Date.now().toString(36);
          document.getElementById("defMtlSetDlg_SetNameVal").value = matSetName;
        }
      }

      let materialSet = new Poi3dMaterialSet();
      materialSet.setMaterialSetTitle(matSetName);
      materialSets.push(materialSet);
      poi3dConnector.getLeftDocument().getMaterialSetObject().setLocalChangeFlag(true);

      var option = document.createElement("option");
      option.text = materialSet.getMaterialSetTitle();
      defMtlSetDlg.materialSetSelection.add(option);
      defMtlSetDlg.materialSetSelection.selectedIndex = materialSets.length-1;
      defMtlSetDlg.selectedMaterialSet = materialSets[defMtlSetDlg.materialSetSelection.selectedIndex];

      updateMaterialSetSelection(materialSets);

    };//defMtlSetDlg.createNew

    defMtlSetDlg.deleteCurrent = function()
    {
      let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();
      if(materialSets.length == 0) return;

      if(currentMaterialSetRef == defMtlSetDlg.selectedMaterialSet)
      {
        currentMaterialSetRef.deleteFromEntities(leftModel);
        currentMaterialSetRef = null;
        currentMaterialSetCopy = null;

        defMtlSetDlg.activeSetTitle.value = "";
        document.getElementById("defMtlSetDlg_SetNameVal").value = "";
        myCmiWindow.drawScene();
      }
      var t1 ;
      var t2 = defMtlSetDlg.selectedMaterialSet.getMaterialSetTitle();
      for (let i=0; i<materialSets.length; i++)
      {
        t1 = materialSets[i].getMaterialSetTitle();
        if(materialSets[i].getMaterialSetTitle() == defMtlSetDlg.selectedMaterialSet.getMaterialSetTitle())
        {
          materialSets = materialSets.filter(function(item) {return item !== materialSets[i]});
          i = materialSets.length;
        }
      }

      if(materialSets.length == 0)
      {
        defMtlSetDlg.materialSetSelection.options.length = 0;
        document.getElementById("defMtlSetDlg_SetNameVal").value = "";
      }
      else
      {
        defMtlSetDlg.materialSetSelection.options.length = 0;
        for ( let i =0; i< materialSets.length; i++)
        {
          var option = document.createElement("option");
          option.text = materialSets[i].getMaterialSetTitle();
          if(i==0) document.getElementById("defMtlSetDlg_SetNameVal").value = option.text;
          defMtlSetDlg.materialSetSelection.add(option);
        }
        defMtlSetDlg.selectedMaterialSet = materialSets[0];
      }
      poi3dConnector.getLeftDocument().setMaterialSets(materialSets);

      updateMaterialSetSelection(materialSets);
    };//defMtlSetDlg.deleteCurrent

    defMtlSetDlg.copyCurrent = function()
    {
      let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();
      if(materialSets.length == 0) return;

      if(defMtlSetDlg.selectedMaterialSet != null)
      {
        var matCopy =  defMtlSetDlg.selectedMaterialSet.createCopy(false);
        materialSets.push(matCopy);
        poi3dConnector.getLeftDocument().getMaterialSetObject().setLocalChangeFlag(true);

        var option = document.createElement("option");
        option.text = matCopy.getMaterialSetTitle();
        defMtlSetDlg.materialSetSelection.add(option);
        defMtlSetDlg.materialSetSelection.selectedIndex = materialSets.length-1;
        defMtlSetDlg.selectedMaterialSet = materialSets[defMtlSetDlg.materialSetSelection.selectedIndex];
        document.getElementById("defMtlSetDlg_SetNameVal").value = matCopy.getMaterialSetTitle();
      }
    };//defMtlSetDlg.copyCurrent

    defMtlSetDlg.deactivateMatSet = function()
    {
      if(currentMaterialSetRef != null)
      {
        currentMaterialSetRef.deleteFromEntities(leftModel);
        currentMaterialSetRef = null;
        currentMaterialSetCopy = null;
        document.getElementById("defMtlSetDlg_ActSetNameVal").value = "";
        myCmiWindow.drawScene();
      }
    }

    defMtlSetDlg.activateMatSet = function()
    {
      if(defMtlSetDlg.selectedMaterialSet != null)
      {
        if(currentMaterialSetRef != null)
          currentMaterialSetRef.deleteFromEntities(leftModel);

        currentMaterialSetRef = defMtlSetDlg.selectedMaterialSet;
        currentMaterialSetCopy = currentMaterialSetRef.createCopy(true);

        currentMaterialSetRef.applyToEntities(leftModel);

        defMtlSetDlg.activeSetTitle.value = currentMaterialSetRef.getMaterialSetTitle();

        myCmiWindow.drawScene();
      }
    }

    defMtlSetDlg.renameActive  = function()
    {
      let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();
      if(defMtlSetDlg.selectedMaterialSet != null)
      {
        let matSetName = document.getElementById("defMtlSetDlg_SetNameVal").value;

        if(matSetName.length > 0)
        {
          var foundMaterial = materialSets.find(item => item.getMaterialSetTitle() === matSetName);
          if(foundMaterial == null)
          {
            defMtlSetDlg.selectedMaterialSet.setMaterialSetTitle(matSetName);
            defMtlSetDlg.materialSetSelection[defMtlSetDlg.materialSetSelection.selectedIndex].text = matSetName;

            if(currentMaterialSetRef != null)
              defMtlSetDlg.activeSetTitle.value = matSetName;
          }
          poi3dConnector.getLeftDocument().getMaterialSetObject().setLocalChangeFlag(true);
        }//if(matSetName.length > 0)
      }//if(defMtlSetDlg.selectedMaterialSet != null)
      updateMaterialSetSelection(materialSets);
    };

    defMtlSetDlg.initialize = function()
    {
      let materialSets = poi3dConnector.getLeftDocument().getMaterialSets();
      defMtlSetDlg.materialSetSelection.options.length = 0;

      document.getElementById("defMtlSetDlg_SetNameVal").value = "";
      for ( var i =0; i< materialSets.length; i++)
      {
        var option = document.createElement("option");
        option.text = materialSets[i].getMaterialSetTitle();
        defMtlSetDlg.materialSetSelection.add(option);

        if(i==0)
        {
          document.getElementById("defMtlSetDlg_SetNameVal").value = materialSets[0].getMaterialSetTitle();
          defMtlSetDlg.selectedMaterialSet = materialSets[0];
        }
      }

      if(currentMaterialSetRef != null)
      {
        defMtlSetDlg.activeSetTitle.value = currentMaterialSetRef.getMaterialSetTitle();
      }
      else
      {
        defMtlSetDlg.activeSetTitle.value = "";
      }
    };//defMtlSetDlg.initialize
  }//if (!defMtlSetDlg)


  //init
  defMtlSetDlg.initialize();
  defMtlSetDlg.showDialog(parentDlg);

  function defMtlSetDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "dmsCancel":
      case "close":
        break;
      default:
        defMtlSetDlg.dialog.style.display = 'block';
        break;
    }//switch(btnName)
  }//function defMtlSetDlgCbk(btnName)
}//function showDefMtlSetDlg()

function showRegUserDlg(parentDlg,context)
{
  if (!regUserDlg)
  {
    regUserDlg = new DialogBox('regUserDlg', regUserDlgCbk, cmiCanvas);
    regUserDlg.statusOutput = document.getElementById("regUserDlg_StateVal");
    regUserDlg.uName = document.getElementById("regUserDlg_UserNameVal");
    regUserDlg.uPwd = document.getElementById("regUserDlg_UserPwdVal");
    regUserDlg.email = document.getElementById("registerUserDialogUserEmailValue");
    regUserDlg.isAuthor = document.getElementById("regUserDlg_IsAuthorVal");
    regUserDlg.adminCreation = false;

    regUserDlg.onShowPwd = function()
    {
      var pwdInput = document.getElementById("regUserDlg_UserPwdVal");

      if (pwdInput.type === "password")
        pwdInput.type = "text";
      else
        pwdInput.type = "password";
    }

    regUserDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      switch(currentStatus)
      {
        case "checkLoginNameExistanceUserExists":
          if(poi3dConnector.getUserSettings().uiLanguage == "de")
            regUserDlg.statusOutput.innerHTML = "Benutzer existiert bereits";
          else
            regUserDlg.statusOutput.innerHTML = textToDisplay;
          break;
        case "checkLoginNameExistanceUserNotExists":
          if(regUserDlg.adminCreation == true)
            poi3dConnector.createUser(regUserDlg.uName.value,regUserDlg.uPwd.value,regUserDlg.email.value,"s",true);
          else if(regUserDlg.isAuthor.checked == true)
            poi3dConnector.createUser(regUserDlg.uName.value,regUserDlg.uPwd.value,regUserDlg.email.value,"c",false);
          else
            poi3dConnector.createUser(regUserDlg.uName.value,regUserDlg.uPwd.value,regUserDlg.email.value,"u",false);
          break;
        case "createUserSuccess":
          if(regUserDlg.adminCreation == true)
            regUserDlg.dialog.style.display = 'none';

          regUserDlg.uName.value = "";
          regUserDlg.uPwd.value = "";
          regUserDlg.email.value = "";
          regUserDlg.isAuthor.checked = false;
          regUserDlg.statusOutput.innerHTML = "";
          regUserDlg.adminCreation = false;

          showMsgDlg(regUserDlg,poi3dConnector.getMessage(33));//User successfully created

          break;
        case "createUserError":
        default:
          regUserDlg.statusOutput.innerHTML = textToDisplay;
      }
    }//regUserDlg.onStatusUpdate

    poi3dConnector.registerCallback("userRegistrationDlgStatusUpdate",regUserDlg.onStatusUpdate);
  }//if (!regUserDlg)

  if(context == "AdminCreation")
  {
    regUserDlg.adminCreation = true;
    Poi3dHelpers.setDisplayStyle("regUserDlg_IsAuthorRow","none");
  }
  else
  {
    regUserDlg.adminCreation = false;
    Poi3dHelpers.setDisplayStyle("regUserDlg_IsAuthorRow","table-row");
  }

  if(regUserDlg.adminCreation == true)
    document.getElementById("regUserDlg_Hint").innerHTML = "Create Portal Administrator";
  else
    document.getElementById("regUserDlg_Hint").innerHTML = "";

  if(poi3dConnector.getPoi3dUser().isAdmin()||(regUserDlg.adminCreation == true))
  {
    if(poi3dConnector.isUserLimitReached() == true)
      showMsgDlg(regUserDlg,poi3dConnector.getMessage(9));//Max. number of users reached
    else
    {
      regUserDlg.showDialog(parentDlg);
    }
  }
  else
    showMsgDlg(regUserDlg,poi3dConnector.getMessage(49));//You do not have administrator rights

  function regUserDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      regUserDlg.dialog.style.display = 'block';
      let uName = regUserDlg.uName.value;
      let uPwd = regUserDlg.uPwd.value;
      let email = regUserDlg.email.value;

      if((poi3dConnector.isValidPassword(uPwd)==false) || (poi3dConnector.isValidUserName(uName)==false))
      {
        if(poi3dConnector.getUserSettings().uiLanguage == "de")
          regUserDlg.statusOutput.innerHTML = "UngÃ¼ltiger Benutzername/Passwort <br>min. 8 Zeichen, <br>kein \"->\", \"\\\", \"&\", \" \' \", \" \" \" erlaubt";
        else
          regUserDlg.statusOutput.innerHTML = "Invalid user name or password <br>min. 8 characters, <br>no \"->\", \"\\\", \"&\", \" \' \", \" \" \" allowed";
      }
      else
      {
        if(poi3dConnector.isValidEmail(email)==false)
        {
          if(poi3dConnector.getUserSettings().uiLanguage == "de")
            regUserDlg.statusOutput.innerHTML = "Ungültige Email Adresse";
          else
            regUserDlg.statusOutput.innerHTML = "Invalid email address";
          return;
        }

        poi3dConnector.checkLoginNameExistance(uName);
      }
    }
    else
    {
      regUserDlg.statusOutput.innerHTML = "";
      regUserDlg.isAuthor.checked = false;
    }
  }//function regUserDlgCbk(btnName)
}//function showRegUserDlg()

function showDwnldDlg(parentDlg)
{
  if (!dwnldDlg)
  {
    dwnldDlg = new DialogBox('dwnldDlg', dwnldDlgCbk, cmiCanvas);

    dwnldDlg.downloadFile  = function(fName)
    {
     let dldDir =  portalSettings.downloadDir;

      window.open(dldDir + "/" + fName,'_blank');
    }
  }

  dwnldDlg.showDialog(parentDlg);

  function dwnldDlgCbk(btnName)
  {
  }
}//function showDwnldDlg()

function showMultSelDlg(parentDlg,context,dlgData,callback)
{
  if (!multSelDlg)
  {
    multSelDlg = new DialogBox('multSelDlg', multSelDlgCbk, cmiCanvas);
    multSelDlg.selection = document.getElementById("multSelDlg_Sel");
  }

  multSelDlg.initSelections = function(context,dlgData)
  {
    multSelDlg.selection.options.length = 0;

    if(context == "CmpCtxFileAttDefineCmd")
    {
      let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();
      for ( var i =0; i< fileAttachments.length; i++)
      {
        var option = document.createElement("option");
        option.text = fileAttachments[i].getTitle() + " (" + fileAttachments[i].getFileName()+ " )";
        option.selected = fileAttachments[i].hasEntity(dlgData);

        multSelDlg.selection.add(option);
      };
    }//if(context == "FileAttDefine")
    else if(context == "DoBoPropCtxImportPropCmd")
    {
      var modelAttTtls = poi3dConnector.getModelAttributeTitlesFromEntityArray(dlgData);

      for ( var i =0; i< modelAttTtls.length; i++)
      {
        var option = document.createElement("option");
        option.text = modelAttTtls[i];
        multSelDlg.selection.add(option);
      };
    }
    else if(context == "exportCatalog")
    {
      for ( var i =0; i< multSelDlg.dlgData.length; i++)
      {
        var option = document.createElement("option");
        option.text = multSelDlg.dlgData[i].getTitle();
        option.poi3dCtlg = multSelDlg.dlgData[i];
        multSelDlg.selection.add(option);
      };
    }
  };//multSelDlg.initSelections

  multSelDlg.callback = callback;
  multSelDlg.context = context;
  multSelDlg.dlgData = dlgData;
  multSelDlg.initSelections(context,dlgData);

  if((poi3dConnector.hasUserAuthorRights() == false)&&(context == "FileAttDefine"))
    showMsgDlg(multSelDlg,poi3dConnector.getMessage(4));//"You must be logged in as an author to use this function"
  else
  {
    multSelDlg.showDialog(parentDlg);
  }

  function multSelDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      switch(multSelDlg.context)
      {
        case "CmpCtxFileAttDefineCmd":
          let fileAttachments = poi3dConnector.getLeftDocument().getFileAttachments();
          for ( var i =0; i< fileAttachments.length; i++)
          {
            if(multSelDlg.selection[i].selected == true)
              fileAttachments[i].addEntities([multSelDlg.dlgData]);
            else
              fileAttachments[i].removeEntities([multSelDlg.dlgData]);
          }
          poi3dConnector.getLeftDocument().getFileAttachmentObject().setLocalChangeFlag(true);
          break;
        case "DoBoPropCtxImportPropCmd":
          var ttlArray = new Array();

          for ( var i =0; i< multSelDlg.selection.length; i++)
          {
            if(multSelDlg.selection[i].selected == true)
              ttlArray.push(multSelDlg.selection[i].text);
          }
          if(multSelDlg.callback != null) multSelDlg.callback(ttlArray);
          break;
        case "exportCatalog":
          var ctlgEntrArray = new Array();

          for ( var i =0; i< multSelDlg.selection.length; i++)
          {
            if(multSelDlg.selection[i].selected == true)
              ctlgEntrArray.push(multSelDlg.selection[i].poi3dCtlg);
          }
          if(ctlgEntrArray.length > 0)
          {
            docMgmtDlg.statusOutput.innerHTML = "exporting...";
            poi3dConnector.exportCatalog(ctlgEntrArray);
          }
          break;
      }
    }//if (btnName == 'ok')
  }//function multSelDlgCbk(btnName)
}//function showMultSelDlg()

function showTxtInputDlg(parentDlg,context,userList)
{
  if (!txtInputDlg)
  {
    txtInputDlg = new DialogBox('txtInputDlg', txtInputDlgCbk, cmiCanvas);
    txtInputDlg.ignoreReturnKey();
    txtInputDlg.inputText = document.getElementById("txtInputDlg_Text");
  }

  txtInputDlg.context = context;

  if(txtInputDlg.context == "SendAbuseMail")
    txtInputDlg.inputText.value = "";

  txtInputDlg.showDialog(parentDlg);

  function txtInputDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      let msgText = "";
      switch(txtInputDlg.context)
      {
        case "SendMail":
          msgText = txtInputDlg.inputText.value.replace(/(?:\r\n|\r|\n)/g, '<br>');
          poi3dConnector.sendMessageToUsers(userList,msgText);
          break;
        case "SendAbuseMail":
          msgText = txtInputDlg.inputText.value.replace(/(?:\r\n|\r|\n)/g, '<br>');
          msgText = "Abuse report<br>" + msgText;
          poi3dConnector.sendMessageToUsers(userList,msgText);
          break;
      }
    }
  }
}//function showTxtInputDlg

function showImgGalDlg(parentDlg,whichDoc,docArray,currWg)
{
  if (!imgGalDlg)
  {
    imgGalDlg = new DialogBox('imgGalDlg', imgGalDlgCbk, cmiCanvas);
    imgGalDlg.ignoreReturnKey();
    imgGalDlg.whichDoc = "primary";
    imgGalDlg.currWg = null;
    imgGalDlg.currDoc = null;
    imgGalDlg.docArray = null;
    imgGalDlg.docTitleVal = document.getElementById("imgGalDlg_DocTitleVal");
    imgGalDlg.docDescVal = document.getElementById("imgGalDlg_DocDescVal");

    imgGalDlg.swiper = new Swiper(".poi3dSwiper",
    {
      rewind: true,
      pagination: {
        el: ".swiper-pagination",
        type: "fraction",
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });

    imgGalDlg.swiper.on('realIndexChange', function (theEvent)
    {
      imgGalDlg.currDoc  = imgGalDlg.docArray[theEvent.realIndex];
      imgGalDlg.updateDocInfo();
    });

    imgGalDlg.updateDocInfo = function()
    {
      if(imgGalDlg.currDoc == null)
      {
        imgGalDlg.docTitleVal.innerHTML = "";
        imgGalDlg.docDescVal.innerHTML = "";
      }
      else
      {
        imgGalDlg.docTitleVal.innerHTML = imgGalDlg.currDoc.getTitle();
        imgGalDlg.docDescVal.innerHTML = imgGalDlg.currDoc.getDescription();
      }
    };
    imgGalDlg.onImageClick = function()
    {
      imgGalDlgCbk('ok');
    }
    imgGalDlg.initialize = function()
    {
      let swiperCollection = document.getElementById("imgGalDlg_Swiper");
      while (swiperCollection.firstChild) {swiperCollection.firstChild.remove()};
      imgGalDlg.currDoc = null;

      for ( let i =0; i< imgGalDlg.docArray.length; i++)
      {
        let swiperSlide = document.createElement("div");
        swiperSlide.classList.add("swiper-slide");
        swiperCollection.append(swiperSlide);

        let swiperImage = document.createElement("img");
        swiperImage.addEventListener('click',imgGalDlg.onImageClick)
        swiperSlide.append(swiperImage);
        swiperImage.src = imgGalDlg.docArray[i].getPreviewUrl(poi3dConnector.getPoi3dUser(),"read");
      }
      if(imgGalDlg.docArray.length > 0)
      {
        imgGalDlg.currDoc = imgGalDlg.docArray[0];
        imgGalDlg.swiper.update();
        imgGalDlg.swiper.slideTo(0, 700, false);
      }

      imgGalDlg.updateDocInfo();
    }//imgGalDlg.initialize
  };//if (!imgGalDlg)

  imgGalDlg.docArray = docArray;
  imgGalDlg.whichDoc = whichDoc;
  imgGalDlg.currWg = currWg;

  imgGalDlg.initialize();

  imgGalDlg.showDialog(parentDlg);

  function imgGalDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      if(imgGalDlg.currDoc != null)
      {
        if(imgGalDlg.whichDoc == "primary")
        {
          Poi3dDocumentLoader.loadPrimaryDocument(myCmiWindow,imgGalDlg.currDoc);
          poi3dConnector.setCurrentWgOrCatalog(imgGalDlg.currWg);
        }
        else
          Poi3dDocumentLoader.loadSecondaryDocument(myCmiWindow,imgGalDlg.currDoc);
      }
    }
    else
      modSelDlg.dialog.style.display = 'block';

    imgGalDlg.dialog.style.display = 'none';
  }//function imgGalDlgCbk
}//function showImgGalDlg

function showFeatDlg(parentDlg,context)
{
  if(!featDlg)
  {
    featDlg = new DialogBox('featDlg', featDlgCbk, cmiCanvas);
    featDlg.ignoreReturnKey();

    featDlg.updateUi = function()
    {
      let set = null;
      if(featDlg.context == "portalSettings")
        set = ptlSetDlg.portalSettings.attRights;
      else if(featDlg.context == "groupSettings")
        set = docMgmtDlg.currGroupFeatures;

      if(set != null)
      {
        document.getElementById("featDlg_ChatUseVal").value = set[0];
        document.getElementById("featDlg_AnnUseVal").value = set[1];
        document.getElementById("featDlg_InstrUseVal").value = set[2];
        document.getElementById("featDlg_MatUseVal").value = set[3];
        document.getElementById("featDlg_FattUseVal").value = set[4];
        document.getElementById("featDlg_BomUseVal").value = set[5];
        document.getElementById("featDlg_SnsUseVal").value = set[6];
        document.getElementById("featDlg_LocUseVal").value = set[7];
        document.getElementById("featDlg_DocAttrUseVal").value = set[8];
      }
    };//featDlg.updateUi
  }//if(!featDlg)

  featDlg.context = context;
  featDlg.updateUi();

  featDlg.showDialog(parentDlg);

  function featDlgCbk(btnName)
  {
    if (btnName == 'ok')
    {
      let set = null;
      if(featDlg.context == "portalSettings")
        set = ptlSetDlg.portalSettings.attRights;
      else if(featDlg.context == "groupSettings")
        set = docMgmtDlg.currGroupFeatures;

      if(set != null)
      {
        set[0] = document.getElementById("featDlg_ChatUseVal").value;
        set[1] = document.getElementById("featDlg_AnnUseVal").value;
        set[2] = document.getElementById("featDlg_InstrUseVal").value;
        set[3] = document.getElementById("featDlg_MatUseVal").value;
        set[4] = document.getElementById("featDlg_FattUseVal").value;
        set[5] = document.getElementById("featDlg_BomUseVal").value;
        set[6] = document.getElementById("featDlg_SnsUseVal").value;
        set[7] = document.getElementById("featDlg_LocUseVal").value;
        set[8] = document.getElementById("featDlg_DocAttrUseVal").value;
      }
    }
  }//featDlgCbk
};//showFeatDlg

function showAiChatDlg(parentDlg)
{
  if (!aiChatDlg)
  {
    aiChatDlg = new DialogBox('aiChatDlg', aiChatDlgCbk, cmiCanvas);
    aiChatDlg.chatInputText = document.getElementById("aiChatDlg_ChatInputTxt");
    aiChatDlg.chatEntries = document.getElementById("aiChatDlg_chatContent");
    aiChatDlg.chatContentArea = document.getElementById("aiChatDlg_chatContentArea");
    aiChatDlg.aiChat = poi3dConnector.getPoi3dUser().getChatObject();
    aiChatDlg.currentBot = null;
    aiChatDlg.lastBotAnswerPos = -1;

    aiChatDlg.onAiBotSelect = function(selectObj)
    {
      aiChatDlg.currentBot = selectObj.options[selectObj.selectedIndex].aiBot;
    };//aiChatDlg.onAiBotSelect

    aiChatDlg.updateChatSection = function(threadId)
    {
      var rowCount = aiChatDlg.chatEntries.rows.length;
      for ( var i = 0; i<rowCount; i++)
      {
        aiChatDlg.chatEntries.deleteRow(-1);
      };

      var chatEntries = aiChatDlg.aiChat.getChatEntries();
      if(chatEntries != null)
      {
        let aliasName = poi3dConnector.getPoi3dUser().getAliasName();
        let replyText = "";
        let replyToId = "";
        let replyToEntry = null;

        for ( let i = 0; i<chatEntries.length; i++)
        {
          if((threadId.length == 0)||(chatEntries[i].getThreadId() == threadId))
          {
            row = aiChatDlg.chatEntries.insertRow(-1);
            cell = row.insertCell(0);

            replyToId = chatEntries[i].getRepToId();

            if(chatEntries[i].getUserAliasName() == aliasName)
              replyText = "<span class=\"chatInfo\">"+chatEntries[i].getDateString()+":</span></br>";
            else
              replyText = "<span class=\"chatInfo\">"+chatEntries[i].getUserAliasName()+" "+chatEntries[i].getDateString()+":</span></br>";

            if(replyToId.length > 0)
            {
              replyToEntry = poi3dConnector.getChatEntryById(null,replyToId);
              if(replyToEntry != null)
              {
                let replyFromText = replyToEntry.getText();

                if(replyToEntry.getImageFlag() == true)
                {
                  let startIndex = replyFromText.indexOf(".png'>");
                  if (startIndex > 0)
                    replyFromText = replyFromText.slice(startIndex+6);
                  else
                    replyFromText = "Reply to " + replyToEntry.getUserAliasName();
                }

                let plainText = document.createElement('div');
                plainText.innerHTML = replyFromText;
                replyFromText = plainText.innerText || plainText.textContent;
                replyFromText = replyFromText.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g, ' ').trim();

                replyText = replyText + "<span class=\"chatReplyEntry\">"+replyToEntry.getUserAliasName()+":</br>"+replyFromText.substr(0,30) + "...</span></br>" ;
              }
            }//if(replyToId.length > 0)


            if(chatEntries[i].getUserAliasName() == aliasName)
            {
              cell.className = "ownChatEntry";
            }
            else
            {
              cell.className = "extChatEntry";
            }
            cell.innerHTML = replyText + "<span>"+chatEntries[i].getText() + "</span>";
          }//if((threadId.length == 0)||(chatEntries[i].getThreadId() == threadId))

        };

        aiChatDlg.lastBotAnswerPos = chatEntries.length-1;
        aiChatDlg.chatContentArea.scrollTop = aiChatDlg.chatContentArea.scrollHeight;
      }//if(chatEntries != null)
    };//aiChatDlg.updateChatSection = function()

    aiChatDlg.clearChat = function()
    {
      aiChatDlg.aiChat.clearEntries();
      aiChatDlg.lastBotAnswerPos = -1;
      aiChatDlg.updateChatSection("");
    };//aiChatDlg.clearChat()

    aiChatDlg.sendChatEntry = function()
    {
      if(aiChatDlg.chatInputText.value.length >0)
      {
        let chatText = "@" + aiChatDlg.currentBot.getBotName() + ":" + aiChatDlg.chatInputText.value;
        let chatEntry = poi3dConnector.askChatBot(aiChatDlg.aiChat,chatText,aiChatDlg.lastBotAnswerPos);

        if(chatEntry != null)
          aiChatDlg.updateChatSection("");

        aiChatDlg.chatInputText.value = "";
        aiChatDlg.lastBotAnswer = -1;
      }
    };//aiChatDlg.sendChatEntry

    //init
    let aiBots = poi3dConnector.getAiBotCfg();
    aiChatDlg.aiChat.setAiBots(aiBots);
    aiChatDlg.aiChat.setOnChangedCallback(aiChatDlg.updateChatSection);
    let aiBotSel = document.getElementById("aiChatDlg_AiBotSel");
    let aiBotEntry;

    for ( let i = 0; i<aiBots.length; i++)
    {
      if(i == 0)
        aiChatDlg.currentBot =  aiBots[i];

      aiBotEntry = document.createElement("option");
      aiBotEntry.text = aiBots[i].getBotName();
      aiBotEntry.aiBot = aiBots[i];
      aiBotSel.add(aiBotEntry);
    };

    if(aiBots.length == 0)
    {
      document.getElementById("aiChatDlg_ChatSendBut").enabled = false;
      document.getElementById("aiChatDlg_ChatSendBut").style.filter = "blur(2px)";
    }

  };//if (!aiChatDlg)

  aiChatDlg.showDialog(parentDlg);
  aiChatDlg.updateChatSection("");

  function aiChatDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "cancel":
      case "close":
        break;
      case "save":
        poi3dConnector.saveUserChat();
        aiChatDlg.dialog.style.display = 'block';
        break;
      default:
        aiChatDlg.dialog.style.display = 'block';
        break;
    };
  };

};//showAiChatDlg

function showCommDlg(parentDlg)
{
  if (!commDlg)
  {
    commDlg = new DialogBox('commDlg', commDlgCbk, cmiCanvas);
    commDlg.ignoreReturnKey();
    commDlg.activeSection = "";
    commDlg.clickedChatRow = -1;
    commDlg.documentUsers = null;
    commDlg.users = new Array();
    commDlg.selectedUsers = new Array();
    commDlg.context = "";
    commDlg.contextObject = null;

    //--------------  Common ---------------------------------------------------------------------

    commDlg.onTabSelectionChange  = function(sectionToActivate)
    {
      commDlg.activeSection = sectionToActivate;

      if(sectionToActivate == "commDlg_ChatSection")
      {
        Poi3dHelpers.setDisplayStyle("commDlg_ChatSection","block");
        Poi3dHelpers.setDisplayStyle("commDlg_VideoSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_EmailSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_NotfSection","none");
        document.getElementById("commDlg_ChatTabVal").checked = true;

        commDlg.chatContentArea.scrollTop = commDlg.chatContentArea.scrollHeight;
        poi3dConnector.startChatUpdate(commDlg.contextObject);
        commDlg.stopVideo();
      }
      else if((sectionToActivate == "commDlg_VideoSection")&&(commDlg.canDoVideoChat == true))
      {
        Poi3dHelpers.setDisplayStyle("commDlg_ChatSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_VideoSection","block");
        Poi3dHelpers.setDisplayStyle("commDlg_EmailSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_NotfSection","none");
        document.getElementById("commDlg_VideoTabVal").checked = true;

        poi3dConnector.stopChatUpdate(commDlg.contextObject);

        if(commDlg.videoConnected == true)
        {
          if(commDlg.intVideoStream.getVideoTracks()[0] == commDlg.bgVideoTrack)
            document.getElementById("commDlg_BgVideo").play();
        }
        else
          commDlg.updateIntVideoStream(commDlg.bgVideoTrack);
      }
      else if(sectionToActivate == "commDlg_EmailSection")
      {
        Poi3dHelpers.setDisplayStyle("commDlg_ChatSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_VideoSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_EmailSection","block");
        Poi3dHelpers.setDisplayStyle("commDlg_NotfSection","none");
        document.getElementById("commDlg_EmailTabVal").checked = true;

        poi3dConnector.stopChatUpdate(commDlg.contextObject);
        commDlg.stopVideo();
      }
      else if(sectionToActivate == "commDlg_NotfSection")
      {
        Poi3dHelpers.setDisplayStyle("commDlg_ChatSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_VideoSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_EmailSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_NotfSection","block");
        document.getElementById("commDlg_NotfTabVal").checked = true;

        commDlg.pushContentArea.scrollTop = commDlg.pushContentArea.scrollHeight;
        poi3dConnector.stopChatUpdate(commDlg.contextObject);
        commDlg.stopVideo();
      }
    };//commDlg.onTabSelectionChange

    commDlg.selectUsers = function()
    {
      showUSelDlg(commDlg,"commDlg",commDlg.selectedUsers,commDlg.users);
    };//commDlg.selectUsers

    commDlg.resetUsers = function()
    {
      commDlg.selectedUsers = new Array();
      document.getElementById("commDlg_EmailToVal").innerHTML = "";
    };//commDlg.selectUsers
    
    commDlg.onContextChanged = function()
    {
      let contextSelection = document.getElementById("commDlg_CtxVal");
      if(contextSelection.selectedIndex == -1)
      {
        poi3dConnector.stopChatUpdate(commDlg.contextObject);
        commDlg.context = "";
        commDlg.users = new Array();
        commDlg.contextObject = null;
      }
      else
      {
        poi3dConnector.stopChatUpdate(commDlg.contextObject);
        let currOpt = contextSelection.options[contextSelection.selectedIndex];
        commDlg.context = currOpt.ctx;
        commDlg.users = currOpt.users;
        commDlg.contextObject = currOpt.ctxObj;
        poi3dConnector.startChatUpdate(commDlg.contextObject);
      }

      commDlg.updateChatSection("");
      commDlg.updateVideoChatSection();
      commDlg.updateEmailSection("");
    };//commDlg.onContextChanged
    
    commDlg.initContextUsers = function()
    {
      let contextSelection = document.getElementById("commDlg_CtxVal");
      let ctxOption = null;
      
      contextSelection.options.length = 0;
      if(poi3dConnector.isDocumentAccessible())
      {
        ctxOption = document.createElement("option");
        ctxOption.text = poi3dConnector.getUiText("mnuDocTtipTtl");
        ctxOption.ctx = "doc";
        ctxOption.ctxObj = poi3dConnector.getLeftDocument();
        ctxOption.users = poi3dConnector.getDocumentUsers();
        contextSelection.add(ctxOption);
      }
      
      let userWorkGroups = poi3dConnector.getUserWorkGroups();
      for ( var i =0; i< userWorkGroups.length; i++)
      {
        if((userWorkGroups[i].getWgState() != "rejected")&&(userWorkGroups[i].getWgState() != "deleted")&&(userWorkGroups[i].getWgState() != "error"))
        {
          ctxOption = document.createElement("option");
          ctxOption.text = userWorkGroups[i].getTitle();
          ctxOption.ctx = "grp";
          ctxOption.ctxObj = userWorkGroups[i];
          ctxOption.users = userWorkGroups[i].getGroupUsers();

          if(userWorkGroups[i].isOwner(poi3dConnector.getPoi3dUser()))
            ctxOption.style.fontWeight = "bold";

          contextSelection.add(ctxOption);
        }
      }      
    };//commDlg.initContextUsers
    
    commDlg.initSelections = function()
    {
      commDlg.documentUsers = poi3dConnector.getDocumentUsers();
      commDlg.initContextUsers();
      commDlg.onContextChanged();
      commDlg.updateNotificationSection();
    };//commDlg.initSelections
        
    //----------  Chat ----------------------------------------------------------------------------
    commDlg.chatInputText = document.getElementById("commDlg_ChatInputTxt");
    commDlg.chatEntries = document.getElementById("commDlg_chatContent");
    commDlg.chatContentArea = document.getElementById("commDlg_chatContentArea");
    commDlg.chatReplyText = document.getElementById("commDlg_ChatReplyToTtl");
    commDlg.imageToStore = null;

    commDlg.onImgSelected = function()
    {
      if(imgOpenDlg.isImageSelected == true)
      {
        commDlg.imageToStore = imgOpenDlg.imageElement;
        document.getElementById("commDlg_ChatPvImg").style.filter = "invert(0%)";
        document.getElementById("commDlg_ChatPvImg").src = imgOpenDlg.imageElement.src;
      }
      else
      {
        commDlg.imageToStore = null;
        document.getElementById("commDlg_ChatPvImg").style.filter = "invert(var(--IconInvert))";
        document.getElementById("commDlg_ChatPvImg").src = "./Poi3d/Images/picture-frame.png";
      }
    };

    commDlg.copyTextToClipboard = function(rowNr)
    {
      let chatEntry = null;

      if(rowNr != undefined)
        commDlg.clickedChatRow = rowNr;

      let chatEntries = poi3dConnector.getChatEntries(commDlg.contextObject);
      chatEntry = chatEntries.find((cEntry) => cEntry.rowNr === commDlg.clickedChatRow);
      commDlg.clickedChatRow = chatEntry.rowNr;

      if(chatEntry != null)
      {
        let plainText = document.createElement('div');
        plainText.innerHTML = chatEntry.getText();

        let textToCopy = plainText.innerText || plainText.textContent;
        textToCopy = textToCopy.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
        
        navigator.clipboard.writeText(textToCopy);
      }
    };

    commDlg.replyToChat = function(rowNr)
    {
      let chatEntry = null;

      if(rowNr != undefined)
        commDlg.clickedChatRow = rowNr;

      //chatEntry = poi3dConnector.getChatEntryByRowNr(commDlg.contextObject,commDlg.clickedChatRow);

      //consider filter
      let chatEntries = poi3dConnector.getChatEntries(commDlg.contextObject);
      chatEntry = chatEntries.find((cEntry) => cEntry.rowNr === commDlg.clickedChatRow);
      commDlg.clickedChatRow = chatEntry.rowNr;

      if(chatEntry != null)
      {
        let plainText = document.createElement('div');
        plainText.innerHTML = chatEntry.getText();

        let replyFromText = plainText.innerText || plainText.textContent;
        replyFromText = replyFromText.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
        let userAlias = chatEntry.getUserAliasName();

        if((replyFromText.length == 0) || (chatEntry.getImageFlag() == true))
          commDlg.chatReplyText.innerHTML="Reply to " + userAlias;
        else
        {
          commDlg.chatReplyText.innerHTML=replyFromText.substr(0,30) + "...";

          if(poi3dConnector.isUserAiBot(userAlias))
            commDlg.chatInputText.value = "@" + userAlias + ":";
          else
            commDlg.chatInputText.value = "";
        }
      }
      else
      {
        commDlg.chatReplyText.innerHTML="";
        commDlg.clickedChatRow = -1;
      }
    };

    commDlg.cancelReplyTo = function()
    {
      commDlg.chatReplyText.innerHTML="";
      commDlg.chatInputText.value = "";
      commDlg.clickedChatRow = -1;
    };

    commDlg.chatUpdated = function()
    {
      commDlg.updateChatSection("");
    };

    commDlg.filterChat = function(rowNr)
    {
      let chatEntry = null;

      if(rowNr != undefined)
        commDlg.clickedChatRow = rowNr;

      chatEntry = poi3dConnector.getChatEntryByRowNr(commDlg.contextObject, commDlg.clickedChatRow);

      if(chatEntry != null)
      {
        let threadId = chatEntry.getThreadId();
        commDlg.updateChatSection(threadId);
      }
    };

    commDlg.updateChatSection = function(threadId)
    {
      commDlg.chatReplyText.innerHTML="";
      commDlg.chatInputText.value = "";
      commDlg.clickedChatRow = -1;

      var rowCount = commDlg.chatEntries.rows.length;
      for ( var i = 0; i<rowCount; i++)
      {
        commDlg.chatEntries.deleteRow(-1);
      };

      var chatEntries = poi3dConnector.getChatEntries(commDlg.contextObject);
      if(chatEntries != null)
      {
        let aliasName = poi3dConnector.getPoi3dUser().getAliasName();
        let replyText = "";
        let replyToId = "";
        let replyToEntry = null;
        let clickCmd = "";
        let filteredRow = -1;

        for ( let i = 0; i<chatEntries.length; i++)
        {
          if(threadId.length > 0)
          {
            if(chatEntries[i].getThreadId() == threadId)
            {
              filteredRow++;
              chatEntries[i].rowNr = filteredRow;
            }
            else
              chatEntries[i].rowNr = -1;
          }
          else
            chatEntries[i].rowNr = i;

          if((threadId.length == 0)||(chatEntries[i].getThreadId() == threadId))
          {

            row = commDlg.chatEntries.insertRow(-1);
            cell = row.insertCell(0);

            replyToId = chatEntries[i].getRepToId();

            if(chatEntries[i].getUserAliasName() == aliasName)
              replyText = "<span class=\"chatInfo\">"+chatEntries[i].getDateString()+":</span></br>";
            else
              replyText = "<span class=\"chatInfo\">"+chatEntries[i].getUserAliasName()+" "+chatEntries[i].getDateString()+":</span></br>";

            if(replyToId.length > 0)
            {
              replyToEntry = poi3dConnector.getChatEntryById(commDlg.contextObject,replyToId);
              if(replyToEntry != null)
              {
                let replyFromText = replyToEntry.getText();

                if(replyToEntry.getImageFlag() == true)
                {
                  let startIndex = replyFromText.indexOf(".png'>");
                  if (startIndex > 0)
                    replyFromText = replyFromText.slice(startIndex+6);
                  else
                    replyFromText = "Reply to " + replyToEntry.getUserAliasName();
                }

                let plainText = document.createElement('div');
                plainText.innerHTML = replyFromText;
                replyFromText = plainText.innerText || plainText.textContent;
                replyFromText = replyFromText.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g, ' ').trim();

                replyText = replyText + "<span class=\"chatReplyEntry\">"+replyToEntry.getUserAliasName()+":</br>"+replyFromText.substr(0,30) + "...</span></br>" ;
              }
            }//if(replyToId.length > 0)

            if(chatEntries[i].getUserAliasName() == aliasName)
            {
              cell.className = "ownChatEntry";
              clickCmd = "";
            }
            else if(chatEntries[i].rowNr >= 0)
            {
              cell.className = "extChatEntry";
              clickCmd = " <nobr class='fntIcon' onclick='commDlg.replyToChat(" + chatEntries[i].rowNr + ")'>&#xE111;</nobr>";
            }

            cell.innerHTML = replyText + "<span>"+chatEntries[i].getText()+ clickCmd + "</span>";

          }//if((threadId.length == 0)||(chatEntries[i].getThreadId() == threadId))
        };//for ( let i = 0; i<chatEntries.length; i++)

        commDlg.chatContentArea.scrollTop = commDlg.chatContentArea.scrollHeight;
      }//if(chatEntries != null)
    };//commDlg.updateChatSection = function()

    commDlg.sendChatEntry = function()
    {
      if((commDlg.chatInputText.value.length >0)||(commDlg.imageToStore != null))
      {
        poi3dConnector.addChatEntry(commDlg.contextObject.getChatObject(),commDlg.chatInputText.value,commDlg.clickedChatRow,commDlg.imageToStore);
        commDlg.chatInputText.value = "";
        commDlg.chatReplyText.innerHTML="";
        commDlg.clickedChatRow = -1;
        commDlg.imageToStore = null;
        document.getElementById("commDlg_ChatPvImg").style.filter = "invert(var(--IconInvert))";
        document.getElementById("commDlg_ChatPvImg").src = "./Poi3d/Images/picture-frame.png";
      }
    };//commDlg.sendChatEntry = function()

    commDlg.disableChatSection = function()
    {
      Poi3dHelpers.setDisplayStyle("commDlg_chatTabLab","none");
      Poi3dHelpers.setDisplayStyle("commDlg_ChatTabVal","none");
      Poi3dHelpers.setDisplayStyle("commDlg_ChatSection","none");
    }

    //--------------  Video Chat ---------------------------------------------------------------------

    commDlg.intVideoStream = new MediaStream();
    commDlg.intView = document.getElementById('commDlg_IntVideoContent');
    commDlg.localStream = new MediaStream();
    commDlg.remoteStream = new MediaStream();
    commDlg.ringTone = new Audio("./Poi3d/Ressources/tuut.mp3");
    commDlg.ringTone.loop = true;
    commDlg.videoConnected = false;
    commDlg.canDoVideoChat = true;

    commDlg.screenStream = null;
    commDlg.cameraStream = null;
    commDlg.micStream = null;
    commDlg.screenTrack = null;
    commDlg.cameraTrack = null;
    commDlg.micTrack = null;
    commDlg.bgVideoTrack = null;
    commDlg.micUsable = -1;
    commDlg.camUsable = -1;
    commDlg.scrUsable = -1;

    commDlg.videoCallUpdated = function(message)
    {
      let callCheckbox = document.getElementById("commDlg_VideoCallSwitch");
      let img = document.getElementById('commDlgVideoChatCallImage');

      switch(message)
      {
        case "logoff":
          if(commDlg.videoConnected == true)
            poi3dConnector.endUserCall();
          img.style.animation = '';
          img.style.animationIterationCount = '';
          commDlg.ringTone.pause();
          commDlg.ringTone.currentTime = 0;
          poi3dConnector.endUserCall();
          commDlg.videoConnected = false;
          commDlg.stopExtVideo();
          break;
        case "callHangup":
          img.style.animation = '';
          img.style.animationIterationCount = '';
          commDlg.ringTone.pause();
          commDlg.ringTone.currentTime = 0;
          commDlg.videoConnected = false;
          commDlg.stopExtVideo();
          break;
        case "callAccepted":
          callCheckbox.checked = true;
          img.style.animation = '';
          img.style.animationIterationCount = '';
          commDlg.ringTone.pause();
          commDlg.ringTone.currentTime = 0;
          poi3dConnector.establishUserCall();
          break;
        case "callRejected":
          callCheckbox.checked = false;
          img.style.animation = '';
          img.style.animationIterationCount = '';
          commDlg.ringTone.pause();
          commDlg.ringTone.currentTime = 0;
          commDlg.videoConnected = false;
          showMsgDlg(commDlg,poi3dConnector.getMessage(62));
          break;
        case "updateExtTrack":
          document.getElementById('commDlg_ExtVideoContent').srcObject = commDlg.remoteStream;
          commDlg.videoConnected = true;
          break;
      }
    };

    commDlg.updateVideoChatSection = function()
    {
      let userSelection = document.getElementById("commDlg_VideoCallToSel");
      let callSwitch = document.getElementById("commDlg_VideoCallSwitch");
      let user = null;
      userSelection.options.length = 0;

      if(commDlg.users.length == 0)
        Poi3dHelpers.canBeUsed(callSwitch,false);
      else
        Poi3dHelpers.canBeUsed(callSwitch,true);

      for ( let i =0; i< commDlg.users.length; i++)
      {
        user = commDlg.users[i];
        if(user.userId != poi3dConnector.getCurrentUserId())
        {
          var option = document.createElement("option");
          option.text = commDlg.users[i].aliasName;
          option.userInfo = user;
          userSelection.add(option);
        }
      }
    };//commDlg.updateVideoChatSection

    commDlg.updateIntVideoStream = function(newTrack)
    {
      let tracks = commDlg.intVideoStream.getVideoTracks();
      tracks.forEach((track) =>
      {
        commDlg.intVideoStream.removeTrack(track);
      });

      if(newTrack)
      {
        commDlg.intVideoStream.addTrack(newTrack);

        if(newTrack == commDlg.bgVideoTrack)
          document.getElementById("commDlg_BgVideo").play();
        else
          document.getElementById("commDlg_BgVideo").pause();

        //https://stackoverflow.com/questions/23497037/change-the-videotrack-of-a-mediastream-object
        if(commDlg.videoConnected == true)
          poi3dConnector.changeSharedVideoTrack(newTrack);
      }
      else
        document.getElementById("commDlg_BgVideo").pause();

      commDlg.intView.srcObject = commDlg.intVideoStream;
    };//commDlg.updateIntVideoStream

    commDlg.switchCamera = function(camCheckbox)
    {
      if(camCheckbox.checked)
      {
        if(commDlg.cameraTrack)
          commDlg.switchToCamera();
        else
          commDlg.startCameraSharing();
      }
      else
        commDlg.switchOffCamera(commDlg.bgVideoTrack);
    };//commDlg.switchCamera

    commDlg.switchScreen = function(screenCheckbox)
    {
      if(screenCheckbox.checked)
      {
        if(commDlg.screenTrack)
          commDlg.switchToScreen();
        else
          commDlg.startScreenSharing();
      }
      else
        commDlg.switchOffScreen(commDlg.bgVideoTrack);
    };//commDlg.switchScreen

    commDlg.switchMic = function(micCheckbox)
    {
      if(commDlg.micTrack != null)
      {
        if(micCheckbox.checked)
          commDlg.micTrack.enabled = true;
        else
          commDlg.micTrack.enabled = false;
      }
      //Test
      commDlg.videoCallUpdated("updateExtTrack");
    };//commDlg.switchMic

    commDlg.switchOnMic = function ()
    {
      if(commDlg.micTrack) commDlg.micTrack.enabled = true;
      document.getElementById('commDlg_VideoMicSwitch').checked = true;
    };//commDlg.switchOffMic

    commDlg.switchOffMic = function ()
    {
      if(commDlg.micTrack) commDlg.micTrack.enabled = false;
      document.getElementById('commDlg_VideoMicSwitch').checked = false;
    };//commDlg.switchOffMic

    commDlg.switchOffCamera = function (newVideo)
    {
      commDlg.updateIntVideoStream(newVideo);
      document.getElementById('commDlg_VideoCamSwitch').checked = false;
    };//commDlg.switchOffCamera

    commDlg.switchOffScreen = function (newVideo)
    {
      commDlg.updateIntVideoStream(newVideo);
      document.getElementById('commDlg_VideoScrnSwitch').checked = false;
    };//commDlg.switchOffScreen

    commDlg.switchToCamera = function ()
    {
      if(commDlg.cameraTrack)
      {
        commDlg.updateIntVideoStream(commDlg.cameraTrack);
        document.getElementById('commDlg_VideoCamSwitch').checked = true;
        document.getElementById('commDlg_VideoScrnSwitch').checked = false;
      }
      else
        document.getElementById('commDlg_VideoCamSwitch').checked = false;

    };//commDlg.switchToCamera

    commDlg.switchToScreen = function ()
    {
      if(commDlg.screenTrack)
      {
        commDlg.updateIntVideoStream(commDlg.screenTrack);
        document.getElementById('commDlg_VideoCamSwitch').checked = false;
        document.getElementById('commDlg_VideoScrnSwitch').checked = true;
      }
      else
        document.getElementById('commDlg_VideoScrnSwitch').checked = false;
    };//commDlg.switchToScreen

    commDlg.startCameraSharing = async function ()
    {
      if((navigator.mediaDevices && navigator.mediaDevices.getUserMedia) == false) commDlg.camUsable = 0;
      if(commDlg.camUsable == 0) return;

      let mediaOptions =  window.constraints = {audio: false, video: true};
      try
      {
        commDlg.cameraStream = await navigator.mediaDevices.getUserMedia(mediaOptions);
        commDlg.cameraStream.getVideoTracks()[0].addEventListener("ended", () => commDlg.stopCameraSharing());
        commDlg.cameraTrack = commDlg.cameraStream.getVideoTracks()[0];

        if(commDlg.cameraTrack)
        {
          commDlg.camUsable = 1;
          commDlg.switchToCamera();
        }
      }
      catch (error)
      {
        commDlg.camUsable = 0;
        commDlg.cameraTrack = null;
        let switchButton = document.getElementById('commDlg_VideoCamSwitch');
        switchButton.checked = false;
        Poi3dHelpers.canBeUsed(switchButton,false);

        setStatusText('Error initiating camera sharing: ' + error.name, "fadeOut");
      }
    };//commDlg.startCameraSharing

    commDlg.stopCameraSharing = function ()
    {
      commDlg.switchOffCamera(null);

      if(commDlg.cameraStream)
      {
        let tracks = commDlg.cameraStream.getTracks();
        tracks.forEach((track) =>
        {
          track.stop();
          commDlg.cameraStream.removeTrack(track);
        });
        commDlg.cameraStream = null;
        commDlg.cameraTrack = null;
      }
    };//commDlg.stopCameraSharing

    commDlg.startMicSharing = async function (context,selectedUser)
    {
      if((navigator.mediaDevices && navigator.mediaDevices.getUserMedia) == false) commDlg.micUsable = 0;
      if(commDlg.micUsable == 0) return;

      let mediaOptions =  window.constraints = {audio: true, video: false};
      try
      {
        commDlg.micStream = await navigator.mediaDevices.getUserMedia(mediaOptions);
        commDlg.micStream.getAudioTracks()[0].addEventListener("ended", () => commDlg.stopMicSharing());
        commDlg.micTrack = commDlg.micStream.getAudioTracks()[0];

        if(commDlg.micTrack)
        {
          commDlg.micUsable = 1;
          commDlg.switchOnMic();
          if(context)//call with uninitialzed micro
          {
            if((context == "handleCall")&&(selectedUser))
            {
              commDlg.addTrackToLocalStream(commDlg.micTrack);
              commDlg.addTrackToLocalStream(commDlg.intVideoStream.getVideoTracks()[0]);

              poi3dConnector.callUser(selectedUser,commDlg.localStream,commDlg.remoteStream);
            }
            else if(context == "acceptCall")
            {
              commDlg.addTrackToLocalStream(commDlg.micTrack);
              commDlg.addTrackToLocalStream(commDlg.intVideoStream.getVideoTracks()[0]);

              poi3dConnector.acceptUserCall(commDlg.localStream,commDlg.remoteStream);
            }
          }//if(context)
        }//if(commDlg.micTrack)
      }
      catch (error)
      {
        commDlg.micUsable = 0;
        commDlg.micTrack = null;
        let switchButton = document.getElementById('commDlg_VideoMicSwitch');
        switchButton.checked = false;
        Poi3dHelpers.canBeUsed(switchButton,false);

        setStatusText('Error initiating microphone sharing: ' + error.name, "fadeOut");
      }
    };//commDlg.startCameraSharing

    commDlg.stopMicSharing = function ()
    {
      commDlg.switchOffMic();

      if(commDlg.micStream)
      {
        let tracks = commDlg.micStream.getTracks();
        tracks.forEach((track) =>
        {
          track.stop();
          commDlg.micStream.removeTrack(track);
        });
        commDlg.micStream = null;
        commDlg.micTrack = null;
      }
    };//commDlg.stopMicSharing

    commDlg.addTrackToLocalStream = function(trackToAdd)
    {
      try
      {
        if(commDlg.localStream.getTracks().length == 0)
          commDlg.localStream.addTrack(trackToAdd);
        else if(commDlg.localStream.getTracks().find((trackInfo) => trackInfo.id === trackToAdd.id) == null)
          commDlg.localStream.addTrack(trackToAdd);
      }
      catch{}
    };

    commDlg.startScreenSharing = async function ()
    {
      if(commDlg.scrUsable == 0) return;

      let mediaOptions =  window.constraints = {audio: false, video: true};
      try
      {
        commDlg.screenStream = await navigator.mediaDevices.getDisplayMedia(mediaOptions);
        commDlg.screenStream.getVideoTracks()[0].addEventListener("ended", () => commDlg.stopScreenSharing());

        commDlg.screenTrack = commDlg.screenStream.getVideoTracks()[0];

        if(commDlg.screenTrack)
        {
          commDlg.scrUsable = 1;
          commDlg.switchToScreen();
        }
      }
      catch (error)
      {
        commDlg.scrUsable = 0;
        commDlg.screenTrack = null;
        let switchButton = document.getElementById('commDlg_VideoScrnSwitch');
        switchButton.checked = false;
        Poi3dHelpers.canBeUsed(switchButton,false);

        setStatusText('Error initiating screen sharing: ' + error.name, "fadeOut");
      }
    };//commDlg.startScreenSharing

    commDlg.stopScreenSharing = function()
    {
      commDlg.switchOffScreen(null);

      if(commDlg.screenStream)
      {
        let tracks = commDlg.screenStream.getTracks();
        tracks.forEach((track) =>
        {
          track.stop();
          commDlg.screenStream.removeTrack(track);
        });
        commDlg.screenStream = null;
        commDlg.screenTrack = null;
      }
    };//commDlg.stopScreenSharing

    commDlg.handleCall = function()
    {
      let userSelection = document.getElementById("commDlg_VideoCallToSel");
      let callCheckbox = document.getElementById("commDlg_VideoCallSwitch");

      let img = document.getElementById('commDlgVideoChatCallImage');
      if(callCheckbox.checked)
      {
        if(commDlg.users.length == 0)
        {
          Poi3dHelpers.canBeUsed(callCheckbox,false);
          callCheckbox.checked = false;
          return;
        }

        let selectedUser = userSelection.options[userSelection.selectedIndex].userInfo;
        poi3dConnector.checkLoginState([selectedUser]);
        if(selectedUser.loggedIn != 1)
        {
          showMsgDlg(commDlg,poi3dConnector.getMessage(64));//"The user is not reachable"
          callCheckbox.checked = false;
          return;
        }

        img.style.animation = 'buttonShake 0.5s';
        img.style.animationIterationCount = 'infinite';
        commDlg.ringTone.play();

        if(commDlg.micTrack)
        {
          commDlg.addTrackToLocalStream(commDlg.micTrack);
          commDlg.addTrackToLocalStream(commDlg.intVideoStream.getVideoTracks()[0]);

          poi3dConnector.callUser(selectedUser,commDlg.localStream,commDlg.remoteStream);
        }
        else if(commDlg.micUsable != 0)
          commDlg.startMicSharing("handleCall",selectedUser);
      }
      else
      {
        img.style.animation = '';
        img.style.animationIterationCount = '';
        commDlg.ringTone.pause();
        commDlg.ringTone.currentTime = 0;
        poi3dConnector.endUserCall();
        commDlg.videoConnected = false;
        commDlg.stopExtVideo();
      }
    };//commDlg.callUser

    commDlg.acceptCall = function()
    {
      //switch to video section
      if(commDlg.activeSection != "commDlg_VideoSection")
      {
        Poi3dHelpers.setDisplayStyle("commDlg_ChatSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_VideoSection","block");
        Poi3dHelpers.setDisplayStyle("commDlg_EmailSection","none");
        Poi3dHelpers.setDisplayStyle("commDlg_NotfSection","none");
        document.getElementById("commDlg_VideoTabVal").checked = true;

        poi3dConnector.stopChatUpdate(commDlg.contextObject);
        commDlg.updateIntVideoStream(commDlg.bgVideoTrack);
        commDlg.activeSection = "commDlg_VideoSection";
      }

      let callSwitch = document.getElementById("commDlg_VideoCallSwitch");
      Poi3dHelpers.canBeUsed(callSwitch,true);

      if(commDlg.micTrack)
      {
        commDlg.addTrackToLocalStream(commDlg.micTrack);
        commDlg.addTrackToLocalStream(commDlg.intVideoStream.getVideoTracks()[0]);

        poi3dConnector.acceptUserCall(commDlg.localStream,commDlg.remoteStream);
      }
      else if(!commDlg.micError)
        commDlg.startMicSharing("acceptCall");

      document.getElementById("commDlg_VideoCallSwitch").checked = true;
    };//commDlg.acceptCall

    commDlg.stopVideo = function()
    {
      if(commDlg.videoConnected == true)
        return;

      commDlg.stopCameraSharing();
      commDlg.stopScreenSharing();
      commDlg.stopMicSharing();
      commDlg.stopExtVideo();
      document.getElementById("commDlg_BgVideo").pause();

      commDlg.ringTone.pause();
      commDlg.ringTone.currentTime = 0;
      document.getElementById('commDlg_VideoCallSwitch').checked = false;

    };//commDlg.stopVideo

    commDlg.stopExtVideo = function()
    {
      let extVideoElement = document.getElementById('commDlg_ExtVideoContent');

      if(commDlg.videoConnected == true)
        return;

      if(commDlg.remoteStream != null)
      {
        extVideoElement.pause();
        let tracks = commDlg.remoteStream.getTracks();
        tracks.forEach((track) =>
        {
          track.stop();
          commDlg.remoteStream.removeTrack(track);
        });

        extVideoElement.srcObject = null;
        commDlg.remoteStream = new MediaStream();
        commDlg.videoConnected = false;
        document.getElementById('commDlg_VideoCallSwitch').checked = false;
      }
    };//commDlg.stopExtVideo

    commDlg.disableVideoSection = function()
    {
      Poi3dHelpers.setDisplayStyle("commDlg_vidChatTabLab","none");
      Poi3dHelpers.setDisplayStyle("commDlg_VideoTabVal","none");
      Poi3dHelpers.setDisplayStyle("commDlg_VideoSection","none");
      commDlg.canDoVideoChat = false;
    }

    commDlg.initVideoChat = function()
    {
      try
      {
        const video = document.getElementById("commDlg_BgVideo");
        video.play();
        const stream = video.captureStream();
        commDlg.bgVideoTrack = stream.getVideoTracks()[0];
      }
      catch
      {
        commDlg.disableVideoSection();
      }
    }

    //--------------  Email -----------------------------------------------------------------------------

    commDlg.updateEmailSection = function()
    {
      let emailToValueText = "";
      let displayText = document.getElementById("commDlg_EmailToVal");
      for(let i=0; i<commDlg.selectedUsers.length; i++)
      {
        emailToValueText = emailToValueText + commDlg.selectedUsers[i].aliasName +",";
      }
      if(emailToValueText.length > 25) emailToValueText = emailToValueText.getText().substr(0,22) + "...";
      displayText.innerHTML=emailToValueText;
    };//commDlg.updateEmailSection

    commDlg.sendEmailEntry = function()
    {
      if(commDlg.selectedUsers.length >0)
      {
        let msgText = document.getElementById("commDlg_EmailTxt").value.replace(/(?:\r\n|\r|\n)/g, '<br>');
        poi3dConnector.sendMessageToUsers(commDlg.selectedUsers,msgText);
      }
    };//commDlg.sendEmailEntry

    //--------------  Notifications ----------------------------------------------------------------------
    commDlg.pushEntries = document.getElementById("commDlg_NotfContent");
    commDlg.pushContentArea = document.getElementById("notificationContentArea");
    commDlg.pushSwitch = document.getElementById("commDlg_NotfSwitch");

    commDlg.updateNotificationSection = function()
    {
      var rowCount = commDlg.pushEntries.rows.length;
      for ( let i = 0; i<rowCount; i++)
      {
        commDlg.pushEntries.deleteRow(-1);
      };

      var entries = poi3dConnector.getNotificationEntries();
      if(entries != null)
      {
        let aliasName = poi3dConnector.getPoi3dUser().getAliasName();
        let replyText = "";
        let replyToId = "";
        let replyToEntry = null;

        for ( let i = 0; i<entries.length; i++)
        {
          row = commDlg.pushEntries.insertRow(-1);
          cell = row.insertCell(0);

          replyToId = entries[i].getRepToId();

          if(entries[i].getUserAliasName() == aliasName)
            replyText = "<span class=\"chatInfo\">"+entries[i].getDateString()+":</span></br>";
          else
            replyText = "<span class=\"chatInfo\">"+entries[i].getUserAliasName()+" "+entries[i].getDateString()+":</span></br>";

          cell.innerHTML = replyText + "<span>"+entries[i].getText()+"</span>";

          if(entries[i].getUserAliasName() == aliasName)
            cell.className = "ownChatEntry";
          else
            cell.className = "extChatEntry";
        };
        commDlg.pushContentArea.scrollTop = commDlg.pushContentArea.scrollHeight;
      }//if(entries != null)
    };//commDlg.updateNotificationSection

    commDlg.notificationUpdated = function(actionInfo)
    {
      commDlg.updateNotificationSection();
    };

    commDlg.showNotificationState = function()
    {
      let pushState = poi3dConnector.getPushState();
      switch(pushState)
      {
        case "disabled":
        case "notUsable":
        case "unsubscribed":
          Poi3dHelpers.canBeUsed("commDlg_NotificTestTtl",false);
          commDlg.pushSwitch.checked = false;
          commDlg.disableVideoSection();
          break;
        case "subscribed":
        case "enabled":
          commDlg.pushSwitch.checked = true;
          break;
      }
      document.getElementById("commDlg_PushStateVal").innerHTML = pushState;
    };

    commDlg.switchNotification = function(switchButton)
    {
      if(switchButton.checked)
      {
        poi3dConnector.enablePushService();
      }
      else
      {
        poi3dConnector.disablePushService();
      }
    };

    commDlg.clearNotificationList = function()
    {
      poi3dConnector.clearNotifications();
      var rowCount = commDlg.pushEntries.rows.length;
      for ( let i = 0; i<rowCount; i++)
      {
        commDlg.pushEntries.deleteRow(-1);
      };
    };

    commDlg.sendTestNotification = function()
    {
      poi3dConnector.pushNotificationToDocUsers("testMessage", "", "Push notification from Server");
    };
    commDlg.initVideoChat();

    //register callbacks
    poi3dConnector.registerCallback("updateChat",commDlg.chatUpdated);
    poi3dConnector.registerCallback("updateNotification",commDlg.notificationUpdated);
    poi3dConnector.registerCallback("updateVideoCall",commDlg.videoCallUpdated);

    commDlg.showNotificationState();

    //check for chat rights
    let attRights = poi3dConnector.getCurrentAttachmentRights();
    if(attRights[0].length == 0)
    {
      commDlg.disableChatSection();
      commDlg.onTabSelectionChange("commDlg_EmailSection");
    }
    else
      commDlg.onTabSelectionChange('commDlg_ChatSection');

  };//if(!commDlg)

  commDlg.initSelections();
  commDlg.showDialog(parentDlg);
  if(commDlg.activeSection == "commDlg_ChatSection")
  {
    poi3dConnector.startChatUpdate(commDlg.contextObject);
  }

  function commDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "close":
        poi3dConnector.stopChatUpdate(commDlg.contextObject);
        commDlg.stopVideo();
        break;
      default:
        commDlg.dialog.style.display = 'block';
        break;
    };
  };
};//function showCommDlg

function showPtlSettDlg(parentDlg)
{
  if (!ptlSetDlg)
  {
    ptlSetDlg = new DialogBox('ptlSetDlg', ptlSetDlgCbk, cmiCanvas);
    ptlSetDlg.canSendTestmail = false;
    ptlSetDlg.activeSection = "";
    ptlSetDlg.portalSettings = poi3dConnector.getPortalConfiguration();
    document.getElementById("ptlSetDlg_AiBotProvVal").selectedIndex = -1;

    ptlSetDlg.onTabSelectionChange  = function(sectionToActivate)
    {
      ptlSetDlg.activeSection = sectionToActivate;

      if(sectionToActivate == "ptlSetDlg_MailSectionion")
      {
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_MailSection","block");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CfgSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CtlgSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_AiSection","none");
      }
      else if(sectionToActivate == "ptlSetDlg_CfgSection")
      {
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_MailSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CfgSection","block");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CtlgSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_AiSection","none");
      }
      else if(sectionToActivate == "ptlSetDlg_CtlgSection")
      {
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_MailSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CfgSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CtlgSection","block");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_AiSection","none");
      }
      else if(sectionToActivate == "ptlSetDlg_AiSection")
      {
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_MailSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CfgSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_CtlgSection","none");
        Poi3dHelpers.setDisplayStyle("ptlSetDlg_AiSection","block");
      }
    };//ptlSetDlg.onTabSelectionChange

    ptlSetDlg.updateUi = function()
    {
      let set = ptlSetDlg.portalSettings;
      let mailButton = document.getElementById("ptlSetDlg_MailTestButt");
      document.getElementById("ptlSetDlg_StateVal").innerHTML = "";

      document.getElementById("ptlSetDlg_EncCommVal").checked = set.encComm;
      if(set.encAtt > 0)
        document.getElementById("ptlSetDlg_EncAttVal").checked = true;
      else
        document.getElementById("ptlSetDlg_EncAttVal").checked = false;

      document.getElementById("ptlSetDlg_MailHostVal").value = set.mlHost;
      document.getElementById("ptlSetDlg_MailUserVal").value = set.mlUser;
      document.getElementById("ptlSetDlg_MailPwdVal").value = set.mlPwd;
      document.getElementById("ptlSetDlg_MailPortVal").value = set.mlPort;
      document.getElementById("ptlSetDlg_MailFromVal").value = set.mlFrom;
      document.getElementById("ptlSetDlg_MailFromTtlVal").value = set.mlFromTtl;
      document.getElementById("ptlSetDlg_BccAttVal").checked = set.mlBcc;
      document.getElementById("ptlSetDlg_BgTxtVal").value = set.bgTxt;
      document.getElementById("ptlSetDlg_HelpDirVal").value = set.helpDir;
      document.getElementById("ptlSetDlg_DemoDocDirVal").value = set.demoDocDir;
      document.getElementById("ptlSetDlg_DwldDirVal").value = set.downloadDir;
      document.getElementById("ptlSetDlg_NrOfUsersVal").innerHTML = poi3dConnector.getAllUsersCount();
      document.getElementById("ptlSetDlg_MaxUsersVal").innerHTML = poi3dConnector.getMaxUsers();
      document.getElementById("ptlSetDlg_LicEndVal").value = poi3dConnector.getLicenseEndDate();

      if(set.usrRights[0]=="1")
        document.getElementById("ptlSetDlg_CmpUseVal").checked = true;
      else
        document.getElementById("ptlSetDlg_CmpUseVal").checked = false;

      if(set.mlUser.length > 0)
      {
        ptlSetDlg.canSendTestmail = true;
        Poi3dHelpers.canBeUsed(mailButton,true);
      }
      else
      {
        Poi3dHelpers.canBeUsed(mailButton,false);
      }

      let extCatalogs = poi3dConnector.getExternalCatalogCfg();
      let ptlSetDlg_CtlgSel = document.getElementById("ptlSetDlg_CtlgSel");
      let optionEntry;
      ptlSetDlg_CtlgSel.options.length = 0;
      document.getElementById("ptlSetDlg_CtlgUrlVal").value = "";
      document.getElementById("ptlSetDlg_CtlgTitleVal").value = "";

      for (let i =0; i<extCatalogs.length; i++)
      {
        optionEntry = document.createElement("option");
        optionEntry.text = extCatalogs[i].ctlgUrl;
        optionEntry.ctlgCfg = extCatalogs[i];
        ptlSetDlg_CtlgSel.add(optionEntry);
      }

      let aiBots = poi3dConnector.getAiBotCfg();
      let ptlSetDlg_AiBotSel = document.getElementById("ptlSetDlg_AiBotSel");

      ptlSetDlg_AiBotSel.options.length = 0;
      document.getElementById("ptlSetDlg_AiBotNmVal").value = "";
      document.getElementById("ptlSetDlg_AiBotDescVal").value = "";
      document.getElementById("ptlSetDlg_AiBotProvVal").value = "OpenRouter";
      document.getElementById("ptlSetDlg_AiBotEndPntVal").value = "";
      document.getElementById("ptlSetDlg_AiBotKeyVal").value = "";
      document.getElementById("ptlSetDlg_AiBotLlmVal").value = "";

      for (let i =0; i<aiBots.length; i++)
      {
        optionEntry = document.createElement("option");
        optionEntry.text = aiBots[i].getBotName();
        optionEntry.aiBot = aiBots[i];
        ptlSetDlg_AiBotSel.add(optionEntry);
      }
      document.getElementById("ptlSetDlg_AiBotProvVal").selectedIndex = -1;

    };//ptlSetDlg.updateUi

    ptlSetDlg.onStatusUpdate = function(textToDisplay,currentStatus)
    {
      switch(currentStatus)
      {
        case "savePortalConfigurationSuccess":
          ptlSetDlg.updateUi();
          break;
      }
      document.getElementById("ptlSetDlg_StateVal").innerHTML = textToDisplay;
    };//ptlSetDlg.onStatusUpdate

    ptlSetDlg.sendTestMail = function()
    {
      poi3dConnector.sendMessageToUsers([poi3dConnector.getUserProperties()],"Testmail");
    };//ptlSetDlg.sendTestMail

    ptlSetDlg.setFeatures = function()
    {
      showFeatDlg(ptlSetDlg,"portalSettings");
    };//ptlSetDlg.setFeatures

    ptlSetDlg.addCatalog = function()
    {
      let cltgUrl = document.getElementById("ptlSetDlg_CtlgUrlVal").value;
      let cltgTitle = document.getElementById("ptlSetDlg_CtlgTitleVal").value;
      let extCatalogs = poi3dConnector.getExternalCatalogCfg();

      ptlSetDlg_StateVal.innerHTML = "";
      if(extCatalogs.find((item) => item.ctlgUrl === cltgUrl) != null)
      {
        ptlSetDlg_StateVal.innerHTML = "Catalog already exists";
        return;
      }

      let resultObj = new Object();
      resultObj.urlExists = false;

      Poi3dHelpers.checkIfUrlExists(cltgUrl + "/catalog.json",resultObj);
      if(resultObj.urlExists == true)
      {
        let cltgEntry = new Object();
        cltgEntry["ctlgTtl"] = cltgTitle;
        cltgEntry["ctlgUrl"] = cltgUrl;
        extCatalogs.push(cltgEntry);
        ptlSetDlg.updateUi();
      }
      else
      {
        showMsgDlg(ptlSetDlg,poi3dConnector.getStatusText(10));//"error loading document"
      }
    };//ptlSetDlg.addCatalog

    ptlSetDlg.updateCatalog = function()
    {
      let ptlSetDlg_CtlgSel = document.getElementById("ptlSetDlg_CtlgSel");
      if(ptlSetDlg_CtlgSel.selectedIndex == -1) return;

      let catalogCfg = ptlSetDlg_CtlgSel.options[ptlSetDlg_CtlgSel.selectedIndex].ctlgCfg;
      let cltgUrl = document.getElementById("ptlSetDlg_CtlgUrlVal").value;
      let cltgTitle = document.getElementById("ptlSetDlg_CtlgTitleVal").value;

      let oldUrl = catalogCfg["ctlgUrl"];
      catalogCfg["ctlgUrl"] = cltgUrl;
      catalogCfg["ctlgTtl"] = cltgTitle;

      if(oldUrl != cltgUrl)
        ptlSetDlg.updateUi();

    };//ptlSetDlg.updateCatalog

    ptlSetDlg.removeCatalog = function()
    {
      let ptlSetDlg_CtlgSel = document.getElementById("ptlSetDlg_CtlgSel");
      if(ptlSetDlg_CtlgSel.selectedIndex == -1) return;

      let extCatalogs = poi3dConnector.getExternalCatalogCfg();
      let selCtlgUrl = ptlSetDlg_CtlgSel.options[ptlSetDlg_CtlgSel.selectedIndex].text;
      poi3dConnector.setExternalCatalogCfg(extCatalogs.filter(function(item) {return item.ctlgUrl !== selCtlgUrl}));
      ptlSetDlg.updateUi();
    };//ptlSetDlg.removeCatalog

    ptlSetDlg.onCltgSelect = function (selectObject)
    {
      if(selectObject.selectedIndex == -1) return;

      let extCatalogs = poi3dConnector.getExternalCatalogCfg();
      let selCtlgCfg = selectObject.options[selectObject.selectedIndex].ctlgCfg;

      document.getElementById("ptlSetDlg_CtlgUrlVal").value = selCtlgCfg.ctlgUrl;
      document.getElementById("ptlSetDlg_CtlgTitleVal").value = selCtlgCfg.ctlgTtl;
    }//ptlSetDlg.onCltgSelect

    ptlSetDlg.addAiBot = function()
    {
      let aiBotName = "NewBot_" + Math.random().toString(36).slice(2, 5);
      let aiBotDesc = document.getElementById("ptlSetDlg_AiBotDescVal").value;
      let aiBotProv = document.getElementById("ptlSetDlg_AiBotProvVal").value;
      let aiBotEndPnt = document.getElementById("ptlSetDlg_AiBotEndPntVal").value;
      let aiBotKey = document.getElementById("ptlSetDlg_AiBotKeyVal").value;
      let aiBotllm = document.getElementById("ptlSetDlg_AiBotLlmVal").value;

      let aiBots = poi3dConnector.getAiBotCfg();

      ptlSetDlg_StateVal.innerHTML = "";
      if(aiBots.find((item) => item.getBotName() === aiBotName) != null)
      {
        ptlSetDlg_StateVal.innerHTML = "AI bot already exists";
        return;
      }

      let knownUsers = poi3dConnector.getUsers();
      if(knownUsers.find((item) => item.aliasName === aiBotName) != null)
      {
        ptlSetDlg_StateVal.innerHTML = "User with the same name already exists";
        return;
      }

      let newAiBot = new Poi3dAiConnector(poi3dConnector.getPoi3dUser());
      newAiBot.setBotName(aiBotName);
      newAiBot.setDescription(aiBotDesc);
      newAiBot.setProvider(aiBotProv);
      newAiBot.setEndPoint(aiBotEndPnt);
      newAiBot.setAccessKey(aiBotKey);
      newAiBot.setLlmName(aiBotllm);
      aiBots.push(newAiBot);

      ptlSetDlg.updateUi();

    };//ptlSetDlg.addCatalog

    ptlSetDlg.updateAiBot = function()
    {
      let ptlSetDlg_AiBotSel = document.getElementById("ptlSetDlg_AiBotSel");
      if(ptlSetDlg_AiBotSel.selectedIndex == -1) return;

      let aiBot = ptlSetDlg_AiBotSel.options[ptlSetDlg_AiBotSel.selectedIndex].aiBot;
      let aiBotName = document.getElementById("ptlSetDlg_AiBotNmVal").value;
      let aiBotDesc = document.getElementById("ptlSetDlg_AiBotDescVal").value;
      let aiBotProv = document.getElementById("ptlSetDlg_AiBotProvVal").value;
      let aiBotEndPnt = document.getElementById("ptlSetDlg_AiBotEndPntVal").value;
      let aiBotKey = document.getElementById("ptlSetDlg_AiBotKeyVal").value;
      let aiBotllm = document.getElementById("ptlSetDlg_AiBotLlmVal").value;

      let aiBots = poi3dConnector.getAiBotCfg();

      ptlSetDlg_StateVal.innerHTML = "";
      let foundAiBot = aiBots.find((item) => item.getBotName() === aiBotName);
      if((foundAiBot != null)&&(foundAiBot != aiBot))
      {
        ptlSetDlg_StateVal.innerHTML = "AI bot already exists";
        document.getElementById("ptlSetDlg_AiBotNmVal").value = "NewBot_" + Math.random().toString(36).slice(2, 5);
        return;
      }

      let knownUsers = poi3dConnector.getUsers();
      if(knownUsers.find((item) => item.aliasName === aiBotName) != null)
      {
        ptlSetDlg_StateVal.innerHTML = "User with the same name already exists";
        document.getElementById("ptlSetDlg_AiBotNmVal").value = "NewBot_" + Math.random().toString(36).slice(2, 5);
        return;
      }
      let oldName = aiBot.getBotName();
      aiBot.setBotName(aiBotName);
      aiBot.setDescription(aiBotDesc);
      aiBot.setProvider(aiBotProv);
      aiBot.setEndPoint(aiBotEndPnt);
      aiBot.setAccessKey(aiBotKey);
      aiBot.setLlmName(aiBotllm);

      if(oldName != aiBotName)
        ptlSetDlg.updateUi();

    };//ptlSetDlg.updateAiBot

    ptlSetDlg.removeAiBot = function()
    {
      let ptlSetDlg_AiBotSel = document.getElementById("ptlSetDlg_AiBotSel");
      if(ptlSetDlg_AiBotSel.selectedIndex == -1) return;

      let aiBots = poi3dConnector.getAiBotCfg();
      let aiBotName = ptlSetDlg_AiBotSel.options[ptlSetDlg_AiBotSel.selectedIndex].text;
      poi3dConnector.setAiBotCfg(aiBots.filter(function(item) {return item.getBotName() !== aiBotName}));

      ptlSetDlg.updateUi();
    };//ptlSetDlg.removeCatalog

    ptlSetDlg.onAiProviderSelect = function (selectObject)
    {
      if(selectObject.selectedIndex == -1) return;
      switch(selectObject.value)
      {
        case "OpenRouter":
          document.getElementById("ptlSetDlg_AiBotEndPntVal").value = "https://openrouter.ai/api/v1/chat/completions";
          break;
        case "OpenAi":
          document.getElementById("ptlSetDlg_AiBotEndPntVal").value = "https://api.openai.com/v1/chat/completions";
          break;
        case "Generic":
          document.getElementById("ptlSetDlg_AiBotEndPntVal").value = "";
          break;
      }
    };

    ptlSetDlg.onAiBotSelect = function (selectObject)
    {
      if(selectObject.selectedIndex == -1) return;

      let aiBots = poi3dConnector.getAiBotCfg();
      let selAiBot= selectObject.options[selectObject.selectedIndex].aiBot;

      document.getElementById("ptlSetDlg_AiBotNmVal").value = selAiBot.getBotName();
      document.getElementById("ptlSetDlg_AiBotDescVal").value = selAiBot.getDescription();
      document.getElementById("ptlSetDlg_AiBotProvVal").value = selAiBot.getProvider();
      document.getElementById("ptlSetDlg_AiBotEndPntVal").value = selAiBot.getEndPoint();
      document.getElementById("ptlSetDlg_AiBotKeyVal").value = selAiBot.getAccessKey();
      document.getElementById("ptlSetDlg_AiBotLlmVal").value = selAiBot.getLlmName();
    }//ptlSetDlg.onCltgSelect

    poi3dConnector.registerCallback("portalSettingsDlgStatusUpdate",ptlSetDlg.onStatusUpdate);

  }//if (!ptlSetDlg)

  ptlSetDlg.updateUi();
  ptlSetDlg.showDialog(parentDlg);

  function ptlSetDlgCbk(btnName)
  {
    switch(btnName)
    {
      case "save":
        ptlSetDlg.dialog.style.display = 'block';

        let set = ptlSetDlg.portalSettings;

        set.encComm = document.getElementById("ptlSetDlg_EncCommVal").checked;
        if(document.getElementById("ptlSetDlg_EncAttVal").checked == true)
          set.encAtt = 1;
        else
          set.encAtt = 0;

        set.mlHost = document.getElementById("ptlSetDlg_MailHostVal").value;
        set.mlUser = document.getElementById("ptlSetDlg_MailUserVal").value;
        set.mlPwd = document.getElementById("ptlSetDlg_MailPwdVal").value;
        set.mlPort = document.getElementById("ptlSetDlg_MailPortVal").value;
        set.mlFrom = document.getElementById("ptlSetDlg_MailFromVal").value;
        set.mlFromTtl = document.getElementById("ptlSetDlg_MailFromTtlVal").value;
        set.mlBcc = document.getElementById("ptlSetDlg_BccAttVal").checked;
        set.bgTxt = document.getElementById("ptlSetDlg_BgTxtVal").value;
        set.helpDir = document.getElementById("ptlSetDlg_HelpDirVal").value;
        set.demoDocDir = document.getElementById("ptlSetDlg_DemoDocDirVal").value;
        set.downloadDir = document.getElementById("ptlSetDlg_DwldDirVal").value;

        if(document.getElementById("ptlSetDlg_CmpUseVal").checked == true)
          set.usrRights[0] = "1";
        else
          set.usrRights[0] = "0";

        poi3dConnector.setPortalConfiguration(set);
        break;
      case "close":
      case "cancel":
        break;
      default:
        ptlSetDlg.dialog.style.display = 'block';
        break;
    }
  }
}//function showPtlSettDlg()
