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

    File:               bes_opdr.asp
    Description:        Edit voor bestellingen-opdrachten
    Parameters:
                        urole
                        opdr_key
    Context:
    Note:
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../shared/save2db.inc" -->
<!-- #include file="bes.inc" -->

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

var urole = getQParamSafe("urole");
var minfo = (urole == "mi");
var opdr_key = getQParamInt("opdr_key");

var bes_bestelopdr = bes.bestelopdracht_info(opdr_key); // Globale variabele met alle bes_bestelopdr informatie
var bes_bestelling = bes.bestelling_info(bes_bestelopdr.bes_key_str[0]);
var this_bestelopdr = bes.func_enabled_bestelopdracht(opdr_key);
%>

<html>
  <head>
<%  FCLTHeader.Generate(); %>
  </head>
<%

  var authparams = user.checkAutorisation("WEB_BESBOF");
  user.auth_required_or_abort(this_bestelopdr.canChange);

  var submitting = getQParamInt("submit", 0) == 1;
  if (submitting)
  {
    protectRequest.validateToken();

    var fields =  [ { dbs: "bes_bestelopdr_opmerking", typ: "varchar", frm: "opmerk",   track: L("lcl_remark"), len: 320 },
                    { dbs: "mld_adres_key_lev",        typ: "key",     frm: "levering", track: L("lcl_bes_adres_lev"), foreign: "MLD_V_AFLEVERADRES" } ,
                    { dbs: "mld_adres_key_fac",        typ: "key",     frm: "factuur",  track: L("lcl_bes_adres_fac"), foreign: "MLD_V_FACTUURADRES" }
                  ];
    if (getFParam("chkproceed", "off") == "on")
        fields.push({ dbs: "bes_bestelopdr_status", typ: "key", val: 3});
    var besOpdrUpd = buildTrackingUpdate("bes_bestelopdr", " bes_bestelopdr_key = " + opdr_key, fields);

    itemregels = getFParamInt("itemregels");
    var besopdr_id = "";
    for (i = 1; i <= itemregels; i++)
    {
      cnt  = getFParamInt('cnt' + i);
      ikey = getFParamInt('ikey' + i);
      // TODO: Moet (desnoods) prijs niet overgenomen uit bes_bestelling_item_prijs?
      sql = "UPDATE bes_bestelopdr_item"
          + "  SET bes_bestelopdr_item_aantal = " + cnt
          + ",     bes_bestelopdr_item_prijs = "
          + "           (SELECT bes.getsrtdeelprijs(bes_srtdeel_key, NULL)"
          + "              FROM bes_bestelling_item WHERE "
          + "               bes_bestelopdr_item_key = " + ikey + ")"
          + " WHERE bes_bestelopdr_item_key = " + ikey;

      Oracle.Execute(sql);

      if (bes_bestelopdr.artikel_arr[i-1].aantal > cnt)
      {
        sql = "SELECT boi.bes_bestelopdr_item_omschrijv"
            + "     , bo.bes_bestelopdr_id"
            + "  FROM bes_bestelopdr_item boi"
            + "     , bes_bestelopdr bo"
            + " WHERE boi.bes_bestelopdr_key = bo.bes_bestelopdr_key"
            + "   AND bes_bestelopdr_item_key = " + ikey;
        oRs = Oracle.Execute(sql);
        var item_oms = oRs("bes_bestelopdr_item_omschrijv").Value;
        besopdr_id = oRs("bes_bestelopdr_id").Value;
        besOpdrUpd.trackarray.push(L("lcl_bes_amount") + ": " + buildTrackText("float", bes_bestelopdr.artikel_arr[i-1].aantal, cnt) + " (" + item_oms + ")");
      }
    }

    Oracle.Execute(besOpdrUpd.sql);

    // Als de status 4 (In bestelling (bevestigd)) is zou het zo kunnen zijn dat nu (na deze wijziging) alles geleverd is.
    if (bes_bestelopdr.status == 4)
    { // Laat de gevolgen bepalen..
      bes.updatebestelopdrstatus(opdr_key);
      bes.updatebestellingstatus(bes_bestelling.bes_key);
    }

    // Update nog tracken
    shared.trackaction("BES2UP",
                       opdr_key,
                       L("lcl_bes_is_bes2uptrack").format(S("bes_bestelopdr_prefix") + besopdr_id) + "\n" + besOpdrUpd.trackarray.join("\n"));



%>  <script type="text/javascript">
      FcltMgr.closeDetail(window, { warning: null } );
    </script>
<%  Response.End;
  }
%>
  <script type="text/javascript">
    function bes_opdrsubmit()
    { //TODO CheckLengte
      document.forms.u2.submit();
      return true;
    }

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

     jQuery(document).ready(function()
                             {
                               $('textarea').resize(function() { FcltMgr.resized(window) });
                               $('textarea').autogrow();
                             });

  </script>
  <body id="editbody">
<%
    var buttons =  [ {title: L("lcl_submit"), icon: "opslaan.png", action: "bes_opdrsubmit()" },
                     {title: L("lcl_cancel"), icon: "undo.png", action: "bes_opdrcancel()" }];

    IFRAMER_HEADER(L("lcl_bes_opdrframe_algemeen"), buttons)

%>
    <div id="edit">
    <script type="text/javascript">
      function recalcPrice(key)
      {
        var m_count = parseInt(document.u2['cnt' + key].value);
        if (isNaN(m_count)) {
            document.u2['cnt'+key].value = document.u2['am' + key].value;
            return;
        }

        // Het aantal moet groter of gelijk blijven aan het aantal geleverd.
        // Trouwens alleen als de status 4 is of daarna kunnen er artikelen geleverd zijn.
        var m_count_ontv = parseInt(document.u2['cnt'+key].getAttribute("aantalontv"));
        if (m_count < m_count_ontv)
        {
          alert(L("lcl_bes_aantontv_mess").format(m_count_ontv));
          document.u2['cnt'+key].value = m_count_ontv;
          document.u2['cnt'+key].focus()
          m_count = m_count_ontv;
        }

        // Aantal kan niet verhoogd worden.
        var m_count_max = parseInt(document.u2['max' + key].value);
        if (m_count > m_count_max)
        {
          alert(L("lcl_bes_verhogen_mess"));
          document.u2['cnt'+key].value = m_count_max;
          document.u2['cnt'+key].focus()
          m_count = m_count_max;
        }
        var price = parseFloat(document.u2['pr'+key].value);
        var c_count = m_count * price;
        $('#price' + key).text(num2curr(c_count));

        var amount = document.u2['am' + key].value;
        document.u2['am' + key].value = m_count;

        var o_count = amount * price;
        document.u2.total.value = parseFloat(document.u2.total.value) - o_count + c_count;
        document.u2.total_txt.value = num2curr(parseFloat(document.u2.total.value));
      }
    </script>

    <form action="bes_edit_opdr.asp?submit=1&urole=<%=urole%>&opdr_key=<%=opdr_key%>" method=post name=u2 >
<%    BLOCK_START("besOpdr", L("lcl_bes_opdralgemeengegevens"));

        ROFIELDTR("fld", L("lcl_bes_RFOs"), S("bes_bestelling_prefix") + bes_bestelopdr.bes_key_str.join(", "));
        if (bes_bestelopdr.bes_key_str.length == 1)
        {
          // Originele aanvraag weergeven indien aanwezig
          if (bes_bestelling.parent_key)
            ROFIELDTR ("fld", L("lcl_bes_origineel"), S("bes_bestelling_prefix") + bes_bestelling.parent_key);
        }
        ROFIELDTR("fld", L("lcl_bes_Supplier"), bes_bestelopdr.prs_bedrijf_naam);
        ROFIELDTR("fld", L("lcl_bes_Bes_status"), bes_bestelopdr.statustxt);
        ROFIELDTR("fld", L("lcl_bes_Bes_Owner"), bes_bestelopdr.prs_perslid_naam);

        if (bes_bestelopdr.status == 1)
        { %>
          <tr><td></td><td>
               <input type="checkbox" name="chkproceed" id="chkproceed" value="on" CHECKED><label for="chkproceed"><%=L("lcl_bes_submit_proceed")%></label>
          </td>
          </tr>
<%      }

        sql = "SELECT aa.mld_adres_key"
            + "     , aa.mld_adres_naam"
            + "  FROM mld_v_aanwezigadres aa"
            + " WHERE aa.mld_adres_afleveradres IS NOT NULL"
            + (authparams.ALGreadlevel >= 0
              ? " AND (EXISTS (SELECT ml.alg_locatie_key"
              + "               FROM fac_v_my_locations ml"
                + "            WHERE ml.prs_perslid_key = " + user_key
                + "              AND ml.niveau = " + authparams.ALGreadlevel
                + "              AND ml.alg_locatie_key = aa.alg_locatie_key)"
                + " OR aa.alg_locatie_key IS NULL"
                + " OR aa.mld_adres_key = " + bes_bestelopdr.mld_adres_key_lev + ")"
              : "")
            + " ORDER BY 2";
        FCLTselector("levering", sql, {label: L("lcl_bes_adres_lev"),
                                       initKey: bes_bestelopdr.mld_adres_key_lev,
                                       emptyOption: (bes_bestelopdr.mld_adres_key_lev < 0? null : "")})

        sql = "SELECT fa.mld_adres_key"
            + "     , fa.mld_adres_naam"
            + "  FROM mld_v_factuuradres fa"
            + (authparams.ALGreadlevel >= 0
              ? " WHERE (EXISTS (SELECT ml.alg_locatie_key"
              + "                 FROM fac_v_my_locations ml"
                + "              WHERE ml.prs_perslid_key = " + user_key
                + "                AND ml.niveau = " + authparams.ALGreadlevel
                + "                AND ml.alg_locatie_key = fa.alg_locatie_key)"
                + "  OR fa.alg_locatie_key IS NULL"
                + "  OR fa.mld_adres_key = " + bes_bestelopdr.mld_adres_key_fac + ")"
              : "")
            + " ORDER BY 2";
        FCLTselector("factuur", sql, {label: L("lcl_bes_adres_fac"),
                                     initKey: bes_bestelopdr.mld_adres_key_fac,
                                     emptyOption:(bes_bestelopdr.mld_adres_key_fac < 0? null : "")})
        RWTEXTAREATR("opmerk", "fldtxt", L("lcl_remark"), bes_bestelopdr.opmerking, {html: "rows='3'", suppressEmpty: true}); // Afhandeling, reden niet akkoord
        ROTEXTAREATR("fldtxt", L("lcl_bes_comment"), bes_bestelopdr.delivery_opmerk, {suppressEmpty: true});
        BLOCK_END();

        BLOCK_START("besOpdrItems", L("lcl_bes_geselecteerd"));
%>
        <tr>
            <th><%=L("lcl_bes_srtdeel_nr")%></th>
            <th><%=L("lcl_bes_discipline")%></th>
            <th><%=L("lcl_bes_srtdeel")%></th>
            <th style="text-align:right"><%=L("lcl_bes_amount")%></th>
            <th style="text-align:right"><%=L("lcl_bes_Price") + " " + (bes_bestelopdr.inclBTW? L("lcl_shared_inclBTW") : L("lcl_shared_exclBTW"))%></th>
        </tr>
<%

        for (var i = 0; i < bes_bestelopdr.artikel_arr.length; i++)
        { %>
          <tr>
              <td><%=safe.html(bes_bestelopdr.artikel_arr[i].artikelnr)%></td>
              <td><%=safe.html(bes_bestelopdr.artikel_arr[i].catalogus_omschr)%></td>
              <td><%=safe.html(bes_bestelopdr.artikel_arr[i].omschr)%></td>
              <td align="right">
                  <input type="text" maxlength=5 style="width:100%;text-align:right" onBlur="recalcPrice(<%=i+1%>);"
                   id="cnt<%=i+1%>" class="fld_dlvrnr" name="cnt<%=i+1%>" value="<%=bes_bestelopdr.artikel_arr[i].aantal%>"
                   aantalontv="<%=bes_bestelopdr.artikel_arr[i].aantalontv%>">
                  <input type='hidden' id='am<%=i+1%>' name='am<%=i+1%>' value='<%=bes_bestelopdr.artikel_arr[i].aantal%>'>
                  <input type='hidden' id='max<%=i+1%>' name='max<%=i+1%>' value='<%=bes_bestelopdr.artikel_arr[i].aantal%>'>
                  <input type='hidden' id='pr<%=i+1%>' name='pr<%=i+1%>' value='<%=safe.jsfloat(bes_bestelopdr.artikel_arr[i].item_prijs)%>'>
                  <input type='hidden' id='ikey<%=i+1%>' name='ikey<%=i+1%>' value='<%=bes_bestelopdr.artikel_arr[i].item_key%>'>
              </td>
              <td id="price<%=i+1%>" align=right><%=safe.curr(bes_bestelopdr.artikel_arr[i].prijs)%></td>
          </tr>
<%      }
        var total = bes_bestelopdr.totaal - bes_bestelopdr.korting + bes_bestelopdr.levkosten;
%>

<%      if (bes_bestelopdr.korting > 0)
        { %>
          <tr>
              <td colspan=4><b><%=L("lcl_bes_order_discount")%></b></td>
              <td align="right">
              <input type="text" style="text-align:right" readonly class='disabled' value='<%=safe.curr(bes_bestelopdr.korting * -1)%>'>
              </td>
          </tr>
<%      } %>

<%      if (bes_bestelopdr.levkosten > 0)
        { %>
          <tr>
              <td align=left colspan=4><b><%=L("lcl_bes_tpcosts")%></b></td>
              <td align="right">
              <input type="text" style="text-align:right" readonly class='disabled'
              value='<%=safe.curr(bes_bestelopdr.levkosten)%>'>
              </td>
          </tr>
<%      } %>

        <tr>
            <td align=left colspan=4><label><%=L("lcl_total")%></label></td>
            <td align=right>
                <input type="text" style="text-align:right" readonly class='disabled' id='total_txt' name='total_txt'
                       value='<%=safe.curr(total)%>'>
            </td>
        </tr>
<%
        BLOCK_END();
%>
        <input type='hidden' id='itemregels' name='itemregels' value='<%=bes_bestelopdr.artikel_arr.length%>'>
        <input type='hidden' id='total' name='total' value='<%=safe.jsfloat(total)%>'>
<% IFACE.FORM_END(); %>
      </form>
    </div>
  </body>
</html>
