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

    File:           job_edit_job.asp
    Description:    show detailed information of a job

    Parameters:     job_key

    Context:
    Note:

*/ %>
<!-- #include file="../Shared/common.inc"-->
<!-- #include file="../Shared/iface.inc"-->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!--#include file="./job.inc"-->

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

var job_key = getQParamInt("job_key");
var rtable = getQParamInt("rtable", -1);
var template = getQParamInt("template", 0);
var actiontxt = "";
var objfirstdate = new Date();
var objenddate = new Date();
var action = 2; // default for add mode
var status = 2; // default for add mode
var rkey = -1;
var isTemplate = (template == 1);
var person = user_key;

if (job_key > -1)
{
  var sql = "SELECT act.fac_activiteit_key"
          + "     , act.fac_activiteit_eenheid"
          + "     , act.fac_activiteit_bits"
          + "     , act.fac_activiteit_periode"
          + "     , act.fac_activiteit_aantal"
          + "     , act.prs_perslid_key"
          + "     , fac_activiteit_eerste"
          + "     , fac_activiteit_einddatum"
          + "     , act.fac_activiteit_status_key"
          + "     , act.fac_activiteit_aantal"
          + "     , DECODE(fac_activiteit_volgende, NULL, 0, 1) reado"
          + "     ," + S("prs_pers_string") + " naam"
          + "     , fac_activiteit_laatste"
          + "     , fac_activiteit_omschrijving"
          + "     , fac_activiteit_xmlnode"
          + "  FROM FAC_ACTIVITEIT act, prs_perslid p"
          + " WHERE act.prs_perslid_key = p.prs_perslid_key"
          + "   AND fac_activiteit_key = " + job_key;

  oRs = Oracle.Execute(sql);

  var this_job = job.func_enabled_job(job_key);
  user.auth_required_or_abort(this_job.canWrite);

  var eenheid   = oRs("fac_activiteit_eenheid").Value;
  var bits      = oRs("fac_activiteit_bits").Value;
  var periode   = oRs("fac_activiteit_periode").Value;
  var person    = oRs("prs_perslid_key").Value;
  var firstdate = oRs("fac_activiteit_eerste").Value;
  var enddate   = oRs("fac_activiteit_einddatum").Value;
  var status    = oRs("fac_activiteit_status_key").Value;
  var act_descr = oRs("fac_activiteit_omschrijving").Value;
  var aantal    = oRs("fac_activiteit_aantal").Value;
  var type      = oRs("fac_activiteit_xmlnode").Value;

  isTemplate = (eenheid == 5);
  switch (type)
  {
    case "bestelling": rtable = 1; break;
    case "melding":    rtable = (isTemplate ? 4 : 2); break;
    case "opdracht":   rtable = 3; break;
  }


  if (firstdate == null)
    var firstEmpty = "1";
  else
    objfirstdate = new Date(firstdate);

  if (enddate == null)
    var endEmpty = "1"
  else
    objenddate = new Date(enddate);

  var naam      = oRs("naam").Value;
  var lastdate  = oRs("fac_activiteit_laatste").Value;

  if (type == "bestelling")
  {
    sql2 = "SELECT bes_bestelling_key "
         + "  FROM bes_bestelling "
         + " WHERE fac_activiteit_key = "+ job_key;

    oRs2 = Oracle.Execute (sql2);
    if (!oRs2.eof)
      rkey = oRs2("bes_bestelling_key").Value;
    oRs2.Close();
  }

  if (type == "melding")
  {
    sql2 = "SELECT mld_melding_key "
         + "  FROM mld_melding "
         + " WHERE fac_activiteit_key = " + job_key;

    oRs2 = Oracle.Execute (sql2);
    if (!oRs2.eof)
      rkey = oRs2("mld_melding_key").Value;
    oRs2.Close();
  }

  if (type == "opdracht")
  {
    sql2 = "SELECT mld_opdr_key "
         + "  FROM mld_opdr "
         + " WHERE fac_activiteit_key = "+ job_key;

    oRs2 = Oracle.Execute (sql2);
    if (!oRs2.eof)
      rkey = oRs2("mld_opdr_key").Value;
    oRs2.Close();
  }

  // 1-malig
  if ((aantal == 1) && (firstdate != ""))
  {
    action = 1;
    actiontxt = L("lcl_job_action_1");
  }
  else
  { // Tot einddatum
    if (aantal == "" || aantal == null)
    {
      action = 2;
      actiontxt = L("lcl_job_action_2");
    }
    else
    {
      if (aantal != "" && aantal != null)
      { // Aantal keer
        action = 3;
        actiontxt = L("lcl_job_action_3");
      }
    }
  }
  oRs.Close();
}
else // if (job_key == -1)
{
  var job_info = job.func_enabled_job();
  user.auth_required_or_abort(job_info.canWriteAny);
}

%>

<html>
  <head>
<%
    FCLTHeader.Generate();
%>
  <script>
    async function job_submit()
    {
      document.activeElement.blur(); // trigger laatste onChanges
      if (!await validateForm("u2"))
        return false;

      if (checkInput()) {
        $.post($("form[name=u2]").attr("action"),
                $("[name=u2]").serialize(),
                FcltCallbackClose,
                "json");
      }
    }

    function job_cancel()
    {
      FcltMgr.closeDetail(window, { cancel: true });
    }

    function changeAction()
    {
      if (document.getElementById("action"))
      {
        if (document.getElementById("action").value == "1")
        { // Eenmalig.
          $("#moment_button").closest("tr").hide();
          $("#aantal").val("1");
          $("#enddate").val("");
          $("#unit").val(-1);
          $("#periode").val("");
          $("#bits").val("");

          $("#aantal").closest("tr").hide();
          $("#show_firstdate").removeAttr("disabled"); // TODO: knopje ook uit/in schakkelen gaat nu fout als er op wordt gedrukt.
          $("#show_enddate").closest("tr").hide();
          $("#unit").closest("tr").hide();
          $("#periode").closest("tr").hide();
          $("#moment_button").closest("tr").hide();
        }

        if (document.getElementById("action").value == "2")
        { // Tot einddatum.
          $("#aantal").removeAttr("disabled");
          $("#aantal").val("");

          $("#aantal").closest("tr").hide();
          $("#show_firstdate").removeAttr("disabled");
          $("#show_enddate").closest("tr").show();
          $("#unit").closest("tr").show();
          $("#periode").closest("tr").show();
          $("#moment_button").closest("tr").show();
        }

        if (document.getElementById("action").value == "3")
        { // Aantal keer.
          $("#show_enddate").val("");

          $("#aantal").closest("tr").show();
          $("#show_firstdate").removeAttr("disabled");
          $("#show_enddate").closest("tr").hide();
          $("#unit").closest("tr").show();
          $("#periode").closest("tr").show();
          $("#moment_button").closest("tr").show();
        }
        FcltMgr.resized(window);
      }
    };

    var changed_bits = 0;
    function checkInput()
    {
      var isTemplate = ("<%=isTemplate%>" == "True" ? true : false);
      var job_key = <%=job_key%>;

      if (!isTemplate || job_key > -1)
      {
        if (sgPerson.getValue()==-1)
        {
          FcltMgr.alert(L("lcl_job_requestor_empty"));
          return false;
        }
      }

      if (!isTemplate)
      {
        if (document.getElementById("show_firstdate").value == "")
        {
          FcltMgr.alert(L("lcl_job_firstdate_empty"));
          return false;
        }

        if ((document.getElementById("show_enddate").value == "") && (document.getElementById("action").value == "2"))
        {
          FcltMgr.alert(L("lcl_job_enddate_empty"));
          return false;
        }

        if (document.getElementById("unit"))
        {
          unit_value = document.getElementById("unit").value;
          if (unit_value < 0 && document.getElementById("action").value != "1")
          {
            FcltMgr.alert(L("lcl_job_unit_error"));
            return false;
          }
        }

        if (document.getElementById("periode"))
        {
          periode_value = document.getElementById("periode").value || 0;
          if (periode_value <= 0 && document.getElementById("action").value != "1")
          {
            FcltMgr.alert(L("lcl_job_period_error"));
            return false;
          }

          var lunit = $("#unit").val();
          var periode_value = $("#periode").val();
          if (lunit > 0 && (parseFloat(periode_value.replace(",", ".")) % 1) > 0)
          {
            FcltMgr.alert(L("ins_srtcontrole_period_int"));
            return false;
          }
        }

        if (document.getElementById("aantal"))
        {
          aantal_value = document.getElementById("aantal").value;
          if ((aantal_value != "") || (document.getElementById("action").value == "3"))
          {
            if (!isGoodInteger(aantal_value) || (aantal_value <= 0))
            {
              FcltMgr.alert(L("lcl_job_n_times_error"));
              return false;
            }
          }
        }

        // Is er een moment/Zijn er momenten geselecteerd?
        var ch_bits = (changed_bits == 1);
        if ($("#action").val() > 1 && !ch_bits)
        {
          FcltMgr.alert(L("ins_srtcontrole_select"));
          return false;
        }
      }
      return true;
    }

    function isGoodInteger(str)
    {
      var anum=/(^\d+$)/
      return anum.test(str);
    }

    function SelectBits()
    {
      if ($("#unit").val() < 0)
      {
        FcltMgr.alert(L("lcl_job_unit_error"));
        return false;
      }

      var proturl = "../ins/ins_bitsform.asp"
                  + "?eenheid=" + $("#unit").val()
                  + "&bits="    + $("#bits").val();
      parent.FcltMgr.openModalDetail(proturl, L("lcl_job_moment"),
                  { callback: function (data)
                          { if (data.eenheid >= 0)
                            {
                              $("#bits").val(data.bits);
                              changed_bits = 1;
                            }
                          }
                  } );
    }

    $(_ => {
      changeAction(); // Ook onload direct 1x uitvoeren
    });
  </script>
</head>

<body class="editmode">
<%
  SUBFRAME_START();
  var buttons =  [ {title: L("lcl_submit"), action:"job_submit()", icon: "fa-fclt-save" },
                   {title: L("lcl_cancel"), action:"job_cancel()", icon: "fa-fclt-cancel" }];

  IFRAMER_HEADER( (isTemplate ? L("lcl_job_frame_template") : L("lcl_job_frame_algemeen") ), buttons);
%>
<form name="u2"
      action="job_edit_job_save.asp?job_key=<%=job_key%>&rtable=<%=rtable%>"
      method="post"
      target="hidFrameSubmit"
      onSubmit="job_submit();">
<%
  BLOCK_START("job-info", (isTemplate ? L("lcl_template_algemeen") : L("lcl_job_algemeen")), { icon: "fa-briefcase" });
    if (job_key > -1)   {
      ROFIELDTR("fldshort", (isTemplate ? L("lcl_job_template_nr") : L("lcl_job_nr")), job_key);
    }
    RWFIELDTR("act_descr",  "fld",          L("lcl_descr"),        act_descr, { required: true, maxlength: 60});

    if (!isTemplate) {
      var statusSql = "       SELECT 1, " + safe.qL("lcl_job_stat_1_inactief") + " FROM DUAL"
                    + " UNION SELECT 2, " + safe.qL("lcl_job_stat_2_actief") + " FROM DUAL"
                    + " UNION SELECT 3, " + safe.qL("lcl_job_stat_3_1xoverslaan") + " FROM DUAL";
      FCLTselector("status",
                    statusSql,
                  { initKey: status,
                    label: L("lcl_job_status")
                  });
    }

    if (!isTemplate || job_key > -1)
    {
      FCLTpersoonselector(
                  "Person",
                  "sgPerson",
                { perslidKey: person,
                  label: L("lcl_requestor"),
                  fieldNameKey: "person",
                  required: true,
                  readonly: false
                });
    }
    else
    {
%>      <input type="hidden" id="Person" name="Person" value="<%=person%>"> <%
    }

    if (!isTemplate && job_key > -1)   {
      ROFIELDTR("fld", L("lcl_job_lastdate"), toDateTimeString(lastdate));
    }
  BLOCK_END();

if (isTemplate) {
%>
      <input type="hidden" id="status" name="status" value="2">
      <input type="hidden" id="template" name="template" value="1">
<%
} else {
  BLOCK_START("job-planning", L("lcl_job_planning"), { icon: "fa-calendar" });
    var actionSql = "       SELECT 1, " + safe.qL("lcl_job_action_1") + " FROM DUAL"
                  + " UNION SELECT 2, " + safe.qL("lcl_job_action_2") + " FROM DUAL"
                  + " UNION SELECT 3, " + safe.qL("lcl_job_action_3") + " FROM DUAL";
    FCLTselector("action",
                  actionSql,
                { initKey: action,
                  label: L("lcl_job_action"),
                  onChange: "changeAction();"
                });

    FCLTcalendar( "firstdate",
                { label : L("lcl_job_firstdate"),
                  datum : objfirstdate,
                  initEmpty: firstEmpty,
                  volgnr: 1
                });
    // Eenheid.
    // Uurlijks tot nu toe niet beschikbaar anders zou er nog veel in de code aangepast moeten worden.
    var sql = "       SELECT 1, " + safe.quoted_sql(L("lcl_ins_controle_dagelijks"))   + " FROM DUAL"
            + " UNION SELECT 2, " + safe.quoted_sql(L("lcl_ins_controle_wekelijks"))   + " FROM DUAL"
            + " UNION SELECT 3, " + safe.quoted_sql(L("lcl_ins_controle_maandelijks")) + " FROM DUAL"
            + " UNION SELECT 4, " + safe.quoted_sql(L("lcl_ins_controle_jaarlijks"))   + " FROM DUAL";
    FCLTselector("unit",
                sql,
                { initKey: eenheid,
                  label: L("lcl_job_unit"),
                  emptyOption: ""
                });
    // Periode.
    RWFIELDTR("periode", "fldshort", L("lcl_job_period"), periode, { datatype: "number" });
    // Bits.
    var rwparams = { datatype: "button",
                    html: "title='" + L("lcl_job_moment") + "' onclick='SelectBits()'",
                    endicon: "fa-hand-point-left"
                  }
    RWFIELDTR("moment_button", "button", L("lcl_job_moment"), L("lcl_select"), rwparams);
  %>
    <tr style="display:none"><td><input type="hidden" id="bits" name="bits" value="<%=bits%>"></td></tr>
  <%

    FCLTcalendar( "enddate",
                { label : L("lcl_job_enddate"),
                  datum : objenddate,
                  initEmpty: endEmpty,
                  volgnr: 2
                });

    RWFIELDTR("aantal",  "fldshort",          L("lcl_job_n_times"),        aantal, {maxlength: 10});
  BLOCK_END();
}
IFACE.FORM_END();
%>
</form>
<iframe src="../Shared/empty.html" name="hidFrameSubmit" style="display:none"></iframe>
<% SUBFRAME_END(); %>
</body>
</html>
<% ASPPAGE_END(); %>
