<%@ LANGUAGE="JavaScript" %>
<% /*
     $Revision$
     $Id$

     File:               cnt_edit_contract.asp
     Description:        Toevoegen of bewerken van een contract
     Parameters:         cnt_key              Contract key
     Context:
     Note:

*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="cnt_flexkenmerk.inc" -->
<!-- #include file="cnt.inc" -->
<!-- #include file="../Shared/calendar.inc"-->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/kostenplaatsselector.inc" -->
<!-- #include file="../Shared/kostensoortselector.inc" -->
<!-- #include file="../Shared/bedrijfselector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/afdelingselector.inc" -->
<!-- #include file="../Shared/contactpersoonselector.inc" -->

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

var cnt_key = getQParamInt("cnt_key");
var l_cnt_srt = getQParamInt("srtdisc", -1);

if (cnt_key > -1)
{
  var cnt_info = cnt.cnt_contract_info(cnt_key); // nog heel beperkt
  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);

  if (!cnt_info.locked_user_key || cnt_info.locked_user_key == user_key)
  {
    cnt.lock(cnt_key);
    cnt_info.locked_user_key = user_key;
  }
}
else // nieuw contract
{
  if (S("cnt_contract_approval") == 1)
  { // Als het approval mechanisme actief is mag ik met WEB_CNTUSE rechten ook een contract aanmaken.
    var autfunction = ["WEB_CNTUSE", "WEB_CNTMAN"];
    var authparams = user.checkAutorisation(autfunction);
  }
  else
  {
    var autfunction = "WEB_CNTMAN";
    var authparams = user.checkAutorisation(autfunction);
  }


  var sql = "SELECT dp.cnt_srtcontract_type,"
          + lcl.xsqla('cs.ins_discipline_omschrijving','cs.ins_discipline_key')
          +",      (SELECT prs_kostensoort_oms || '-' || " + lcl.xsqla('prs_kostensoort_opmerking', 'prs_kostensoort_key')
          + "         FROM prs_kostensoort"
          + "        WHERE prs_kostensoort_key = cs.prs_kostensoort_key) kostensoort_naam"
          + " FROM cnt_disc_params dp,"
          + "      cnt_discipline cs"
          + " WHERE dp.cnt_ins_discipline_key = " + l_cnt_srt
          + "   AND cs.ins_discipline_key =  " + l_cnt_srt;
  var oRs = Oracle.Execute( sql );

  var authparamsUSE = user.checkAutorisation("WEB_CNTUSE", true) || {PRSreadlevel: 9, PRSwritelevel: 9};

  var this_cnt = {canChangeKosten: true,
                  canChangeAlg: true,
                  isAbonnement: false,
                  // Volgende4 worden voor de flex gebruikt
                  canMANread  : authparams.PRSreadlevel < 9,
                  canUSEread  : authparamsUSE.PRSreadlevel < 9,
                  canMANwrite : authparams.PRSwritelevel < 9,
                  canUSEwrite : authparamsUSE.PRSwritelevel < 9 };

  var cnt_info = {contract_status: S("cnt_contract_approval") == 1? 2 : 0,
                  srtcontract_type: oRs("cnt_srtcontract_type").value,
                  discipline_omschrijving: oRs("ins_discipline_omschrijving").value,
                  discipline_key: l_cnt_srt,
                  kostensoort_naam: oRs("kostensoort_naam").Value};
  oRs.close();
}
%>
<html>
  <head>
<%  FCLTHeader.Generate() %>
    <script type="text/javascript">
      jQuery(document).ready(function()
                             {
                               $('textarea').autogrow();
                               FcltMgr.resized(window)
                             });


      function cnt_submit()
      {
          document.activeElement.blur(); // trigger laatste onChanges
          if (!validateForm("u2"))
              return false;
          document.forms.u2.submit();
      }

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

      // Meestal unlocken we gewoon in showmode die er achteraan komt
      // maar soms wordt het tabblad daarvoor al gesloten. Dan komen
      // we hier langs.
      function onCloseHot()
      {
         var data = { cnt_key: <%=cnt_key%> };
          <% protectRequest.dataToken("data"); %>
          jQuery.ajaxSetup({async: false}); // Anders faalt o.a. bij IE9 de $.post bij afsluiten
          $.post("cnt_unlock.asp",
                 data,
                 FcltCallback,
                 "json");
      }
    </script>

  </head>
  <body id="editbody">
<%
    var buttons = [];
    if (!cnt_info.locked_user_key || cnt_info.locked_user_key == user_key)
      buttons.push({title: L("lcl_submit"), action:"cnt_submit()", icon: "opslaan.png"});
    buttons.push({title: L("lcl_cancel"), action:"cnt_cancel()", icon: "undo.png" });

    IFRAMER_HEADER(L("lcl_cnt_frame_algemeen"), buttons);
      if (cnt_info.locked_user_key && cnt_info.locked_user_key != user_key)
      {
        var other = new Perslid(cnt_info.locked_user_key);
%>
        <script type="text/javascript">
          jQuery(document).ready(function()
                                 {
                                   FcltMgr.closeDetail(window, {cancel: true});
                                 });
        </script>
<%      Response.End;
      }
      if (cnt_info.contract_status == 1)
      {
%>      <div class="cnt_inactive"><%=L("lcl_cnt_is_inactive")%></div><%
      }
%>
    <script type="text/javascript">
      function checkTextarea(field, show, klen)
      {
          var valid = true;
          var value = field.value;
          var err = L("lcl_cnt_text_toolong1")+klen+ L("lcl_cnt_text_toolong2");
          if( value != '' ) {
            if( value.length > klen ) valid = false;
          }
          if( show && ! valid ) {
            alert(err);
            field.focus();
          }
          return valid;
      }
    </script>
    <div id="edit">
      <form name="u2"
            action="cnt_edit_contract_save.asp?cnt_key=<%=cnt_key%>&srtdisc=<%=cnt_info.discipline_key%>"
            method="post"
            target="hidFrameSubmit"
            onSubmit="cnt_submit();">
<%
        BLOCK_START("cntInfo", L("lcl_cnt_general_info"));
        // Het interne contractnr is automatisch&readonly indien S("cnt_internalnr_readonly")
        RWFIELDTR("cnt_cntnrint",  "fld",           L("lcl_cnt_intern_nr"),  cnt_info.nummer_intern, {maxlength: 30, readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg ||S("cnt_internalnr_readonly"), suppressEmpty: true});
        ROFIELDTR ("fldshort",                      L("lcl_cnt_versie"),     cnt_info.versie, {suppressEmpty: true, readonly: !this_cnt.canChangeAlg});
        //  CONN#16529/CONN#17562: versienummer wordt via splitsing bepaald, is niet te editen.
        ROFIELDTR("fld",                            L("lcl_cnt_srttype"),    cnt_info.discipline_omschrijving, {readonly: !this_cnt.canChangeAlg});
        RWFIELDTR("cnt_cntomst",  "fld",            L("lcl_cnt_descr"),      cnt_info.omschrijving, {required: true, maxlength: 50, readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg});
        RWFIELDTR("cnt_cntnr",  "fld",              L("lcl_cnt_contractnr"), cnt_info.nummer, {maxlength: 30, readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg});
        // Mantel contracten mogen niet zelf onder een ander contract vallen.
        // Bij mantel contracten selectbox met mantel contracten niet tonen.
        if (cnt_info.srtcontract_type != 6)
        { // Geen Mantel/Master contract. Dan kan selectbox getoond worden.
          sql_mantels   = "SELECT cnt_contract_key"
                        + "     , cnt_contract_nummer_intern || '-' || cnt_contract_omschrijving"
                        + "  FROM cnt_v_aanwezigcontract c"
                        + "     , cnt_disc_params dp"
                        + "     , cnt_discipline d"
                        + " WHERE dp.cnt_srtcontract_type=6 "  // mastercontracts
                        + "   AND c.ins_discipline_key = dp.cnt_ins_discipline_key"
                        + "   AND d.ins_discipline_key = dp.cnt_ins_discipline_key"
                        + "   AND d.ins_discipline_verwijder IS NULL"
                        + "   AND d.ins_discipline_key IN"
                        + " (SELECT ins_discipline_key"
                        + "    FROM fac_v_webgebruiker g"
                        + "       , fac_functie f"
                        + "   WHERE g.fac_functie_key = f.fac_functie_key"
                        + "     AND f.fac_functie_code = 'WEB_CNTMAN'"
                        + "     AND (g.fac_gebruiker_alg_level_read < 9 AND g.fac_gebruiker_prs_level_read < 9)" // prs en alg read rechten
                        + "     AND g.prs_perslid_key = " + user_key + ")"
                        + " ORDER BY 2";

          FCLTselector("cnt_macntkey", sql_mantels,
                           { label: L("lcl_cnt_mantel"),
                             initKey: cnt_info.mantel_key,
                             emptyOption: "",
                             readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg,
                             suppressEmpty: true
                          });
        }
        RWTEXTAREATR("cnt_cntdoc", "fldtxt", L("lcl_cnt_document"), cnt_info.document, {readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg});
        FCLTafdelingselector("cnt_owner",
                             "cnt_owner",
                            { departmentKey: cnt_info.afdeling_key_eig,
                              autlevel: authparams && authparams.PRSwritelevel,
                              label: L("lcl_cnt_owner"),
                              required: true,
                              readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                            });
        FCLTpersoonselector("cnt_owner_prs", // requestor
                            "sgCnt_owner_prs",
                           { perslidKey: cnt_info.perslid_key_eig,
                             /* bewust geen afhankelijkheid van cnt_owner meer */
                             /* bewust geen filtercode,wat maakt ons het uit? */
                             autlevel: authparams && authparams.PRSwritelevel,
                             label: L("lcl_cnt_contact_eig"),
                             required: S("cnt_contract_requestor_required"),
                             moreinfo: false,  /* PF: omdat de showmode die heeft, en het label erg lang is*/
                             readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                          });
        FCLTpersoonselector("cnt_manager", // beheerder
                            "sgcnt_manager",
                           { perslidKey: cnt_info.perslid_key_beh,
                             autlevel: authparams && authparams.PRSwritelevel,
                             label: L("lcl_cnt_manager"),
                             filtercode: "CNTB",
                             required: true,
                             readonly: (cnt_key > -1 && !this_cnt.canMANwrite) || !this_cnt.canChangeAlg,
                             moreinfo: false  /* PF: omdat de showmode die heeft, en het label erg lang is*/
                          });

        var cntopm_ro = (cnt_info.isAbonnement ? !this_cnt.canVerlengen : cnt_info.isAbonnement); // zelfde voorwaarde als het veld Verlengen.
        RWTEXTAREATR("cnt_cntopm", "fldtxt", L("lcl_remark"), cnt_info.opmerking, {html: "onChange='checkTextarea(this, false, 4000)'", readonly: cntopm_ro, suppressEmpty: true});
        BLOCK_END();

        BLOCK_START("cntData" , L("lcl_cnt_dates"));
        var params = { infoPointer: { Url: "appl/shared/status_info.asp?cnt_key=" + cnt_key + "&urole=bo",
                                      Title: L("lcl_status_details") + " " + cnt_info.nummer_intern
                                    }
                     }
        ROFIELDTR("fld", L("lcl_cnt_status"), cnt_info.contract_status_str, params);
        FCLTcalendar( "flddatevan",
                    { label  : L("lcl_cnt_date_start"),
                      datum  : cnt_info.looptijd_van,
                      volgnr: 1,
                      required: true,
                      readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                    });
        FCLTcalendar( "flddatetot",
                    { label  : L("lcl_cnt_date_end"),
                      datum  : cnt_info.looptijd_tot,
                      volgnr: 2,
                      required: true,
                      readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                    });
        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_cancel_period", sql_termijnen,
                       { label: L("lcl_cnt_cancel_period"),
                         initKey: cnt_info.opzegtermijn,
                         required: true,
                         emptyOption: "",
                         readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                      });
        FCLTselector("cnt_rappel_period", sql_termijnen,
                       { label: L("lcl_cnt_rappel_period"),
                         initKey: cnt_info.rappeltermijn,
                         required: true,
                         emptyOption: "",
                         readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                      });
        // Heb ik rechten om verlengen aan te passen. Alleen bij bestaande contracten
        if (cnt_key > -1 && cnt_info.isAbonnement)
        { // Het is een abonnement contract
          sql_verlengen = "SELECT -1,' " + L("lcl_unknown") + "', 1 FROM DUAL"
                        + " UNION SELECT " + (cnt_info.verlenging > 1? "3" : "1") + ", " + safe.qL("lcl_Yes") + ", 2 FROM DUAL"
                        + " UNION SELECT " + (cnt_info.verlenging > 1? "2" : "0") + ", " + safe.qL("lcl_No") + ", 3 FROM DUAL"
                        + " ORDER BY 3";
          FCLTselector("cntverlengen", sql_verlengen,
                        { label: L("lcl_cnt_verlengen"),
                          initKey: cnt_info.verlenging,
                          readonly: !this_cnt.canVerlengen // Als (cnt_verlenging > 1) dan is canVerlengen false.
                       });
        }
        BLOCK_END();

        BLOCK_START("cntBedrijf" , L("lcl_cnt_effecter"));

        if (cnt_info.srtcontract_type == S("cnt_srttype_rental"))
        { // Huur/Rental contracttype.
          // Één van de drie, persoon, bedrijf of afdeling, is verplicht maar niet meerdere. Dat dwingt een trigger wel af.
          FCLTbedrijfselector("cnt_bdrkey",
                              "sgCompany",
                              { companyKey: cnt_info.bedrijf_key,
                                label: L("lcl_cnt_mutatie_huurder"),
                                filtercode: "H",
                                moreinfo: true,
                                required: false,
                                emptyOption: "",
                                onChange: "onChangeCompany",
                                readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                              });
          FCLTafdelingselector("cnt_afdkey",
                               "sgDepartment",
                              { departmentKey: cnt_info.afdeling_key,
                                label: L("lcl_cnt_afdeling"),
                                required: false,
                                onChange: "onChangeDepartment",
                                readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                              });
        }
        else
        { // Algemeen/Generic, Leverancier/Supplier, Mantel/Master, Onderhoud/maintenance of Ondersteuning/Support contracttype
          // Één van de twee, persoon of bedrijf, is verplicht maar niet beide. Dat dwingt een trigger wel af.
          FCLTbedrijfselector("cnt_bdrkey",
                              "sgCompany",
                              { companyKey: cnt_info.bedrijf_key,
                                label: L("lcl_cnt_company"),
                                filtercode: "K",
                                moreinfo: true,
                                required: false,
                                emptyOption: "",
                                onChange: "onChangeCompany",
                                readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                              });

          FCLTcontactpersoonselector("cnt_contprs",
                                      "sgCntPersUitv",
                                      { contactpersoonKey: cnt_info.contactpersoon_key,
                                        label: L("lcl_cnt_contact_prs"),
                                        urlAdd: [{urlParam: "uitv_key", field: "cnt_bdrkey"}],
                                        moreinfo: true,
                                        readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg,
                                        suppressEmpty: true
                                      });

          sql_dienst = "SELECT prs_dienst_key"
                       + ", " + lcl.xsqla('prs_dienst_omschrijving', 'prs_dienst_key')
                       + " FROM prs_dienst"
                       + " ORDER BY UPPER("+lcl.xsql('prs_dienst_omschrijving', 'prs_dienst_key')+")"
          FCLTselector("dienst",
                       sql_dienst,
                       { initKey: cnt_info.prs_dienst_key,
                         label: L("lcl_prs_companies_dienst"),
                         emptyOption: "",
                         readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg,
                         suppressEmpty: true
                       });
        }

        // PF: wil hier ook nog een srtcontract_type-afhankelijke conditie voor
          FCLTpersoonselector("cnt_prskey", // requestor
                              "sgPerson",
                             { perslidKey: cnt_info.perslid_key,
                               /* bewust geen afhankelijkheid van cnt_owner meer */
                               /* bewust geen filtercode, wat maakt ons het uit? */
                               autlevel: authparams && authparams.PRSwritelevel,
                               label: L("lcl_person"),
                               required: false,
                               moreinfo: true,
                               emptyOption: "",
                               onChange: "onChangePerson",
                               readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg,
                               suppressEmpty: true
                             });
        BLOCK_END();

        BLOCK_START("cntFindata" , L("lcl_cnt_fin_data"));
        FCLTkostenplaatsselector("prs_kstplkey",
                                 "prs_kstplkey",
                                 user_key,
                                 {label: L("lcl_cnt_kostenplaats"),
                                  kostenplaatsKey: cnt_info.prs_kostenplaats_key,
                                  required: true,
                                  filtercode: (S("cnt_all_kostenplaats") == 1? "A" : null),
                                  readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg
                                 });

        if (cnt_info.isAbonnement || !this_cnt.canChangeAlg)
            ROFIELDTR ("fldkp", L("lcl_cnt_kostensoort"), cnt_info.kostensoort_naam, {suppressEmpty: true});
        else
        {
            ROFIELDTR ("fldkp", L("lcl_cnt_kostensoort_standaard"), cnt_info.kostensoort_naam, {suppressEmpty: true});
            if (S("cnt_enable_kostensoort") != 0)
                FCLTkostensoortselector("prs_kstsrtkey",
                                        "prs_kstsrtkey",
                                        { kostensoortKey: cnt_info.prs_kostensoort_key,
                                          label: L("lcl_cnt_kostensoort_specifiek")
                                        });
        }

        RWFIELDTR("cnt_termkstn", "fldshort float",  L("lcl_cnt_period_sum") + " " + L("lcl_valutasign"), safe.curreditable(cnt_info.termijnkosten), {readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg, suppressEmpty: true});
        FCLTselector("cnt_term_period", sql_termijnen,
                       { label: L("lcl_cnt_period_period"),
                         initKey: cnt_info.termijntermijn,
                         required: false,
                         emptyOption: "",
                         readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg,
                         suppressEmpty: true
                      });
        // TODO: berekend jaarbedrag hiertussen??
        RWFIELDTR("cnt_cntkstn",  "fldshort float",  L("lcl_cnt_contract_sum") + " " + L("lcl_valutasign"),
                                    safe.curreditable(cnt_info.kosten),
                                    { readonly: !this_cnt.canChangeKosten || !this_cnt.canChangeAlg, suppressEmpty: true} );
        RWFIELDTR("cnt_uurloon",  "fldshort float",      L("lcl_hour_rate") + " " + L("lcl_valutasign"), safe.curreditable(cnt_info.uurloon), {readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg, suppressEmpty: true});
        RWFIELDTR("cnt_korting",  "fldshort float",      L("lcl_cnt_discount"), cnt_info.korting, {datatype:"float", readonly: cnt_info.isAbonnement || !this_cnt.canChangeAlg, suppressEmpty: true});
        BLOCK_END();

        BLOCK_START("cntFlex"+(S("cnt_flexcolumns")!=1?"2":"") , L("lcl_cnt_flexblok"));
        generateFlexKenmerkCode ({cnt_key    : cnt_key,
                                  disc_key   : cnt_info.discipline_key,
                                  this_cnt   : this_cnt,
                                  flexcolumns: S("cnt_flexcolumns")
                                 });
        BLOCK_END();
IFACE.FORM_END();
%>
      </form>
      <iframe src="../Shared/empty.html" name="hidFrameSubmit" style="display:none"></iframe>
    </div>
  </body>
</html>
