<% /*
     $Revision$
     $Id$
    File:               alg_gebouw.inc
    Description:        Show an overview of gebouw items in list-form,
                        which meets with the given requirements
    Parameters:
    Context:            Search action from alg_gebouw_search_list.asp form
    Note:
*/ %>

<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/getkenmerksql.inc" -->
<!-- #include file="alg.inc" -->

<%
FCLTHeader.Requires({ plugins: ["jQuery"] });

  var cnt_full = getQParamInt("cnt_full", 1);

  // Fast check to see if any building responsibles have been set
  // If not, we can suppress the column
  sql = "SELECT 1 FROM alg_gebouw"
      + " WHERE prs_perslid_key_verantw IS NOT NULL"
      + " AND alg_gebouw_verwijder IS NULL AND ROWNUM = 1";
  oRs = Oracle.Execute(sql);
  var anybldresp = !oRs.eof;
  oRs.close()

  // We gaan er vanuit dat verwantw2 niet is gezet als nergens verantw1 wordt getoond.
  // Als dat wel zo is, jammer maar dan tonen we die niet in de lijst.
  var anybldresp2 = false;
  if (anybldresp)
  {
    sql = "SELECT 1 FROM alg_gebouw"
      + " WHERE prs_perslid_key_verantw2 IS NOT NULL"
      + " AND alg_gebouw_verwijder IS NULL AND ROWNUM = 1";
    oRs = Oracle.Execute(sql);
    anybldresp2 = !oRs.eof;
    oRs.close()
  }

  var canImport = (user.checkAutorisation("WEB_IMPORT", true) != null);
%>
<script type="text/javascript">

  var autosearch = 1 // automatisch laden van resultaat op search pagina

  function gotoDetails(row)
  {
    var algData = JSON.parse(row.getAttribute("ROWDATA"));
    var url = "appl/alg/alg_verdieping_search.asp?gebouw_key=" + algData.detail_key + "&autosearch=" + autosearch + "&chkgeb=1";
    FcltMgr.openDetail(url, L("lcl_floor"));
  }

  function gotoParent(row)
  {
    var algData = JSON.parse(row.getAttribute("ROWDATA"));
    var url = "appl/alg/alg_locatie_search.asp?locatie_key=" + algData.parent_key + "&autosearch=" + autosearch;
    FcltMgr.openDetail(url, L("lcl_location"));
  }

  function gebouwEdit(row)
  {
    var algData = JSON.parse(row.getAttribute("ROWDATA"));
    var url = "appl/alg/alg_gebouw.asp?mode=viewChange&key=" + algData.key + "&cnt_full=<%=cnt_full%>";
    FcltMgr.openDetail(url, L("lcl_building") + " " + algData.oms);
  }

  function aggregateCNDscores(rowArray, isMulti)
  {
    FcltMgr.confirm(L("cnd_aggregate_confirm"), { autoconfirm: isMulti }, function() {
        var locKeyString = getKeyString(rowArray);
        var data = { key: locKeyString,
                     level: "G"
                   };
        <% protectRequest.dataToken("data"); %>
        $.post("alg_cnd_aggregate.asp", data, FcltCallbackRefresh, "json");
    });
  }

  function gebouwEditMulti(rowArray, isMulti)
  {
      var bldKeyString = getKeyString(rowArray);
      var subject = L("lcl_alg_multi_edit");
      var url = "../alg/alg_edit_gebouw_multi.asp?bld_keys=" + bldKeyString;
      FcltMgr.openModalDetail(url, subject, {callback: FcltCallbackRefresh});
  }

  function doDelete(rowArray, isMulti)
  {
    FcltMgr.confirm(L("lcl_alg_del_txt_gebouw"), { autoconfirm: isMulti }, function() {
      var bldKeyString = getKeyString(rowArray);
      var data = { key: bldKeyString,
                   level: "G"
                 };
      <% protectRequest.dataToken("data"); %>
      $.post("alg_delete.asp", data, FcltCallbackRefresh, "json");
    });
  }

  function toObjMan(row)
  {
    var algData = JSON.parse(row.getAttribute("ROWDATA"));
    var url = "appl/ins/ins_search.asp?urole=bo&gebouw_key=" + algData.key;
    FcltMgr.openDetail(url, L("lcl_building") + " " + algData.oms);
  }
</script>
<%

function gebouw_list(pautfunction, params)
{
  // De functie checkAutorisation(autfunction) geeft een Response.End indien er geen autorisatie voor autfunction wordt gevonden
  var addButton = [];
  var authparams = alg.checkAutorisation();
  var canAdd = (authparams.mALGwritelevel < 4);

  // Voor resulttable de globalen zetten; zou ng anders moeten.
  var outputmode = params.outputmode; // print to 0 = screen, 1 = printer, 2 = excel, etc.
  var showall = params.showall;

  var noref = params.noref;

  var ins_score_enabled = S("ins_score_enabled") == 1;
  var reg_key = params.reg_key;
  var dis_key = params.dis_key;
  var loc_key = params.loc_key;
  var bld_key = params.bld_key;
  var srtgebouw_key = params.srtgebouw_key;
  var verantw_key = params.verantw_key;
  var expalgincl = params.expalgincl;
  var fitness_score1_from = params.fitness_score1_from;
  var fitness_score1_through = params.fitness_score1_through;

  var transitParam = buildTransitParam(["locatiekey", "urole", "bld_key", "flo_key", "room_key"]);
  var rstFilters = params.rstFilters;
  var checkBoxes = [
    {
     lcl: L("lcl_alg_gebouw_vervallen_incl"),
     param: 'expAlgIncl',
     checked: expalgincl,
     transitParams: transitParam
    }
  ];

  var rstCheckBoxes = rstFilters ? checkBoxes : [];
  var autparamsINSUSE = user.checkAutorisation("WEB_INSUSE", true);
  var autparamsINSMAN = user.checkAutorisation("WEB_INSMAN", true);
  var readuse = autparamsINSUSE && autparamsINSUSE.PRSreadlevel < 9 && autparamsINSUSE.ALGreadlevel < 9; // Wijzigen Afgeronde gegevens.
  var readman = autparamsINSMAN && autparamsINSMAN.PRSreadlevel < 9 && autparamsINSMAN.ALGreadlevel < 9; // Wijzigen Afgeronde gegevens.
%>

  <html>
    <head>
      <% FCLTHeader.Generate({outputmode: outputmode}) %>
    </head>
    <body id="listbody">
<%
  var flexParams = alg.alg_onroerendgoed_flex_params("G");
  var sqln = "SELECT g.alg_gebouw_key"
           + "     , g.alg_locatie_key"
           + "     , g.alg_srtgebouw_key"
           + "     , l.alg_locatie_omschrijving"
           + "     , " + lcl.xsqla('s.alg_srtgebouw_omschrijving', 's.alg_srtgebouw_key')
           + "     , g.alg_gebouw_code"
           + "     , g.alg_gebouw_naam"
           + "     , COALESCE(g.alg_gebouw_adres, l.alg_locatie_adres) adres"
           + "     , COALESCE(g.alg_gebouw_postcode, l.alg_locatie_postcode) postcode"
           + "     , l.alg_locatie_plaats"
           + "     , g.alg_gebouw_omschrijving"
           + "     , g.alg_gebouw_opmerking"
           + "     , g.alg_gebouw_bruto_vloeropp"
           + "     , g.alg_gebouw_omtrek"
           + "     , g.alg_gebouw_inhoud"
           + "     , g.alg_gebouw_x"
           + "     , g.alg_gebouw_y"
           + "     , g.alg_gebouw_vervaldatum"
           + "     , g.alg_gebouw_mjb_score1"
           + "     , (SELECT prs_perslid_naam_full FROM prs_v_perslid_fullnames_all WHERE prs_perslid_key = prs_perslid_key_verantw) perslid_resp"
           + "     , (SELECT prs_perslid_naam_full FROM prs_v_perslid_fullnames_all WHERE prs_perslid_key = prs_perslid_key_verantw2) perslid_resp2"
           + "     , g.alg_gebouw_email"
           + "     , (SELECT mld_adres_naam FROM mld_adres ma WHERE ma.mld_adres_key = g.mld_adres_key) delivery_adr"
           + "     , (SELECT MAX(t.fac_tracking_datum)"
           + "          FROM fac_tracking t"
           + "             , fac_srtnotificatie sn"
           + "         WHERE t.fac_srtnotificatie_key = sn.fac_srtnotificatie_key"
           + "           AND t.fac_tracking_refkey = g.alg_gebouw_key"
           + "           AND sn.fac_srtnotificatie_xmlnode = 'gebouw'"
           + "       ) recentdatum"
           +       flexParams.sql
           + "  FROM alg_gebouw g"
           + "     , alg_locatie l"
           + "     , alg_srtgebouw s"
           + " WHERE l.alg_locatie_key(+) = g.alg_locatie_key"
           + "   AND s.alg_srtgebouw_key(+) = g.alg_srtgebouw_key"
           + "   AND g.alg_gebouw_verwijder IS NULL";

    if ( authparams.ALGreadlevel > -1 )
    {  // Er is een scope-beperking van kracht
      sqln += " AND g.alg_gebouw_key IN (SELECT alg_gebouw_key FROM fac_v_my_buildings "
            + "                           WHERE prs_perslid_key = " + user_key
            + "                             AND niveau = " + authparams.ALGreadlevel + ")";
    }

    sqln += getKenmerkSql("ALG", "g.alg_gebouw_key");

    if (bld_key)
      sqln += " AND g.alg_gebouw_key = " + bld_key;
    else if (loc_key)
      sqln += " AND g.alg_locatie_key = " + loc_key;
    else if (dis_key)
      sqln += " AND l.alg_district_key = " + dis_key;
    else if (reg_key)
      sqln += " AND l.alg_district_key IN (SELECT alg_district_key FROM alg_district WHERE alg_regio_key = " + reg_key+")";

    if (params.bld_code)
        sqln += " AND UPPER(g.alg_gebouw_code) LIKE " + safe.quoted_sql_wild(params.bld_code + "%");
    if (params.bld_name)
        sqln += " AND UPPER(g.alg_gebouw_naam) LIKE " + safe.quoted_sql_wild(params.bld_name + "%");
    if (params.bld_email)
        sqln += " AND UPPER(g.alg_gebouw_email) LIKE " + safe.quoted_sql_wild("%" + params.bld_email + "%");
    if (params.bld_groep)
        sqln += " AND UPPER(g.alg_gebouw_groep) LIKE " + safe.quoted_sql_wild("%" + params.bld_groep + "%");

    if (srtgebouw_key)
      sqln += " AND g.alg_srtgebouw_key = " + srtgebouw_key;

    if (verantw_key)
      sqln += " AND (g.prs_perslid_key_verantw = " + verantw_key + " OR g.prs_perslid_key_verantw2 = " + verantw_key + ")";

    if (!expalgincl)
      sqln += " AND (g.alg_gebouw_vervaldatum IS NULL OR g.alg_gebouw_vervaldatum > TRUNC(SYSDATE)) ";

    if (ins_score_enabled)
    { // Conditiescore.
      // Niet gemeten objecten doen wel mee in dit filter. Deze objecten worden dus niet getoond als er een waarde is ingevuld.
      if (fitness_score1_from > 0)
        sqln += " AND alg_gebouw_mjb_score1 >= " + fitness_score1_from;
      if (fitness_score1_through > 0)
        sqln += " AND alg_gebouw_mjb_score1 <= " + fitness_score1_through;
    }

    sqln += " ORDER BY l.alg_locatie_upper ASC, "
          +  "          g.alg_gebouw_upper ASC  ";

    var addurl = "appl/alg/alg_gebouw.asp";

    var addButton = [];
    if (canAdd)
    {
      addButton.push({ icon: "fa-plus", title: L("lcl_add"), action: "FcltMgr.openDetail('" + addurl + "', '" + safe.jsstring(L("lcl_add")) + "')" });
    }

    /**********************************
    * Callback functies ResultsetTable
     *********************************/
    var recent = new Date();

    function fnrowData(oRs)
    {
      var parent_key = oRs("alg_locatie_key").value;
      var detail_key = oRs("alg_gebouw_key").value;
      var key        = oRs("alg_gebouw_key").value;
      var oms        = oRs("alg_gebouw_naam").value;

      var data = {parent_key: parent_key, detail_key: detail_key, key: key, oms: oms};
      return JSON.stringify(data);
    }

    function fnrowClass(oRs)
    {
      var lclass = "";
      // Tracking: hoe lang geleden voor het laatst gewijzigd?
      if (oRs.Fields("recentdatum").Value != null)
      {
        var ltrackdate1 = new Date();
        var ltrackdate10 = new Date();
        var ltrackdate100 = new Date();
        var alg_onrgoed_recent = S("alg_onrgoed_recent");
        ltrackdate1.setMinutes(recent.getMinutes() - alg_onrgoed_recent);
        ltrackdate10.setMinutes(recent.getMinutes() - alg_onrgoed_recent * 12);
        ltrackdate100.setMinutes(recent.getMinutes() - alg_onrgoed_recent*12*2);

        var fac_recent = new Date(oRs.Fields("recentdatum").Value);
        if (fac_recent > ltrackdate1)
        {
          lclass += " updated";
        }
        else if (fac_recent > ltrackdate10)
        {
          lclass += " updated10";
        }
        else if (fac_recent > ltrackdate100)
        {
          lclass += " updated100";
        }
      }
      return lclass;
    }

    function fnrowActionEnabler(oRs)
    {
      var eDelete = false;
      var eEditMulti = false;
      var eObjMan = false;
      if (alg.canWriteGebouw(oRs("alg_gebouw_key").value, authparams.mALGwritelevel))
      {
        eDelete = true;
        eEditMulti = true;
      }
      // Heb ik rechten om het objectenbeheer overzicht te zien?
      if (readuse || readman)
        eObjMan = true;
      return ({eDelete: eDelete, eEditMulti: eEditMulti, eObjMan: eObjMan});
    }

    function fnrowFlexParams(oRs)
    {
      var bld_key = oRs("alg_gebouw_key").Value;
      var this_alg = alg.func_enabled(bld_key, "G");

      var flexParams = { readman: this_alg.readman, readuse: this_alg.readuse};
      return flexParams;
    }

    function fncolFlexBijlagen(oRs)
    {
      var flexval = oRs("algflex").Value;
      var alg_key = oRs("alg_gebouw_key").Value;
      var result = ( flexval
                   ? safe.html(flexval.replace(/\r/g, "\n")+ "\n")
                   : ""
                   );
      if (flexParams.bijlageflex)
      {
        result += alg.alg_onroerendgoed_flex_bijlagen("G", alg_key);
      }
      return result;
    }

    var rst = new ResultsetTable({ sql:sqln,
                                   keyColumn: "alg_gebouw_key",
                                   ID: "algtable",
                                   title: L("lcl_menu_alg_gebouw"),
                                   showAll: showall,
                                   rowData: fnrowData,
                                   rowClass: fnrowClass,
                                   rowActionEnabler: fnrowActionEnabler,
                                   flexModule: "ALG",
                                   flexId: "alg_gebouw_key",
                                   flexParams: fnrowFlexParams,
                                   filterParams: params,
                                   outputmode: outputmode,
                                   buttons: addButton,
                                   rstCheckBoxes: rstCheckBoxes,
                                   roundtripCode: (canImport ? "ONRGOED1" : "")
                                  });

    rst.addColumn(new Column({caption: L("lcl_estate_locatie_man_descr"), content: "alg_locatie_omschrijving"}));
    rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_code"), content: "alg_gebouw_code"}));
    rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_name"), content: "alg_gebouw_naam" }));
    rst.addColumn(new Column({caption: L("lcl_estate_gebouw_srtgebouw"), content: "alg_srtgebouw_omschrijving"}));
    rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_descr"), content: "alg_gebouw_omschrijving" }));
    rst.addColumn(new Column({caption: L("lcl_adress"), content: "adres" }));  // gebouwadres anders locatieadres
    rst.addColumn(new Column({caption: L("lcl_prs_address_bezoek_postcode"), content: "postcode"}));
    rst.addColumn(new Column({caption: L("lcl_alg_loc_plaats"), content: "alg_locatie_plaats"}));
    if (anybldresp)
    {
      rst.addColumn(new Column({caption: L("lcl_alg_verantw"), content: "perslid_resp"}));
      if (anybldresp2)
        rst.addColumn(new Column({caption: L("lcl_alg_verantw2"), content: "perslid_resp2", combine: true}));
    }
    rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_bruto_vloeropp"), content: "alg_gebouw_bruto_vloeropp", datatype: "float", decimals: 2}));
    rst.addColumn(new Column({caption: L("lcl_alg_vervaldatum"), content: "alg_gebouw_vervaldatum", datatype: "date"}));
    if (outputmode != 0)
    {
      rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_opmerk"), content: "alg_gebouw_opmerking"}));
      rst.addColumn(new Column({caption: L("lcl_alg_gebouw_email"), content: "alg_gebouw_email"}));
      rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_omtrek"), content: "alg_gebouw_omtrek"}));
      rst.addColumn(new Column({caption: L("lcl_estate_gebouw_man_inhoud"), content: "alg_gebouw_inhoud"}));
      rst.addColumn(new Column({caption: L("lcl_delivery_address"), content: "delivery_adr"}));
      rst.addColumn(new Column({caption: L("lcl_geoxcoord"), content: "alg_gebouw_x"}));
      rst.addColumn(new Column({caption: L("lcl_geoycoord"), content: "alg_gebouw_y"}));
    }
    if (ins_score_enabled)
      rst.addColumn(new Column({caption: L("lcl_alg_gebouw_mjb_score1"), content: "alg_gebouw_mjb_score1", datatype: "number"}));
    if (flexParams.anyflex)
      rst.addColumn(new Column({caption: flexParams.flexlabel, content: fncolFlexBijlagen, colName: "fncolFlexBijlagen"}));

    rst.addAction({ action: "gebouwEdit", caption: L("lcl_edit"), isDefault:  true});
    if (S("cnd_gebreken_srtdisc_key") > -1)
        rst.addAction({ action: "aggregateCNDscores", caption: L("cnd_aggr_conditiescores"), multi: true, multiOnce: true});
    rst.addAction({ action: "gebouwEditMulti", caption: L("lcl_alg_multi_edit"), enabler: "eEditMulti", single:false, multi: true, multiOnce: true});
    rst.addAction({ action: "doDelete", caption: L("lcl_delete"), enabler: "eDelete", single:!noref, multi: true, multiOnce: true});
    rst.addAction({ action: "toObjMan", caption: L("lcl_ins_object_management"), enabler: "eObjMan"});
    var cnt = rst.processResultset();
%>
    </body>
  </html>
<%
} %>
