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

    File:               cnt/cnt_verlengschema.asp
    Description:        Voeg een reeks datums met verlengtermijn toe voor een specifiek contract.
    Parameters:        
    Context:            
*/
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../cnt/cnt.inc" -->
<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["../cnt/cnt_verlengschema.js", "date.js"]
                    })
var cnt_key = getQParamInt("cnt_key", -1);
var cnt_looptijd_tot = getQParamInt("einddatum", null);
var cnt_info = cnt.cnt_contract_info(cnt_key);
var this_cnt = cnt.func_enabled_contract(cnt_key, cnt_info); // Wat heb ik zoal aan rechten op dit contract?
user.auth_required_or_abort(this_cnt.canChange);
var einddatum = (cnt_looptijd_tot ? new Date(cnt_looptijd_tot) : cnt_info.looptijd_tot)

function itemListTable(ilt_id, ilt_sql, ilt_caption, ilt_params, ilt_columns)
{
  function itemListTableHeader(p_id, p_columns)
  {
    var v_html = "<tr>"
               + "<th width='15'>"
               + "<span title='" + L("lcl_del_allrows") + "' OnClick='cancelAllItems(\"" + p_id + "\")' class='default-clickable-icon'>" + I("fa-trash-alt") + "</span>"
               + "</th>";
    for (var i=0; i< p_columns.length; i++)
    {
      if (!p_columns[i].hidden) {
        v_html += "<th>"+ safe.html(p_columns[i].caption) + "</th>";
      }
    }
    v_html += "</tr>";
    return v_html;
  }
  function itemListTableRows(p_id, p_sql, p_columns)
  {
    var v_selected_items = [];
    var v_html = "";
    if (p_sql != "") {
      var sql = "SELECT COUNT(*) aantal FROM (" + p_sql + ")";
      var oRs = Oracle.Execute(sql);
      var v_rows = oRs("aantal").Value;
      oRs.Close();
      var oRs = Oracle.Execute(p_sql);
      var v_rowIndex = 1;
      while (!oRs.EOF)
      {
        v_html +="<tr>";
        // Create drop button
        v_hidden = (v_rowIndex < (v_rows) ? " class='hidden'" : "");
        v_html += "<td class='result' align='center'>"
                + "<span title='" + L("lcl_del_row") + "'" + v_hidden + " OnClick='cancelItem(\"" + p_id + "\", " + v_rowIndex + ")' class='default-clickable-icon'>" + I("fa-trash-alt") + "</span>"
                + "</td>";

        var v_row_data = [];
        for (var i=0; i<p_columns.length; i++)
        {
          var v_col = p_columns[i];
          var v_class = "result nowrap" + (v_col.hidden ? " hidden" : "");
          var v_val = "";
          var v_col_data = "";
          switch (v_col.typ)
          {
            case "date":  v_val = toDateString(oRs(v_col.content).Value);
                          v_col_data = new Date(oRs(v_col.content).Value).getTime();
                          break;
            default:  v_val = oRs(v_col.content).Value;
                      v_col_data = oRs(v_col.content).Value;
          }
          v_html += "<td class='" + v_class + "' align='left'>" + v_val + "</td>";
          v_row_data.push(v_col_data);
        }
        v_html += "</tr>";
        v_selected_items.push( {rowIndex: v_rowIndex, values: v_row_data});
        oRs.MoveNext();
        v_rowIndex++;
      }
      oRs.Close();
    }
    return {html: v_html, selected_items: v_selected_items};
  }

  var v_html = "";
  v_html += "<tr><td colspan='2'><div id='" + ilt_id + "'>";
  v_html += "<input type='hidden' id='" + ilt_id + "_data' name='" + ilt_id + "_data' value=''>"; // voor het opslaan van gegevens in de tabel.
  v_html += "<label>" + safe.html(ilt_caption) + "</label>";
  v_html += "<table id='" + ilt_id + "_table' cellspacing='0' cellpadding='0' width='100%'>";
  v_html += itemListTableHeader(ilt_id, ilt_columns);
  var v_row = itemListTableRows(ilt_id, ilt_sql, ilt_columns);
  v_html += v_row.html;
  v_html += "</table></div></td></tr>";
  Response.Write(v_html);
%>
<script>
  var s_itemlist_id = "<%=ilt_id%>";
  itemListTables[s_itemlist_id] = { params: <%=JSON.stringify(ilt_params)%>
                                  , columns: <%=JSON.stringify(ilt_columns)%>
                                  , selectedItems: <%=JSON.stringify(v_row.selected_items)%>
                                  };
</script>
<%
}
%>


<html>
  <head>
<%  FCLTHeader.Generate(); %>
    <script type="text/javascript">
      async function addToList()
      {
        if (!await validateForm("u2"))
          return false;        

        var schema = itemListTables["sel_items"].selectedItems;
        var startdatum = <%=new Date(einddatum).getTime()%>;
        if (schema.length > 0) {
          // startdatum van nieuwe regel is einddatum laatste regel (altijd achteraan toevoegen).
          startdatum = schema[schema.length - 1].values[2];
        }

        var url_params = "&startdatum=" + startdatum
                       + "&termijn_key=" + parseInt($("#cnt_prolong_period").val());
        $.getJSON( "./get_cnt_info_ajax.asp?req_info=termijndatum" + url_params
                 , function(data) {
                      var s_row = [ data.termijn_key
                                  , data.termijn_oms 
                                  , data.termijn_datum
                                  ];

                      addItem("sel_items", s_row);  // voeg nieuwe regel met prullenbak toe
                      setDropButtonHidden();        // verwijder prullenbak bij huidige regels
                    }
                 );
      }

      function setDropButtonHidden()
      { // Zet de prullenbak van de vorige regel hidden.
        $("#sel_items table tr:last").prev().find("td:first span").addClass("hidden");
      }

      function setDropButtonVisible()
      { // In cnt_verlengschema.js heeft de functie CancelItem() de laatste regel verwijderd.
        // Van de nieuwe laatste regel moet de prullenbak weer zichtbaar worden.
        $("#sel_items table tr:last td:first").find("span").removeClass("hidden");
      }

      function cntVerlengschemaSubmit()
      {
        var data = {termijnen: []};
        for (var i=0; i<itemListTables["sel_items"].selectedItems.length; i++)
        {
          data.termijnen.push(itemListTables["sel_items"].selectedItems[i].values[0]);
        }

        <% protectRequest.dataToken("data"); %>
        var url = "cnt_verlengschema_save.asp?cnt_key=<%=cnt_key%>";
        $.post( url
              , data
              , function(data) {
                    FcltMgr.closeDetail( window
                                       , { success: data.success
                                         , warning: data.message
                                         , rowcount: data.rowcount
                                         , termijn: data.termijn_key
                                         });
                }
              , "json"
              );
        return true;
      }

      function cntVerlengschemaClose()
      {
        FcltMgr.closeDetail(window, { cancel: true });
      }
    </script>
  </head>

  <body class="fclt-modal" id="mod_cntverlengschema">
<%  MODAL_START(); %>
    <form name="u2" method="post">
<%
      MODAL_BLOCK_START("verlengschema", L("lcl_cnt_prolongation_schedule"), { icon: "fa-paperclip" });

        ROFIELDTR ("fld", L("lcl_cnt_date_end"), toDateString(einddatum));

        sql_termijnen = "SELECT t.cnt_termijn_key"
                           + ", "+lcl.xsqla('t.cnt_termijn_omschrijving', 't.cnt_termijn_key')
                           + " FROM cnt_termijn t"
                           + " ORDER BY t.cnt_termijn_volgnummer";
        FCLTselector("cnt_prolong_period", sql_termijnen,
                     { label: L("lcl_cnt_prolongation_period"),
                       required: true,
                       emptyOption: ""
                     });
        var sql_verlengschema = "SELECT c.cnt_contract_key                 cnt_key"
                              + "     , c.cnt_verlengschema_volgnr         volgnr"
                              + "     , c.cnt_verlengschema_verlengtermijn periode_key"
                              + "     , t.cnt_termijn_omschrijving         periode_oms"
                              + "     , cnt.getVerlengschemaEinddatum(" + einddatum.toSQL() + ", " + cnt_key + ", c.cnt_verlengschema_volgnr) einddatum"
                              + "  FROM cnt_verlengschema c"
                              + "     , cnt_termijn t"
                              + " WHERE c.cnt_verlengschema_verlengtermijn = t.cnt_termijn_key"
                              + "   AND c.cnt_contract_key = " + cnt_key
                              + " ORDER BY 2";

        itemListTable( "sel_items"
                     , sql_verlengschema
                     , L("lcl_cnt_prolongation_schedule") 
                     , { maxrows: 99
                       , onDeleteItem: "setDropButtonVisible"
                       , sort: "einddatum"
                       } 
                     , [ { caption: "", content: "periode_key", required: true, hidden: true }
                       , { caption: L("lcl_cnt_prolongation_period"), content: "periode_oms", required: true }
                       , { caption: L("lcl_cnt_prolongation_end"), content: "einddatum", required: true, unique: true, typ: "date" }
                       ]
                     );

      MODAL_BLOCK_END();
      IFACE.FORM_END();
%>
    </form>
<%
      SIMPLE_BLOCK_START();
        CreateButtons([ { title: L("lcl_add_to_list"), action: "addToList()", icon: "fa-plus" }
                      , { title: L("lcl_submit"), action: "cntVerlengschemaSubmit()", icon: "fa-fclt-save", importance: 1}
                      , { title: L("lcl_cancel"), action: "cntVerlengschemaClose()",  icon: "fa-fclt-cancel", importance: 3}
                      ]);
      SIMPLE_BLOCK_END();
    MODAL_END();
%>
  </body>
</html>
<%ASPPAGE_END(); %>
