<%@ language = "JavaScript" %>
<% /*
    $Revision$
    $Id$

    File:               ins_deel.asp
    Description:        Details of an object (Mobile version) and access to actions on that object
                        If not authorised for this object we can forward to a "melding" on this object if stdmkina
    Parameters:         ins_key (bv via QRC)
                        stdmkina    stdmeldingkey IF NOT AUTHORIZED,
                                   -1/not defined = do not initiate a call if unauthorized
                                    0             = initiate a unspecific (determined by configuration) call if unauthorized and authorized for MLDUSE
                                   >0             = idem for that stdmeldingkey (rare)


*/
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/discx3d.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="./mobile.inc" -->
<!-- #include file="./iface.inc" -->
<!-- #include file="./resultset_table.inc" -->
<!-- #include file="../mld/mld.inc" -->
<!-- #include file="../ins/ins.inc" -->
<!-- #include file="../ins/ins_flexkenmerk.inc" -->
<%
FCLTHeader.Requires({ plugins:["jQuery", "suggest"],
                      js: ["jquery-ui.js"]
                    });

var urole= getQParamSafe("urole", "bo");
var fronto = (urole == "fo");
var ins_score_enabled = S("ins_score_enabled") == 1;
var ins_key = getQParamInt("ins_key", -1);
var alg_key = getQParamInt("alg_key", -1);
var alg_typ = getQParamSafe("alg_typ", "");
var disc_key = getQParamInt("disc", -1);
var srtgrp_key = getQParamInt("srtgrp", -1);
var srtobj_key = getQParamInt("srtobj", -1);
var qrc = getQParamInt("qrc", 0) != 0;
var stdmkina = getQParamInt("stdmkina", -1);  //STDMeldingKeyIfNotAuthorized
var return_from = getQParam("return_from", "");
var isNew = false;
var parent_key = -1;


/* Welke acties willen we tonen als we via qrc binnenkomen? (default allemaal) */
var btns = {};

/* Bestaand object */
btns["ins_obj_lend_out"]    = !qrc || getQParamInt("ins_obj_lend_out", 0) == 1; /* Uitlenen */
btns["ins_obj_receive"]     = !qrc || getQParamInt("ins_obj_receive", 0) == 1;  /* Innemen */
btns["ins_reserve"]         = !qrc || getQParamInt("ins_reserve", 0) == 1;      /* Reserveer object */
btns["ins_claim_res"]       = !qrc || getQParamInt("ins_claim_res", 0) == 1;    /* Bevestig reservering */
btns["ins_inspect"]         = !qrc || getQParamInt("ins_inspect", 0) == 1;      /* Taken */
btns["ins_sub_objects"]     = !qrc || getQParamInt("ins_sub_objects", 0) == 1;  /* Onderdelen */
btns["ins_koppel"]          = !qrc || getQParamInt("ins_koppel", 0) == 1;       /* Gerelateerde objecten */
btns["ins_move"]            = !qrc || getQParamInt("ins_move", 0) == 1;         /* Verplaats object */
btns["ins_same_as_parent"]  = !qrc || getQParamInt("ins_move", 0) == 1;         /* Verplaats object naar dezelfde plek als de parent */
btns["ins_history"]         = !qrc || getQParamInt("ins_history", 0) == 1;      /* Object historie */
btns["ins_add_mld"]         = !qrc || getQParamInt("ins_add_mld", 0) == 1;      /* Maak melding */
btns["ins_show_mld"]        = !qrc || getQParamInt("ins_show_mld", 0) == 1;     /* Zie meldingen op dit object */
btns["ins_notes"]           = !qrc || getQParamInt("ins_notes", 0) == 1;        /* Object notities */
// var ins_cancel          = 0;                                        /* Annuleren [Nooit, denk ik] */

/* Nieuw object */
btns["ins_save"]            = !qrc || getQParamInt("ins_save", 0) == 1;         /* Opslaan */

/* Indien niets gedefinieerd -> dan alle knoppen laten zien */
var all_buttons = 1;
for (btn in btns)
    all_buttons &= !btns[btn]; // xOr
for (btn in btns)
    btns[btn] |= all_buttons;

function getBindLevel(ruimte_type, ruimte_key)
{
    var plaats_niveau = "";
    if (ruimte_type == "L")
    {
        plaats_niveau = "RL";
    }
    else if (ruimte_type == "R")
    {
        var sql = "SELECT alg_plaatsaanduiding"
                + "     , alg_plaatsomschrijving"
                + "     , alg_type"
                + "  FROM alg_v_allonrgoed_gegevens"
                + " WHERE alg_onroerendgoed_keys = " + ruimte_key;
        var oRs = Oracle.Execute(sql);
        plaats_niveau = "R" + oRs("alg_type").Value;
        oRs.Close();
    }
    else
        plaats_niveau = ruimte_type;  // lijkt mij toch

    return plaats_niveau;
}

function getBindString(bind, bind_key, parent_key)
{   // Geef de omschrijving van de afdeling/ruimte/persoon/terreinsector/werkplek
    var sql;
    var binding_item = L("lcl_unknown");
    switch (bind)
    {
        case 'A':
        {
            sql = "SELECT " + S("prs_dep_string")
                + "  FROM prs_v_afdeling d"
                + " WHERE d.prs_afdeling_key = " + bind_key;
            break;
        }

        case 'P':
        {
            sql = "SELECT prs_perslid_naam_full"
                + "  FROM prs_v_perslid_fullnames_all pf"
                + " WHERE pf.prs_perslid_key = " + bind_key;
            break;
        }

        case 'C':
        {
            sql = "SELECT cp.prs_contactpersoon_naam"
                + "  FROM prs_contactpersoon cp"
                + " WHERE cp.prs_contactpersoon_key = " + bind_key;
            break;
        }

        case 'R':
        {
            sql = "SELECT o.alg_plaatsaanduiding || DECODE(o.alg_plaatsomschrijving, '','' ,' (' || o.alg_plaatsomschrijving || ')')"
                + "  FROM ins_v_alg_overzicht o "
                + " WHERE o.alg_onroerendgoed_type = 'R'"
                + "   AND o.alg_ruimte_key = " + bind_key;
            break;
        }

        case 'W':
        {
            sql = "SELECT pa.alg_plaatsaanduiding || DECODE(a.alg_ruimte_omschrijving,NULL,'',' (' || a.alg_ruimte_omschrijving || ')')"
                + "  FROM alg_ruimte a"
                + "     , ins_v_alg_overzicht pa"
                + " WHERE a.alg_ruimte_key = pa.alg_ruimte_key"
                + "   AND pa.prs_werkplek_key = " + bind_key;
            break;
        }

        case 'T':
        {
            sql = "SELECT pa.alg_plaatsaanduiding || DECODE(t.alg_terreinsector_naam,NULL,'',' (' || t.alg_terreinsector_naam || ')')"
                + "  FROM alg_terreinsector t"
                + "     , ins_v_alg_overzicht pa"
                + " WHERE t.alg_terreinsector_key = pa.alg_terreinsector_key"
                + "   AND t.alg_terreinsector_key = " + bind_key;
          break;
        }

        case 'I':
        {
            sql = "SELECT ins_deel_omschrijving"
                + "  FROM ins_v_deelenonderdeel d"
                + " WHERE d.ins_deel_key = " + parent_key;
          break;
        }

        default: INTERNAL_ERROR_UNKNOWN_BIND;
    }
    var oRs = Oracle.Execute(sql);
    if (!oRs.eof)
        binding_item = oRs(0).Value;
    oRs.Close();
    return binding_item;
}

function getBindlabel(plaats_niveau)
{
    var binding_text = 'unknown';
    switch (plaats_niveau)
    {
        case "RL": binding_text = L("lcl_location");   break;
        case "RG": binding_text = L("lcl_building");   break;
        case "RV": binding_text = L("lcl_floor");      break;
        case "RR": binding_text = L("lcl_obj_bind_r"); break;
        case "T":  binding_text = L("lcl_obj_bind_t"); break;
        case "W":  binding_text = L("lcl_obj_bind_w"); break;
        case "P":  binding_text = L("lcl_obj_bind_p"); break;
        case "A":  binding_text = L("lcl_obj_bind_a"); break;
        case "C":  binding_text = L("lcl_obj_bind_c"); break;
    }
    return binding_text;
}

var transitParam = buildTransitParam(["qrc", "tiny", "self"]);
var ins_info = {};
var imagePath;

if (ins_key == -1)
{
    if (alg_key == -1 || disc_key == -1 || srtgrp_key == -1 || srtobj_key == -1)
    {
        if (disc_key > 0)
        {   // Als de user op de discipline geen write rechten heeft, dan mag de user geen object toevoegen.
            var autfunction = (urole == "fo"? "WEB_INSFOF" : "WEB_INSMAN");
            var authparams = user.checkAutorisation(autfunction, false, disc_key);
            var PRSALGwrite = authparams.PRSwritelevel < 9 && authparams.ALGwritelevel < 9;
            user.anything_todo_or_abort(PRSALGwrite);
        }
        Server.Transfer("ins_deel_new.asp");
    }
    isNew = true;
    var this_ins = { canChangeAlg: true };

    var sql = "SELECT ins.nextdescription(ins_srtdeel_code, " + (parent_key < 0 ? "NULL" : parent_key) + ")"
            + "  FROM ins_srtdeel"
            + " WHERE ins_srtdeel_key = " + srtobj_key;
    var oRs = Oracle.Execute( sql );
    ins_info.ins_deel_omschrijving = oRs(0).Value;
    oRs.Close();

    ins_info.ins_deel_aanmaak = new Date();
    ins_info.ins_deel_vervaldatum = null;
    ins_info.ins_srtdeel_key = srtobj_key;
    ins_info.ins_parent_key = parent_key;
    ins_info.perslid_key_beh = -1;
    ins_info.ins_deel_actief = true;
    ins_info.ruimte_key = alg_key;
    ins_info.plaats_afdeling = getBindString(alg_typ, alg_key, ins_info.ins_parent_key);
    ins_info.bindlevel = getBindLevel(alg_typ, alg_key);
}
else
{
    var sql = "SELECT 1 FROM ins_deel WHERE ins_deel_key = " + ins_key;
    var oRs = Oracle.Execute(sql);
    if (oRs.eof) // Voorkom foutmelding als gevolg van niet bestaande ins_key.
        user.auth_required_or_abort(false);
    oRs.Close();

    var this_ins = ins.func_enabled_deel(ins_key);

    if (stdmkina == -1)
    {
        // geen alternatief aangegeven, dus wegwezen zonder rechten
        user.auth_required_or_abort(this_ins.canReadAny);
    }
    else
    {
        // Als ik leesrechten heb dan gaan we (ook) gewoon door
        // en laten we de objectdetails zien (met onderin de mogelijkheid voor melding)
        // Als ik deze details niet mag zien, spring ik door naar het doen van een melding

        if (this_ins.canReadAny)
        {
            // I am authorized, just go on (disregard stdmkina)
            user.auth_required_or_abort(this_ins.canReadAny);
        }
        else
        {  // ik mag niets zien, doorstarten
            if (user.checkAutorisation( "WEB_MLDUSE", true)) {
                // Dan laat maar een melding doen
                var theURL = "./melding.asp?mld_key=-1&ins_key=" + ins_key + (stdmkina > 0 ? "&stdm_key="+stdmkina : "") + transitParam;
                Response.Redirect(theURL);
            }
            else {
                // ik wil wel een melding starten maar ik heb daar helemaal geen rechten voor,
                // dan alsnog evt. unauthorized
                user.auth_required_or_abort(false);
            }
        }
    }
    var isResDeel = false;
    var hasImage = false;
    ins_info.perslid_key_beh = -1;

    // Bepaal wat objectgegevens, specifiek ook de plaats (TODO: Terrein)
    var sql = " SELECT id.ins_deel_omschrijving"
            + "      , " + lcl.xsqla("sd.ins_srtdeel_omschrijving", "sd.ins_srtdeel_key")
            + "      , id.ins_deel_opmerking"
            + "      , id.ins_deel_key"
            + "      , id.ins_srtdeel_key"
            + "      , id.ins_deel_parent_key"
            + "      , id.ins_alg_ruimte_type"
            + "      , id.ins_alg_ruimte_key"
            + "      , id.ins_alg_ruimte_key_org"
            + "      , id.prs_perslid_key_beh"
            + "      , id.ins_deel_aanmaak"
            + "      , id.ins_deel_vervaldatum"
            + "      , id.ins_deel_verwijder"
            + "      , id.ins_deel_actief"
            + "      , id.ins_deel_mjb_score1"
            + "      , id.ins_deel_mjb_score2"
            + "      , id.ins_discipline_key"
            + "      , sd.ins_srtdeel_image"
            + "      , CASE WHEN sd.ins_srtdeel_sensortype != 0 AND sd.ins_srtdeel_statethreshold is not null"
            + "             THEN ins.state_diff (ins_deel_state, ins_srtdeel_statethreshold) END thresholdstate"
            + "      , id.ins_deel_state"
            + "      , id.ins_deel_statedate"
            + "   FROM ins_v_deelenonderdeel id"
            + "      , ins_srtdeel sd"
            + "  WHERE sd.ins_srtdeel_key = id.ins_srtdeel_key"
            + "    AND id.ins_deel_key = " + ins_key;
    var oRs = Oracle.Execute(sql);
    if (!oRs.eof)
    {
        ins_info.ins_alg_ruimte_key_org   = oRs("ins_alg_ruimte_key_org").Value;
        ins_info.ins_deel_aanmaak         = new Date(oRs("ins_deel_aanmaak").Value);
        ins_info.ins_deel_vervaldatum     = oRs("ins_deel_vervaldatum").Value;
        if (ins_info.ins_deel_vervaldatum !== null) {
            ins_info.ins_deel_vervaldatum = new Date(ins_info.ins_deel_vervaldatum);
        }
        ins_info.ins_deel_verwijderd      = oRs("ins_deel_verwijder").value != null;
        ins_info.ins_deel_omschrijving    = oRs("ins_deel_omschrijving").Value;
        ins_info.ins_srtdeel_omschrijving = oRs("ins_srtdeel_omschrijving").Value;
        ins_info.ins_deel_opmerking       = oRs("ins_deel_opmerking").Value;
        ins_info.ins_srtdeel_key          = oRs("ins_srtdeel_key").Value;;
        ins_info.ins_parent_key           = oRs("ins_deel_parent_key").Value || -1;
        ins_info.ins_deel_actief          = oRs("ins_deel_actief").Value == 1;
        ins_info.ruimte_type              = oRs("ins_alg_ruimte_type").Value;
        ins_info.ruimte_key               = oRs("ins_alg_ruimte_key").Value;
        ins_info.ins_deel_mjb_score1      = oRs("ins_deel_mjb_score1").Value;
        ins_info.ins_deel_mjb_score2      = oRs("ins_deel_mjb_score2").Value;
        ins_info.perslid_key_beh          = oRs("prs_perslid_key_beh").Value || -1;
        ins_info.srtdeel_image            = oRs("ins_srtdeel_image").Value;
        ins_info.thresholdstate           = oRs("thresholdstate").Value;
        ins_info.ins_deel_state           = oRs("ins_deel_state").Value;
        ins_info.ins_deel_statedate       = oRs("ins_deel_statedate").Value;
        ins_info.subject         = ins_info.ins_srtdeel_omschrijving+ " " +ins_info.ins_deel_omschrijving;
        ins_info.plaats_afdeling = getBindString(ins_info.ruimte_type, ins_info.ruimte_key, ins_info.ins_parent_key);
        ins_info.bindlevel       = getBindLevel(ins_info.ruimte_type, ins_info.ruimte_key);
        disc_key                          = oRs("ins_discipline_key").Value;  // tbv dialect

        var eLendOut = false;
        var eReceive = false;
        if (fronto)
        {
            eLendOut = ins_info.ins_alg_ruimte_key_org == null;
            eReceive = !eLendOut;
        }
        ins_info.eLendOut = (fronto ? ins_info.ins_alg_ruimte_key_org == null : false);
        ins_info.eReceive = (fronto ? !ins_info.eLendOut : false);

        // Haal nog wat gegevens over de parent op als het een onderdeel is.
        ins_info.parent = "";
        if (ins_info.ins_parent_key > -1)
        {
            var psql = "SELECT id.ins_deel_omschrijving"
                     + "     , " + lcl.xsqla('sd.ins_srtdeel_omschrijving', 'sd.ins_srtdeel_key')
                     + "     , ins_deel_parent_key"
                     + "     , ins_alg_ruimte_key"
                     + "     , ins_alg_ruimte_type"
                     + "  FROM ins_deel id"
                     + "     , ins_srtdeel sd"
                     + " WHERE id.ins_srtdeel_key = sd.ins_srtdeel_key"
                     + "   AND id.ins_deel_key = " + ins_info.ins_parent_key;
            var pRs = Oracle.Execute(psql);
            ins_info.parent = pRs("ins_srtdeel_omschrijving").Value + " "
                            + pRs("ins_deel_omschrijving").Value;
            ins_info.alg_ruimte_key_parent = pRs("ins_alg_ruimte_key").Value;
            ins_info.alg_ruimte_type_parent = pRs("ins_alg_ruimte_type").Value;
            pRs.Close();
        }
    }
    // Mag object verplaatst worden.
    var verplaatsbaar = (ins_info.ruimte_type == "R" || ins_info.ruimte_type == "T");
    this_ins.canMove = (verplaatsbaar && this_ins.canChangeAlg && (this_ins.canWrite("WEB_INSMAN") || this_ins.canWrite("WEB_INSUSE")) && !eLendOut);
    this_ins.canSameAsParent = ins_info.ins_parent_key > 0 && this_ins.canMove &&
                              (ins_info.alg_ruimte_key_parent != ins_info.ruimte_key || ins_info.alg_ruimte_type_parent != ins_info.ruimte_type); // Plaats/eigenaar moet aangepast zijn.
    oRs.Close();
}
ins_info.binding_text = getBindlabel(ins_info.bindlevel);

var sql = "SELECT g.ins_discipline_omschrijving"
        + "     , g.ins_srtgroep_omschrijving"
        + "     , g.ins_srtdeel_code_upper"
        + "     , g.ins_srtdeel_omschrijving"
        + "     , p. ins_disc_params_autonum"
        + "  FROM ins_v_srtdeel_gegevens g"
        + "     , ins_disc_params p"
        + " WHERE g.ins_discipline_key = p.ins_discipline_key"
        + "   AND g.ins_srtdeel_key = " + ins_info.ins_srtdeel_key;
var oRs = Oracle.Execute(sql);
ins_info.disc_omschr = oRs("ins_discipline_omschrijving").Value;
ins_info.grp_omschr  = oRs("ins_srtgroep_omschrijving").Value;
ins_info.srt_omschr  = oRs("ins_srtdeel_code_upper").Value + " " + oRs("ins_srtdeel_omschrijving").Value;
ins_info.autonum     = oRs("ins_disc_params_autonum").Value;
oRs.Close();

if (alg_typ == "R" || alg_typ == "W" || alg_typ == "T")
{
    var sql = "SELECT alg_locatie_key"
            + "  FROM ins_v_alg_overzicht"
            + " WHERE alg_onroerendgoed_type = " + safe.quoted_sql(alg_typ)
            + "   AND alg_onroerendgoed_keys = " + alg_key;
    oRs = Oracle.Execute(sql);
    ins_info.locatie_key = oRs("alg_locatie_key").Value;
    oRs.Close();
}

%>
<html>
  <head>
<% FCLTMHeader.Generate({ title: ins_info.subject });
%>
    <script>
<%  if (getQParamInt("notitie", 0) == 1) { %>
      $(function() {
        jqToast(L("lcl_mobile_data_saved"));
      });
<%  }
    else
    {
%>
      $(function() {
        if (window.sessionStorage.getItem("mobile_data_saved"))
        {
          window.sessionStorage.removeItem("mobile_data_saved");
          jqToast(L("lcl_mobile_data_saved"));
        }
      });
<%
    }
%>

    function insCheckIn()
    {
      window.location.href = "<%=rooturl%>/appl/pda/ins_deel_free.asp?ins_key=" + <%=ins_key%>;
    }

    function insCheckOut()
    {
      window.location.href = "<%=rooturl%>/appl/pda/ins_deel_free.asp?ins_key=" + <%=ins_key%>;
    }

    <% if (this_ins.writeman) { %>
        $(() => {
            $(".ins-image.tappable").on("click", insUpload);
            $("#insimg").on("change", doUpload);
        });

        function insUpload() {
            $("#insimg").trigger("click");
        }

        var uploads = [];
        function doUpload() {
            if (this.value) { /* Niets doen bij 'Annuleren' */
                uploads.push(
                new Promise((resolve, reject) => {
                    $.when(
                    $.ajax({
                        url: "<%=protectQS.create("../Shared/UploadForm_save.asp?module=INSPHD&key=" + ins_key + "&usenow=1")%>",
                        type: "POST",
                        data: new FormData(document.getElementById("deel")),
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: FcltCallbackAndThen(uploadDone)
                    }).done(resolve)
                    );
                })
                );
            }
        }

        function uploadDone(json) {
            if (json?.safefilename[0]) {
                $(".ins-image > :is(.ins-img-upload, i, img):first-child").replaceWith("<img src='" + json.deepUrl[0] + "'>");
            }
        }
    <% } %>

    async function ins_submit()
    {
        <% if (this_ins.writeman) { %>
            await Promise.all(uploads);
        <% } %>

        if (!await validateForm("deel"))
            return false;

        $.post( $("form[name=deel]")[0].action
              , $("form[name=deel]").serialize() + "<%=transitParam%>"
              , McltCallbackAndThenAlways(ins_submit_callback)
              , "json"
              );
        return true; // disable button
    }

    function ins_submit_callback(json)
    {
        if (json.success)
        {
<%          if (qrc) { %>
                // Waarschijnlijk QR-code op object.
                McltCallbackClose(json);
<%          } else if (ins_key > 0) { %>
                jqToast(L("lcl_mobile_data_saved"));
                window.location.href = "<%=rooturl%>/appl/pda/ins_deel.asp?ins_key=" + "<%=ins_key%>";
<%          } else if (ins_key < 0){ %>
                // Nieuw deel aangemaakt. Altijd complete reload, we hebben nu een ins_key namelijk
                jqToast(L("lcl_mobile_data_saved"));
                window.location.href = "<%=rooturl%>/appl/pda/ins_deel.asp?ins_key=" + json.ins_key;
                return;
<%          } %>
        }
    }

    function ins_cancel()
    {
        window.history.back();
    }

    function move_same_as_parent()
    {
      FcltMgr.confirm(L("lcl_ins_make_place_same").format("<%=safe.jsstring(ins_info.parent)%>"), function() {
        var data = { asparent: 1
                   , srtdeel: <%=ins_info.ins_srtdeel_key%>
                   , desc: "<%=ins_info.ins_deel_omschrijving%>"};
        var bind = "<%=safe.jsstring(ins_info.alg_ruimte_type_parent)%>";
        var bind_key = <%=ins_info.alg_ruimte_key_parent? ins_info.alg_ruimte_key_parent : -1%>;
        switch (bind)
        {
          case "A":
          {
            data.sDept = bind_key;
            break;
          }
          case "P":
          {
            data.sPerson = bind_key;
            break;
          }
          case "C":
          {
            data.sCntPers = bind_key;
            break;
          }
          case "R":
          {
            data.ruimtekey = bind_key;
            break;
          }
          case "W":
          {
            data.werkplekkey = bind_key;
            break;
          }
          case "T":
          {
            data.gebouwkey = bind_key;
            break;
          }
          default: INTERNAL_ERROR_UNKNOWN_BIND;
        }
        protectRequest.dataToken(data);
        $.post( "../ins/ins_edit_deel_save.asp?urole=<%=urole%>&ins_key=" + <%=ins_key%>
              , data
              , McltCallbackAndThenAlways(same_as_parent_callback)
              , "json"
              );
      });
      return true;
    }

    function same_as_parent_callback()
    {
        v_urole = "<%=urole%>";
        v_ins_key = <%=ins_key%>;
        v_return_from =  "&return_from=<%=safe.url(return_from.length? return_from : "")%>";
        window.location.replace("ins_deel.asp?urole=" + v_urole + "&ins_key=" + v_ins_key + v_return_from);
    }
    </script>
  </head>
  <body>
<%
    lcl.set_dialect(disc_key, 'INS_DISCIPLINE_KEY');

    PAGE_START();
      HEADER({title: ins_info.subject, go: return_from, back: !qrc, home: !qrc});
      CONTENT_START();
        FORM_START("deel", {action: rooturl + "/appl/ins/ins_edit_deel_save.asp?urole="+urole+"&ins_key="+ins_key, method: "get"});
        if (this_ins.writeman) {
%>          <input type="file" name="insimg" id="insimg" accept="image/*">
<%      }
         HIFIELD("srtdeel", ins_info.ins_srtdeel_key);
          if (inArray(ins_info.bindlevel, ["T","W","RL","RG","RV","RR"]))
          { // deze hebben een locatie_key
            HIFIELD("locatiekey", ins_info.locatie_key);
          }
          switch(ins_info.bindlevel)
          {
            case "A":  HIFIELD("sDept", ins_info.ruimte_key); break;
            case "P":  HIFIELD("sPerson", ins_info.ruimte_key); break;
            case "C":  HIFIELD("sCntPers", ins_info.ruimte_key); break;
            case "T":  HIFIELD("gebouwkey", ins_info.ruimte_key); break;
            case "W":  HIFIELD("werkplekkey", ins_info.ruimte_key); break;
            case "RL": HIFIELD("locatiekey", ins_info.locatie_key); break;
            case "RG": HIFIELD("gebouwkey", ""); break;
            case "RV": HIFIELD("verdiepingkey", ""); break;
            case "RR": HIFIELD("ruimtekey", ins_info.ruimte_key); break;
          }

          if (ins_info.ins_deel_verwijderd)
          {
%>          <div class="ins_deleted"><%=L("lcl_ins_is_deleted")%></div>
<%        }

        if (ins_key != -1) {

            var img = IMG(null, { "module": "INSPHD", "key": ins_key });
            var content = "";

            if (img) {
                content = img;
            } else if (this_ins.writeman) {
                content = '<div class="ins-img-upload flex-center">'
                        + '   <span class="flex-center">' + I("fa-camera fa-3x") + '</span>'
                        + '</div>';
            }

            if (content) {
%>              <div class="ins-image flex-center<%=this_ins.writeman ? " tappable" : ""%>">
                    <%=content%>
                </div>
<%          }
        }

          BLOCK_START({collapsedIcon: "fa-plus", expandedIcon: "fa-minus", collapsed: true, title: L("lcl_inssrt_general_info")});
            ROFIELD("fld", L("lcl_discipline"), ins_info.disc_omschr);
            ROFIELD("fld", L("lcl_obj_group"), ins_info.grp_omschr);
            ROFIELD("fld", L("lcl_obj_sort"), ins_info.srt_omschr);
          BLOCK_END();

          if (ins_info.ins_parent_key > -1)
          {
            ROFIELD("fld", L("lcl_ins_parentobject"), ins_info.parent);
          }
          RWFIELD("desc", L("lcl_obj_identification"), ins_info.ins_deel_omschrijving, { pclass: "required", readonly: !this_ins.canChangeAlg || !(ins_info.autonum & 2) });
          if (ins_info.ins_deel_state)
          {
            var sensorstatetext = "<span class='statedate'>" + toDateTimeString(ins_info.ins_deel_statedate, true, true, true) + "</span><span class='stateval'>" + ins_info.ins_deel_state + "</span>";
            if (!ins_info.thresholdstate)
                var presentatie = "<span>" + I("fa-sensor") + "</span><span>" + sensorstatetext + "</span>";
            else
                if (ins_info.thresholdstate > 0)
                    var presentatie = "<span class='sensoralert'>" + I("fa-exclamation-triangle fas") + "</span><span>" + sensorstatetext + "</span>";
                else
                    var presentatie = "<span class='sensorok'>" + I("fa-circle fas") + "</span><span>" + sensorstatetext + "</span>";
            Response.Write("<div class='sensorstate'>" + presentatie + "</div>");
          }

          ROFIELD("fld", ins_info.binding_text, ins_info.plaats_afdeling);
          RWFIELD("opmerk", L("lcl_ins_opmerking"), ins_info.ins_deel_opmerking, {suppressEmpty: !isNew, readonly: !this_ins.canChangeAlg});

          BLOCK_START({collapsedIcon: "fa-plus", expandedIcon: "fa-minus", collapsed: true, title: L("lcl_ins_meta_data")});
            FCLTcalendar( "aanmaakdatum"
                        , { datum: ins_info.ins_deel_aanmaak
                          , label: L("lcl_last_action")
                          , addClass: "allow_old_dates"
                          , required: true
                          , readonly: !this_ins.canChangeAlg
                          , mobile: true
                          }
                        );

            FCLTcalendar( "vervaldatum"
                        , { datum: ins_info.ins_deel_vervaldatum
                          , label: L("lcl_ins_vervaldatum")
                          , initEmpty: (ins_info.ins_deel_vervaldatum == null)
                          , suppressEmpty: true
                          , readonly: !this_ins.canChangeAlg
                          , mobile: true
                          }
                        );

            CHB_FIELD("ins_actief", L("lcl_ins_active"), ins_info.ins_deel_actief, {disabled: !this_ins.canChangeAlg});

            FCLTpersoonselector( "ins_manager" // beheerder
                               , "sgins_manager"
                               , { perslidKey: ins_info.perslid_key_beh
                                 , autlevel: authparams && authparams.PRSwritelevel
                                 , label: L("lcl_ins_manager")
                                 , filtercode: "INSB"
                                 , required: false
                                 , suppressEmpty: true
                                 , readonly: ((ins_key > 0) && (!this_ins.writeman || urole == "fo"))
                                 , moreinfo: false
                                 , mobile: true
                                 }
                               );

            if (ins_score_enabled)
            {
              ROFIELD("fld", L("lcl_ins_deel_mjb_score1"), ins_info.ins_deel_mjb_score1, {suppressEmpty: true});
              ROFIELD("fld", L("lcl_ins_deel_mjb_score2"), ins_info.ins_deel_mjb_score2, {suppressEmpty: true});
            }
          BLOCK_END();

          // Plus flexkenmerken
          generateFlexKenmerkBlock({ urole: (isNew ? "bo" : "fe")
                                   , ins_key: ins_key
                                   , srtdeel_key: ins_info.ins_srtdeel_key
                                   , srtdeelkey_array: (ins_info.ins_srtdeel_key > 0 ? [ins_info.ins_srtdeel_key] : [])
                                   , reado: !isNew
                                   , mobile: true
                               //    , bewerkniveau: "D"
                                   });

          // Heeft deel ook onderdelen?
          var sql = "SELECT COUNT(*)"
                  + "  FROM ins_v_aanwezigonderdeel"
                  + " WHERE ins_deel_parent_key = " + ins_key;
          oRs = Oracle.Execute(sql);
          var hasOnderdelen = (oRs(0).Value > 0);
          oRs.Close();

          // Heeft deel ook relaties
          var sql = "SELECT COUNT(ins_deelkoppeling_key) aantal"
                  + "  FROM ins_deelkoppeling"
                  + " WHERE ins_deelkoppeling_naar_key = " + ins_key
                  + "    OR ins_deelkoppeling_van_key = " + ins_key
          oRs = Oracle.Execute(sql);
          var hasKoppel = (oRs("aantal").Value > 0);
          oRs.Close();

          // Inspecties mogelijk op dit object?
          var sql = "SELECT COUNT(*)"
                  + "  FROM ins_srtcontrole isc,"
                  + "       ins_v_deelenonderdeel d,"
                  + "       ins_srtdeel sd"
                  + " WHERE sd.ins_srtdeel_key = d.ins_srtdeel_key"
                  + "   AND ins_deel_key = " + ins_key
                  + "  AND (    isc.ins_srtcontrole_niveau = 'S' AND isc.ins_srtinstallatie_key = d.ins_srtdeel_key"
                  + "        OR isc.ins_srtcontrole_niveau = 'G' AND isc.ins_srtinstallatie_key = sd.ins_srtgroep_key"
                  + "        OR isc.ins_srtcontrole_niveau = 'D' AND isc.ins_srtinstallatie_key = d.ins_discipline_key"
                  + "      )"
          oRs = Oracle.Execute(sql);
          canInspect = (oRs(0).Value > 0);
          oRs.Close();
          //TODO-AUTH: mag ik deze soort (hier) inspecteren?

          sql = "SELECT res_deel_key, rad.res_discipline_key"
              + "  FROM res_deel d, res_activiteitdiscipline rad"
              + " WHERE res_deel_verwijder IS NULL"
              + "   AND rad.res_discipline_key = d.res_discipline_key"
              + "   AND rad.res_discipline_key != " + S("vis_parking_key")
              + "   AND res_ins_deel_key = " + ins_key;
          oRs = Oracle.Execute(sql);
          if (!oRs.eof) {
            isResDeel = true;
            var authparamsRESUSE = user.checkAutorisation("WEB_RESUSE", true, oRs("res_discipline_key").Value);
            var canResWrite = authparamsRESUSE && authparamsRESUSE.PRSwritelevel < 9 && authparamsRESUSE.ALGwritelevel < 9;
          }
          oRs.Close();

          //TODO-AUTH: mag ik deze soort (hier) reserveren?

            function aboutMeldingen(ins_key)
            {
                var mldResult = { canAdd: false
                                , canShow: false
                                };
                if (ins_key > 0 && user.checkAutorisation( "WEB_MLDUSE", true))
                {   // Als ik een melding wil toevoegen, dan moet er wel een srtdiscipline getoond kunnen worden.
                    var mySRTsql = mld.srtdisc_sql({ ins_key: ins_key });
                    var sql = "SELECT MIN(ins_srtdiscipline_key) ins_srtdiscipline_key"
                            + "     , COUNT(DISTINCT ins_srtdiscipline_key) aantal"
                            + "  FROM (" +  mySRTsql + ")";
                    var oRs = Oracle.Execute(sql);
                    mldResult.canAdd = (oRs("aantal").Value > 0);
                    oRs.Close();

                    var tsql = "SELECT m.mld_melding_key"
                             + "  FROM mld_melding_object mo"
                             + "     , mld_melding m"
                             + " WHERE mo.mld_melding_object_verwijder IS NULL"
                             + "   AND mo.mld_melding_key = m.mld_melding_key"
                             + "   AND m.mld_melding_status IN (0, 2, 4, 7)"  // lopende meldingen
                             + "   AND mo.ins_deel_key = " + ins_key;
                    mldResult.transit_status = "0,2,4,7";
                    if (S("cnd_gebreken_srtdisc_key") != -1)
                    {
                        tsql += " UNION "
                              + "SELECT m.mld_melding_key"
                              + "  FROM mld_melding_object mo"
                              + "     , mld_melding m"
                              + "     , mld_stdmelding s"
                              + "     , mld_discipline d"
                              + " WHERE mo.mld_melding_key = m.mld_melding_key"
                              + "   AND mo.mld_melding_object_verwijder IS NULL"
                              + "   AND m.mld_stdmelding_key = s.mld_stdmelding_key"
                              + "   AND s.mld_ins_discipline_key = d.ins_discipline_key"
                              + "   AND m.mld_melding_status = 5" // afgemelde melding
                              + "   AND mo.ins_deel_key = " + ins_key
                              + "   AND d.ins_srtdiscipline_key = " + S("cnd_gebreken_srtdisc_key");
                        mldResult.transit_status += ",5";
                    }
                    tsql = "SELECT COUNT(*) FROM (" + tsql + ")";
                    var toRs = Oracle.Execute(tsql);
                    mldResult.mldCount = toRs(0).Value;
                    toRs.Close();
                    mldResult.canShow = ( (mldResult.mldCount > 0) && (user.checkAutorisation( "WEB_MLDBOF", true) || user.checkAutorisation( "WEB_MLDFOF", true) || user.checkAutorisation( "WEB_MLDBAC", true)))
                }
                return mldResult;
            }

            CONTROLGROUP_START();

            trackinglines = mobile.hastrackingpage("deel", ins_key);

            if (btns["ins_save"] && (this_ins.canChangeAlg || this_ins.canChange)) {
                BUTTON((ins_key>-1 ? L("lcl_submit") : L("lcl_newsubmit")), {click: "ins_submit()", icon: "fa-fclt-save", singlepress: (ins_key == -1) });
            }
            if (!isNew)
            {
                if (btns["ins_obj_lend_out"] && fronto && eLendOut)
                { // uitleenmodule
                    BUTTON(L("lcl_obj_lend_out"), {click: "insCheckOut()", icon: "fa-arrow-up" });
                }
                if (btns["ins_obj_receive"] && fronto && eReceive)
                { // uitleenmodule
                    BUTTON(L("lcl_obj_receive"), {click: "insCheckIn()", icon: "fa-arrow-down" });
                }
                if (isResDeel && canResWrite)
                {
                    if (btns["ins_reserve"])
                        BUTTON(L("lcl_mobile_reserve"), {linkid: "./reserveringen.asp?ins_key=" + ins_key + transitParam, icon: "fa-calendar-plus" });
                    if (btns["ins_claim_res"] && qrc)
                        BUTTON(L("lcl_mobile_claimwp"), {linkid: "./res_claimwp.asp?fromins=1&ins_deel_key=" + ins_key + transitParam, icon: "fa-calendar-check" });
                }
                if (btns["ins_inspect"] && canInspect)
                {
                    BUTTON(L("lcl_mobile_inspecties"), {linkid: "./ins_inspect_list.asp?ins_key=" + ins_key + transitParam, icon: "fa-list" });
                }
                if (btns["ins_sub_objects"] && hasOnderdelen)
                {
                    BUTTON(L("lcl_subobjects"), {linkid: "./ins_list.asp?ins_parent_key=" + ins_key +"&plaatsfilter=0" + transitParam, icon: "fa-cog" });
                }
                if (btns["ins_koppel"] && hasKoppel)
                {
                    BUTTON(L("lcl_ins_koppelobjects"), {linkid: "./ins_list.asp?koppel_key=" + ins_key + transitParam, icon: "fa-diagram-project" });
                }
                if (btns["ins_move"] && this_ins.canMove)
                {
                    var move_params = "?urole="+urole + "&ins_key="+ins_key + (return_from.length ? "&return_from=" + safe.url(return_from) : "");
                    BUTTON(L("lcl_ins_move"), {linkid: "./ins_deel_move.asp"+move_params, icon: "fa-arrows" });
                }
                if (btns["ins_same_as_parent"] && this_ins.canSameAsParent)
                {
                    BUTTON(L("lcl_ins_place_same_as_parent").format(ins_info.parent), {click: "move_same_as_parent()", icon: "fa-fclt-copy"});
                }
                if (btns["ins_history"] && trackinglines > 0 && this_ins.canReadHistory)
                {
                    BUTTON(L("lcl_history"), {linkid: "#ins-2-"+ins_key, icon: "fa-list"});
                }
                var withMeldingen = aboutMeldingen(ins_key);
                if (btns["ins_add_mld"] && withMeldingen.canAdd)
                {
                    BUTTON(L("lcl_mobile_newmelding"), {linkid: "./melding.asp?mld_key=-1&ins_key=" + ins_key + transitParam, icon: "fa-plus" });
                }
                if (btns["ins_show_mld"] && withMeldingen.canShow)
                {
                    transitParam += "&status=" + withMeldingen.transit_status;
                    BUTTON(L("lcl_mobile_meldingen") + " (" + withMeldingen.mldCount + ")", {linkid: "./mld_list.asp?ins_key=" + ins_key + transitParam, icon: "fa-exclamation-circle"});
                }
                if (btns["ins_notes"] && this_ins.canChange)
                {   // Heb ik rechten om notities te zien
                    var tsql = "SELECT COUNT(*) FROM ins_deel_note n WHERE n.ins_deel_key = " + ins_key;
                    toRs = Oracle.Execute(tsql);
                    BUTTON(L("lcl_ins_deel_notes")+" ("+toRs(0).value+")", {linkid: rooturl+"/appl/pda/notitie.asp?node=deel&key="+ins_key, icon: "fa-comment" });
                    toRs.Close();
                }
            }
            else
            {
                if (btns["ins_save"] && (this_ins.canChangeAlg || this_ins.canChange)) {
                    BUTTON(L("lcl_cancel"), {click: "mobile.changePage();", icon: "fa-fclt-cancel"} );
                }
            }
            CONTROLGROUP_END();
        FORM_RVT();
        FORM_END();
      CONTENT_END();
      FOOTER();
    PAGE_END();

    if (trackinglines>0)
    {
        PAGE_START({id: "ins-2-"+ins_key, dialog: true})
            mobile.trackingpage("deel", ins_key, ins_info.subject);
        PAGE_END();
    }
PDA_PAGE_END(); %>
	</body>
</html>
<% ASPPAGE_END(); %>
