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

    File:         ins_deel_free.asp
    Description:  Modal screen

    Parameters:   ins_key of
                  res_deel_key (dan zoeken we ins_key zelf wel op)

    Context:
    Note:

*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/contactpersoonselector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/plaatsselector.inc" -->
<!-- #include file="../ins/ins_flexkenmerk.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/objectselector.inc" -->
<!-- #include file="../ins/ins.inc" -->
<!-- #include file="./mobile.inc" -->
<!-- #include file="./iface.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery", "suggest"],
                      js: ["jquery-ui.js"]
                    });

var has_rsvdeel = false;
var qrc = getQParamInt("qrc", 0) != 0;
var rsv_deel_key = getQParamInt("rsv_deel_key", -1); // We komen uit een bestaande reservering
if (rsv_deel_key > 0)
{
    var sql = "SELECT res_ins_deel_key"
            + "  FROM res_rsv_deel rrd,"
            + "       res_deel rd"
            + " WHERE rrd.res_deel_key = rd.res_deel_key"
            + "   AND res_rsv_deel_key = " + rsv_deel_key;
    var oRs = Oracle.Execute(sql);
    obj_key = oRs("res_ins_deel_key").Value;
    oRs.Close();
}
else
    var obj_key = getQParamInt("ins_key", -1);

user.anything_todo_or_abort(obj_key > 0);

var adapt = getQParamInt("adapt", 0) == 1;

// Indien het een sleutel of cilinder betreft dan WEB_SLEFOF rechten i.p.v. WEB_INSFOF rechten.
if (obj_key > 0 && ins.isSleCil(obj_key))
  var autfunction = "WEB_SLEFOF";
else
  var autfunction = "WEB_INSFOF";
var authparams = user.checkAutorisation(autfunction);

var isLendOut = false;
var isCil = false;
if (obj_key > 0)
{ // Object uitlenen of innemen
  var sql = "SELECT s.ins_srtdeel_key"
          + ", d.ins_deel_omschrijving"
          + ", " + lcl.xsqla('s.ins_srtdeel_omschrijving', 's.ins_srtdeel_key')
          + ", s.ins_srtgroep_key"
          + ", d.ins_alg_ruimte_key_org"
          + ", d.ins_alg_ruimte_key"
          + ", d.ins_alg_ruimte_type"
          + " FROM ins_deel d"
          + ", ins_srtdeel s"
          + ", ins_srtgroep g"
          + ", ins_tab_discipline dis"
          + " WHERE ins_deel_key = " + obj_key
          + " AND d.ins_srtdeel_key = s.ins_srtdeel_key"
          + " AND s.ins_srtgroep_key = g.ins_srtgroep_key"
          + " AND g.ins_discipline_key = dis.ins_discipline_key";
  var oRs = Oracle.Execute(sql);
  var desc = oRs("ins_deel_omschrijving").value;
  var sort = oRs("ins_srtdeel_omschrijving").value;
  var sort_key = oRs("ins_srtdeel_key").value;
  var algprs_key = oRs("ins_alg_ruimte_key").value; // alg_key (niet uitgeleend) of prs_key (uitgeleend)
  var alg_ruimte_type = oRs("ins_alg_ruimte_type").value; // alg_key (niet uitgeleend) of prs_key (uitgeleend)
  var subject = sort+ " " +desc;
  isLendOut = oRs("ins_alg_ruimte_key_org").value != null;
  isCil = oRs("ins_srtgroep_key").value == S("cil_ins_srt_groep_key");
  oRs.Close();

  if (isCil)
  {
    sql = "SELECT aor.alg_locatie_key"
        + "     , aor.alg_gebouw_key"
        + "     , aor.alg_terreinsector_key"
        + "     , aor.alg_verdieping_key"
        + "     , aor.alg_ruimte_key"
        + "     , aor.alg_type"
        + "  FROM alg_v_allonroerendgoed aor"
        + " WHERE aor.alg_onroerendgoed_keys = " + algprs_key;
    var oRs_1 = Oracle.Execute(sql);

    var loc_key = oRs_1("alg_locatie_key").value;
    var bld_key = oRs_1("alg_gebouw_key").value;
    var ter_key = oRs_1("alg_terreinsector_key").value;
    var flr_key = oRs_1("alg_verdieping_key").value;
    var room_key = oRs_1("alg_ruimte_key").value;
    var alg_type = oRs_1("alg_type").value;
    oRs_1.Close();
  }

  var default_prs_key = null;
  var restxt = "";
  var hasreservering = false;
  var has_rsvdeel = (rsv_deel_key > 0) && !isLendOut;
  var res_rsv_deel_key = null;
  // Is het object ook reserveerbaar?
  var sql = "SELECT res_deel_key,"
          + "       res_deel_image,"
          + "       res_deel_opmerking"
          + "  FROM res_deel"
          + " WHERE res_ins_deel_key = " + obj_key;
  var oRs = Oracle.Execute(sql);
  if (!oRs.Eof)
  {
      restxt = L("lcl_ins_lend_no_res"); // Geen toekomstige reservering gevonden
      var res_deel_key = oRs("res_deel_key").Value;
      var res_deel_image = oRs("res_deel_image").Value;
      if (!isLendOut)
      {
        // zoek contactpersoon van eerstkomende reservering
        sql = "SELECT rrr.res_reservering_key,"
            + "       rrr.res_rsv_ruimte_volgnr,"
            + "       rrr.res_rsv_ruimte_van, "
            + "       rrr.res_rsv_ruimte_host_key,"
            + "       rrd.res_rsv_deel_key,"
            + S("prs_pers_string") + " host_naam"
            + "  FROM res_rsv_ruimte rrr,"
            + "       res_rsv_deel rrd,"
            + "       prs_perslid p"
            + " WHERE res_rsv_ruimte_host_key = p.prs_perslid_key(+)"
            + "   AND rrd.res_rsv_ruimte_key = rrr.res_rsv_ruimte_key"
            + "   AND res_rsv_deel_verwijder IS NULL"
            + "   AND res_deel_key = " + res_deel_key;
        if (rsv_deel_key > 0)
          sql += "   AND res_rsv_deel_key = " + rsv_deel_key;
        else
           sql += "   AND res_rsv_deel_tot > SYSDATE"
               + " ORDER BY res_rsv_deel_tot ASC"; // eerstkomende eerst
        oRs2 = Oracle.Execute(sql);
        if (!oRs2.Eof)
        {
          default_prs_key = oRs2("res_rsv_ruimte_host_key").Value; // gedachte is dat de gastheer daadwerkelijk naar
                                                                   // de zaal gaat en de contactpersoon niet per se
          restxt = L("lcl_ins_lend_next_res").format(
                            String(oRs2("res_reservering_key").value) + "/" + oRs2("res_rsv_ruimte_volgnr").value,
                            toDateTimeString(oRs2("res_rsv_ruimte_van").Value),
                            oRs2("host_naam").Value);
          hasreservering = true;
          res_rsv_deel_key = oRs2("res_rsv_deel_key").Value;
        }
        oRs2.Close();
      }
  }
  oRs.Close();

}

%>
<html>
  <head>
<%
    FCLTMHeader.Generate();
%>
    <script type="text/javascript">

      $(function() {
        if (window.sessionStorage.getItem("mobile_data_saved"))
        {
          window.sessionStorage.removeItem("mobile_data_saved");
          jqToast(L("lcl_mobile_data_saved"));
        }
      });

      async function ins_submit()
      {
        document.activeElement.blur(); // trigger laatste onChanges
        if (!await validateForm("u2"))
          return false;
        var data = $("form").serializeArray();
        protectRequest.dataToken(data);

        var backAndReload = McltCallbackAndThen(function (json)
        {
           window.sessionStorage.setItem("mobile_data_saved", true);
           window.history.back(1);
        });

        $.post("<%=rooturl%>/appl/ins/ins_deel_free_save.asp",
               data, //TODO: Gewoon submit van het formulier en ins_deel_free_save.asp hierop aanpassen.
               backAndReload,
               "json");
        return true; // disable button
      }

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

      function onChangeGebouw()
      {
        var isGebouw = $("#bttype").val() == "B";

        if ($("#bttype").val() == "B")
        { // Het is een gebouw
          if (!$("#verdieping").hasClass("required"))
            $("#verdieping").addClass("required");
          if (!$("#ruimte").hasClass("required"))
            $("#ruimte").addClass("required");
        }
        else
        { // Het is een terrein
          $("#verdieping").removeClass("required");
          $("#ruimte").removeClass("required");
        }
      }

      function onChangeIsres()
      {
        if ($("#leen_res").is(":checked"))
            $("#lent_out_person_show").removeClass("required");
        if ($("#leen_vrij").is(":checked"))
            $("#lent_out_person_show").addClass("required");
      }

      $(function()
      {
        $("[name=isres]").change(onChangeIsres);
        onChangeIsres();
        onChangeGebouw();
      });

    </script>
  </head>

  <body>
<%
  PAGE_START({id: "ins-out-1-" + obj_key, dialog: true, "headerImage": (res_deel_image ? S("res_image_path") + "deel/" + res_deel_image : null) })
    HEADER({title: subject, back:!qrc, home: !qrc});
    CONTENT_START();
%>
    <form name="u2"
          action="<%=rooturl%>/appl/ins/ins_deel_free_save.asp"
          method="post"
          onsubmit="ins_submit();return false">
      <input type="hidden" name="adapt" id="adapt" value="<%=adapt? 1 : 0%>">
      <input type="hidden" name="lendout" id="lendout" value="<%=isLendOut? 0 : 1%>">
      <input type="hidden" name="takein" id="takein" value="<%=isLendOut? 1 : 0%>">
<%    if (hasreservering)
      {
        Response.Write("<tr><td colspan='2' class='label'>"
                     + "<div class='big_radio " + MOBILE_UI_CLASSES.checkbox_wrapper + "'>"
                     + "<input type='radio' name='isres' id='leen_res' class='" + MOBILE_UI_CLASSES.checkbox + "' value='" + res_rsv_deel_key + "' checked>"
                     + "<label class='" + MOBILE_UI_CLASSES.checkbox_label + "' for='leen_res'>" + safe.html(restxt) + "</label></div></td></tr>"
                      );
      }
      else
      {
        if (!isLendOut && restxt != "")
            Response.Write("<tr><td colspan='2'><div id='uitleen_restxt'>" + safe.html(restxt) + "</div></td></tr>");
      }

      if (isCil)
      {
        FCLTplaatsselector(authparams.ALGwritelevel,
                            { locatiekey: loc_key,
                              gebouwkey: alg_type == "G"? bld_key : ter_key,
                              verdiepingkey: flr_key,
                              ruimtekey: room_key,
                              suppressEmpty: true,
                              terrein: true,
                              eindlevel: 5,
                              requiredlevel: 5,
                              onGebChange: "onChangeGebouw();",
                              readonly: isLendOut
                            });
      }
      else
      {
        if (alg_ruimte_type == "C")
          FCLTcontactpersoonselector("lent_out_person",
                                      "sglent_out_person",
                                      { contactpersoonKey: (isLendOut? algprs_key : null),
                                        label: L("lcl_contact_pers"),
                                        extracode: "B",
                                        required: true,
                                        readonly: isLendOut
                                      });
        else
          if (!has_rsvdeel)
          FCLTpersoonselector("lent_out_person", // requestor
                                "sglent_out_person",
                              { perslidKey: (isLendOut? algprs_key : default_prs_key),
                                label: L("lcl_name"),
                                autlevel: authparams.PRSwritelevel,
                                required: true,
                                readonly: isLendOut
                                });
      }
%>
        <tr><td><input type="hidden" name="ins_keys" id="ins_keys" value="<%=obj_key%>"></td></tr>
<%

      generateFlexKenmerkBlock({ urole: "fo",
                                 ins_key: obj_key,
                                 srtdeelkey_array: sort_key > 0? [sort_key] : [],
                                 lendout: true,
                                 reado: false,
                                 mobile: true
                               });

      CONTROLGROUP_START();
       BUTTON(isLendOut? L("lcl_ins_insinn") : L("lcl_ins_lend_out"), {click: "ins_submit()", icon: isLendOut ? "fa-arrow-down" : "fa-arrow-up"});
       BUTTON(L("lcl_cancel"), {click: "ins_cancel()", icon: "fa-arrow-left"});
      CONTROLGROUP_END();
IFACE.FORM_END();
%>
    </form>
<%
    CONTENT_END();
    FOOTER();
  PAGE_END();
PDA_PAGE_END(); %>
	</body>
</html>
<% ASPPAGE_END(); %>
