/*
    $Revision$
    $Id$

    File:           mjb_search_list.js
*/
function naarlocatie(loc_key, deze)
{
   if (fulldetails)
     var url = "appl/alg/alg_locatie.asp?key=" + loc_key;
   else
     var url = "appl/mjb/mjb_search.asp?autosearch=1&groupby=9" + transitParam + "&locatie_key=" + loc_key;
   FcltMgr.openDetail(url, $(deze).text());
}

function naargebouw(bld_key, deze)
{
   if (fulldetails)
     var url = "appl/alg/alg_gebouw.asp?key=" + bld_key;
   else
     var url = "appl/mjb/mjb_search.asp?autosearch=1&groupby=9" + transitParam + "&gebouw_key=" + bld_key;
   FcltMgr.openDetail(url, $(deze).text());
}

function naarterrein(ter_key, deze)
{
   if (fulldetails)
     var url = "appl/alg/alg_terreinsector.asp?ter_key=" + ter_key;
   else
     var url = "appl/mjb/mjb_search.asp?autosearch=1&groupby=9" + transitParam + "&gebouw_key=" + ter_key;
   FcltMgr.openDetail(url, $(deze).text());
}

function naarruimte(rui_key, deze)
{
   if (groupby == 7 || groupby == 9)
   {
     var url = "appl/alg/alg_ruimte.asp?key=" + rui_key;
     FcltMgr.openDetail(url, $(deze).text());
   }
}

function naardeel(ins_key, deze)
{
   var url = "appl/ins/ins_deel.asp?ins_key=" + ins_key + "&urole=bo";
   FcltMgr.openDetail(url, $(deze).text());
}

function exception(ins_key, srtcont_key, scen_key, ttl)
{
   var url = "../ins/ins_xcp.asp?ins_key=" + ins_key + "&srtcont_key=" + srtcont_key + "&scen_key=" + scen_key + "&incbtw=" + incbtw + "&urole=bo";
   FcltMgr.openModalDetail(url, { titel: L("lcl_ins_change_xcp")+" "+ttl, callback: FcltMgr.reload });
}

function naarmelding(mld_key, deze)
{
   var url = "appl/mld/mld_melding.asp?mld_key=" + mld_key + "&urole=bo";
   FcltMgr.openDetail(url, $(deze).text());
}

function moveplan(evt, ins_key, srtcont_key, scen_key, dlsrtcont_key, startdatum, hascontrole, bedragFY, notSucces, rejectedInFY, jaar, plan_opm)
{
  FcltMgr.stopPropagation(evt);
  return new Promise((resolve, reject) => {
    // 1) Als er geen jaar meegegeven is dan niets doen.
    // 2) Als er al een succesvol uitgevoerde inspectie is geweest dan niet meer naar startdatum kijken.
    //    Situatie als het jaar gelijk is aan de startdatum:
    //    Geplande inspectie record aanwezig: Nee: (dlsrtcont_key < 0) Niets doen => refresh en return.
    //                                         Ja: (dlsrtcont_key > 0) Door naar ins_inspect_save.asp om record te verwijderen.
    // 3) Als je de inspectie verschuift naar het freeze jaar waar al een bedrag in vermeld staat (een inpectie is), dan niets doen.
    if (!jaar ||
        (!hascontrole &&
        (startdatum > 0 &&
          ((dlsrtcont_key < 0 && jaar <= new Date(startdatum).getFullYear()) ||
          (dlsrtcont_key > 0 && jaar <  new Date(startdatum).getFullYear())
          )
        )
        ) ||
        ((bedragFY != null && bedragFY >= 0) && jaar == mjb_freeze_year)
      )
    {
      resolve();
      return;
    }

    var minjaar = mjb_freeze_year || (new Date()).getFullYear();
    var savemode, plandatum;

    if (jaar >= minjaar && jaar < (minjaar + mjb_show_years))
    {
      savemode = "P"; // (absolute) plan-mode
      plandatum = new Date(jaar, 11, 31).getTime();
    }
    else if (jaar > -mjb_show_years && jaar < mjb_show_years)
    {
      savemode = "R" // relative plan-mode
      plandatum = jaar;
    }
    else
    {
      resolve();
      return;
    }

    if (notSucces > 0 && dlsrtcont_key > 0 && jaar == (rejectedInFY == 1? (mjb_freeze_year + 1) : mjb_freeze_year))
      // Laatste inspectie was niet succesvol. Volgende inspectie is naar het volgende jaar gesleept. Geplande record verwijderen.
      savemode = "D";

    var data = { savemode        : savemode,
                ins_keys        : ins_key,
                srtcont_key_arr : srtcont_key,
                deelsrtcont_key : dlsrtcont_key,
                scen_key_arr    : scen_key,
                plandatum       : plandatum,
                plan_opm        : plan_opm,
                mjob            : 1
              };

    protectRequest.dataToken(data);
    $.ajax({
      type: "POST",
      url: "../ins/ins_inspect_save.asp",
      data: data,
      success: json => {
        if (json.success) {
          mjbAantal++;
          resolve();
        } else {
          reject();
        }
      },
      error: reject,
      dataType: "json"
    });
  }).catch(_ => { /* rejected, no action */ });
}

var mjbDeelKeyArray       = [];
var mjbSrtContrKeyArray   = [];
var mjbDlSrtContKeyArr    = [];
var mjbScenKeyArray       = [];
var mjbStartDatumKeyArray = [];
var mjbHasControleArray   = [];
var mjbBedragFYArray      = [];
var mjbNotSuccesArray     = [];
var mjbRejectedInFYArray  = [];
var mjbAantal;
async function dragDropCallback(json, textStatus)
{
  mjbAantal = 0;
  let movePlanPromises = [];
  for (var i = 0; i < mjbDeelKeyArray.length; i++)
  {
    movePlanPromises.push(
      moveplan(null,
               mjbDeelKeyArray[i],
               mjbSrtContrKeyArray[i],
               mjbScenKeyArray[i],
               mjbDlSrtContKeyArr[i],
               mjbStartDatumKeyArray[i],
               mjbHasControleArray[i],
               mjbBedragFYArray[i],
               mjbNotSuccesArray[i],
               mjbRejectedInFYArray,
               json.year,
               json.plan_opm));
  }

  await Promise.all(movePlanPromises);

  // Als bij multi niet alle taken zijn hergepland dan een nette melding hiervan geven.
  if (mjbAantal < mjbDeelKeyArray.length)
  { // Niet alle taken zijn hergepland.
    json.message = mjbAantal == 1? L("lcl_mjb_reschedule_mess_1").format(mjbDeelKeyArray.length) : L("lcl_mjb_reschedule_mess_n").format(mjbAantal, mjbDeelKeyArray.length);
  }
  else
  { // Alle taken zijn hergepland.
    json.toaster = L("lcl_mjb_reschedule_completed");
  }

  // Wel even het overzicht refreshen.
  json.success = true;
  FcltCallbackRefresh(json, textStatus);
}

function mjb_dragdrop(rowArray, isMulti)
{
  mjbDeelKeyArray       = [];
  mjbSrtContrKeyArray   = [];
  mjbDlSrtContKeyArr    = [];
  mjbScenKeyArray       = [];
  mjbStartDatumKeyArray = [];
  mjbHasControleArray   = [];
  mjbBedragFYArray      = [];
  mjbNotSuccesArray     = [];
  mjbRejectedInFYArray  = [];
  for (var i = 0; i < rowArray.length; i++)
  {
    rowdata = JSON.parse(rowArray[i].getAttribute("ROWDATA"));
    mjbDeelKeyArray.push(rowdata.insKey);
    mjbSrtContrKeyArray.push(rowdata.insSrtControleKey);
    mjbDlSrtContKeyArr.push(rowdata.insDeelSrtContrKey);
    mjbScenKeyArray.push(rowdata.insScenKey);
    mjbStartDatumKeyArray.push(rowdata.insStartDatum);
    mjbHasControleArray.push(rowdata.insHasControle);
    mjbBedragFYArray.push(rowdata.insBedragFY);
    mjbNotSuccesArray.push(rowdata.insNotSucces);
    mjbRejectedInFYArray.push(rowdata.insRejectedInFY);
  }
  url = "../mjb/mjb_dragdropyear.asp?ctrdisc_key=" + ctrdisc_key + "&ins_keys=" + mjbDeelKeyArray.join(",");
  FcltMgr.openModalDetail(url, L("lcl_mjb_dragdrop"), {callback: dragDropCallback});
}

function mjb_dragdrop_1x(evt, ins_key, srtcont_key, scen_key, dlsrtcont_key, startdatum, hascontrole, bedragFY, notSucces, rejectedInFY, jaar, plan_opm)
{
  mjbDeelKeyArray       = [ins_key];
  mjbSrtContrKeyArray   = [srtcont_key];
  mjbDlSrtContKeyArr    = [dlsrtcont_key];
  mjbScenKeyArray       = [scen_key];
  mjbStartDatumKeyArray = [startdatum];
  mjbHasControleArray   = [hascontrole];
  mjbBedragFYArray      = [bedragFY];
  mjbNotSuccesArray     = [notSucces];
  mjbRejectedInFYArray  = [rejectedInFY];
  url = "../mjb/mjb_dragdropyear.asp?ctrdisc_key=" + ctrdisc_key + "&ins_keys=" + mjbDeelKeyArray.join(",") + "&jaar=" + jaar + "&plan_opm=" + plan_opm;
  FcltMgr.openModalDetail(url, L("lcl_mjb_dragdrop"), {callback: dragDropCallback});
}

function mjb_moveYearBack(rowArray, isMulti)
{ // Deze functie wordt alleen aangeroepen in de actuele situatie (scenario key is 1) (WOHW#79637).
  var ins_key_arr       = [];
  var srtcont_key_arr   = [];
  var dlsrtcont_key_arr = [];
  var scen_key_arr      = [];
  var aantaltaken = 0;
  for (var i = 0; i < rowArray.length; i++)
  {
    rowdata = JSON.parse(rowArray[i].getAttribute("ROWDATA"));

    // Delete the following ins_deelsrtcontrole records
    if (rowdata.insDeelSrtContrKey    != null && rowdata.insDeelSrtContrKey > -1 &&
        rowdata.insDeelSrtContrStatus != null && rowdata.insDeelSrtContrStatus == 0) // Ingepland (0)
    {
      ins_key_arr.push(rowdata.insKey);
      srtcont_key_arr.push(rowdata.insSrtControleKey);
      dlsrtcont_key_arr.push(rowdata.insDeelSrtContrKey);
      scen_key_arr.push(rowdata.insScenKey);
      aantaltaken += rowdata.aantaltaken;
    }
  }
  if (ins_key_arr.length)
  {
    var data = { savemode         : "D", // delete-mode
                 ins_keys         : ins_key_arr.join(","),
                 srtcont_key_arr  : srtcont_key_arr.join(","),
                 dlsrtcont_key_arr: dlsrtcont_key_arr.join(","),
                 scen_key_arr     : scen_key_arr.join(","),
                 mjob             : 1
               };

    protectRequest.dataToken(data);
    $.post("../ins/ins_inspect_save.asp"
           , data
           , function(json, textStatus)
             { // Als bij multi niet alle taken zijn teruggepland dan een nette melding hiervan geven.
               if (json.success && rowArray.length == ins_key_arr.length)
               { // Alle taken zijn teruggepland.
                 json.toaster = L("lcl_mjb_moveback_completed");
               }
               else
               { // Niet alle taken zijn teruggepland.
                 json.message = ins_key_arr.length == 1? L("lcl_mjb_moveback_mes_1").format(rowArray.length) : L("lcl_mjb_moveback_mes_n").format(ins_key_arr.length, rowArray.length);
               }
               FcltCallbackRefresh(json, textStatus);
             }
           , "json"
           );
  }
  else // Er hoeven geen taken te worden teruggezet.
    FcltMgr.alert(L("lcl_mjb_moveback_mes_n").format(0, rowArray.length));
}

// Nu in "MJOP Scenario's" aan te roepen.
//function insInstituteScen()
//{
//  var subject = L("lcl_mjb_inst_scen");
//  var url = "../mjb/mjb_institute_scen.asp";
//  FcltMgr.openModalDetail(url, subject, {callback: FcltCallbackRefresh});
//}

//function insAddTCScen()
//{
//  var subject = L("lcl_mjb_incl_scen");
//  var url = "../mjb/mjb_incl_scen.asp?totalcopy=1";
//  FcltMgr.openModalDetail(url, subject, {callback: FcltCallbackRefresh});
//}

function insMultiEdit(rowArray)
{
  var insKeyString = getKeyString(rowArray);
  var srtcontrolekeyArray = new Array();
  var scenKeyArray = new Array();
  var xcpkeyArray = new Array();
  var deleted = 0;
  for (var i = 0; i < rowArray.length; i++)
  {
    rowdata = JSON.parse(rowArray[i].getAttribute("ROWDATA"));
    srtcontrolekeyArray[i] = rowdata.insSrtControleKey;
    xcpkeyArray[i] = rowdata.insXcpKey;
    scenKeyArray[i] = rowdata.insScenKey;
  }

  var url = "../ins/ins_xcp_multi.asp"
  var subject = L("lcl_ins_multi_edit");
  var data = { insKeyString: insKeyString,
               srtcontrolekeyArray: srtcontrolekeyArray.join(","),
               xcpkeyArray: xcpkeyArray.join(","),
               scenKeyArray: scenKeyArray.join(","),
               callback: FcltCallbackRefresh
             };
  FcltMgr.openModalDetail(url, subject, data);
}

function multiPriceChangeCallback(json, insKeyString)
{
  var data = { costs: json.costs || 0,
               costs2: json.costs2 || 0,
               costs3: json.costs3 || 0,
               material: json.material || 0,
               aantaltaken: json.aantaltaken,
               ins_keys: insKeyString,
               showempty: (showempty? 1 : 0),
               categorie_key_arr: categorie_key_arr,
               dist_key_arr: dist_key_arr,
               loc_key_arr: loc_key_arr,
               bld_key_arr: bld_key_arr,
               disc_key_arr: disc_key_arr,
               srtgroep_key_arr: srtgroep_key_arr,
               srtdeel_key_arr: srtdeel_key_arr,
               srtgebouw_key_arr: srtgebouw_key_arr,
               groep_str_arr: groep_str_arr,
               srtcontrole_key_arr: srtcontrole_key_arr,
               frequentie_arr: frequentie_arr,
               kp_key_arr: kp_key_arr,
               incbtw: incbtw,
               groupby: groupby,
               moredetail: moredetail,
               deel: deel,
               mjbMoved: mjbMoved,
               mjbFreezed: mjbFreezed,
               mjbXcped: mjbXcped,
               toyear: toyear,
               scenario: scenario,
               fitness_score1_from: fitness_score1_from,
               fitness_score1_through: fitness_score1_through,
               fitness_score1_from_neg: fitness_score1_from_neg,
               fitness_score1_through_neg: fitness_score1_through_neg,
               fitness_score1_from_pos: fitness_score1_from_pos,
               fitness_score1_through_pos: fitness_score1_through_pos,
               priority_score2_from: priority_score2_from,
               priority_score2_through: priority_score2_through,
               jaren: jaren
             };
  protectRequest.dataToken(data);
  $.post("../ins/ins_srtcontrolexcp_pc_save.asp", data, FcltCallbackRefresh, "json");
}

function insMultiPriceChange(rowArray)
{
  var insKeyString = getKeyString(rowArray); // Bevat de keys van de betreffende groepering.
  var aantaltaken = 0;
  for (var i = 0; i < rowArray.length; i++)
  {
    rowdata = JSON.parse(rowArray[i].getAttribute("ROWDATA"));
    aantaltaken += rowdata.aantaltaken;
  }

  var url = "../ins/ins_pricechange.asp";
  FcltMgr.openModalDetail(url,
                          L("lcl_mjb_change_costs"),
                          { callback: function (json)
                                      {
                                        json.aantaltaken = aantaltaken;
                                        multiPriceChangeCallback(json, insKeyString);
                                      }
                          });
}

function insAddScen(rowArray)
{
  var insKeyString = getKeyString(rowArray);
  var srtcontrolekeyArray = new Array();
  var scenariokeyArray = new Array();
  var deelsrtcontrstatusArray = new Array();
  var isfreezeyearArray = new Array();
  var ctrdisciplinekeyArray = new Array();
  var deleted = 0;
  var aantaltaken = 0;
  for (var i = 0; i < rowArray.length; i++)
  {
    rowdata = JSON.parse(rowArray[i].getAttribute("ROWDATA"));
    // Scenario's kunnen niet opgenomen worden in een scenario. Hier de scenario's er al uit filteren.
    if (!rowdata.insScenKey || rowdata.insScenKey == 1)
    { // Het is geen scenario. De periodieke taak kan in een scenario worden opgenomen. De inspectie aan het array toevoegen.
      if (groupby == 9)
      {
        srtcontrolekeyArray[i - deleted] = rowdata.insSrtControleKey;
        scenariokeyArray[i - deleted] = rowdata.insScenKey;
        deelsrtcontrstatusArray[i - deleted] = rowdata.insDeelSrtContrStatus;
        isfreezeyearArray[i - deleted] = rowdata.insIsFreezeYear;
        ctrdisciplinekeyArray[i - deleted] = rowdata.insCtrDisciplineKey;
      }
      aantaltaken += rowdata.aantaltaken;
    }
    else
    { // Het is een scenario. De ins_key verwijderen uit de lijst.
      var insKeyString_arr = insKeyString.split(",");
      insKeyString_arr.splice(i - deleted, 1);
      insKeyString = insKeyString_arr.join(",");
      deleted++;
    }
  }

  if (insKeyString.length > 0)
  {
    if (scenario > 1)
    {
      var data = { ins_keys: insKeyString,
                   srtcont_keys: srtcontrolekeyArray.join(","),
                   scen_key_arr: scenariokeyArray.join(","),
                   deelsrtcontrstatus_arr: deelsrtcontrstatusArray.join(","),
                   isfreezeyear_arr: isfreezeyearArray.join(","),
                   ctrdisc_keys: ctrdisciplinekeyArray.join(","),
                   scen_key: scenario,
                   aantaltaken: aantaltaken
                 };
      protectRequest.dataToken(data);
      $.post("../mjb/mjb_incl_scen_save.asp"
            , data
            , FcltCallbackRefresh
            , "json"
            );
    }
    else
    {
      var subject = L("lcl_mjb_incl_scen");
      var url = "../mjb/mjb_incl_scen.asp?groupby=" + groupby;
      var data = { insKeyString: insKeyString,
                   srtcontrolekeyArray: srtcontrolekeyArray.join(","),
                   scenariokeyArray: scenariokeyArray.join(","),
                   deelsrtcontrstatusArray: deelsrtcontrstatusArray.join(","),
                   isfreezeyearArray: isfreezeyearArray.join(","),
                   ctrdisciplinekeyArray: ctrdisciplinekeyArray.join(","),
                   aantaltaken: aantaltaken,
                   callback: FcltCallbackRefresh
                 };

      if (groupby < 9)
      {
        data.scenario = scenario;
        data.actsit = (actsit? 1 : 0);
        data.showunfin = (showunfin? 1 : 0);
        data.showempty = (showempty? 1 : 0);
        data.categorie_key_arr = categorie_key_arr;
        data.reg_key_arr = reg_key_arr;
        data.dist_key_arr = dist_key_arr;
        data.loc_key_arr = loc_key_arr;
        data.bld_key_arr = bld_key_arr;
        data.disc_key_arr = disc_key_arr;
        data.srtgroep_key_arr = srtgroep_key_arr;
        data.srtdeel_key_arr = srtdeel_key_arr;
        data.moredetail = moredetail;
        data.srtgebouw_key_arr = srtgebouw_key_arr;
        data.groep_str_arr = groep_str_arr;
        data.srtcontrole_key_arr = srtcontrole_key_arr;
        data.frequentie_arr = frequentie_arr;
        data.kp_key_arr = kp_key_arr;
        data.verantw_key = verantw_key;
        data.beheerder_key = beheerder_key;
        data.incbtw = incbtw;
        data.toyear = toyear;
        data.groupby = groupby;
        data.deel = deel;
        data.fitness_score1_from = fitness_score1_from;
        data.fitness_score1_through = fitness_score1_through;
        data.fitness_score1_from_neg = fitness_score1_from_neg;
        data.fitness_score1_through_neg = fitness_score1_through_neg;
        data.fitness_score1_from_pos = fitness_score1_from_pos;
        data.fitness_score1_through_pos = fitness_score1_through_pos;
        data.priority_score2_from = priority_score2_from;
        data.priority_score2_through = priority_score2_through;
        data.mjbMoved = mjbMoved;
        data.mjbFreezed = mjbFreezed;
        data.mjbXcped = mjbXcped;
        data.jaren = jaren;
      }
      FcltMgr.openModalDetail(url,
                              subject,
                              data);
    }
  }
  // else: alle taken zitten al in het scenario.
}

function insExecute(rowArray)
{
  var insKeyString = getKeyString(rowArray);
  var srtcontrolekeyArray = new Array();
  var deelsrtcontrkeyArray = new Array();
  var ctrdisciplinekeyArray = new Array();
  var aantaltaken = 0;
  for (var i = 0; i < rowArray.length; i++)
  {
    rowdata = JSON.parse(rowArray[i].getAttribute("ROWDATA"));
    // De scenario's zijn er in het overzicht al uitgefilter.
    if (groupby == 9)
    {
      srtcontrolekeyArray[i] = rowdata.insSrtControleKey;
      deelsrtcontrkeyArray[i] = rowdata.insDeelSrtContrKey;
      ctrdisciplinekeyArray[i] = rowdata.insCtrDisciplineKey;
    }
    aantaltaken += rowdata.aantaltaken;
  }

  if (insKeyString.length > 0)
  {
    var subject = L("lcl_mjb_incl_mld");
    var url = "../mjb/mjb_inspect_execute.asp?groupby=" + groupby;
    var data = { insKeyString: insKeyString,
                 srtcontrolekeyArray: srtcontrolekeyArray.join(","),
                 deelsrtcontrkeyArray: deelsrtcontrkeyArray.join(","),
                 ctrdisciplinekeyArray: ctrdisciplinekeyArray.join(","),
                 aantaltaken: aantaltaken,
                 callback: FcltCallbackRefresh
               };

    if (groupby < 9)
    {
      data.scenario = 1;
      data.actsit = (actsit? 1 : 0);
      data.showunfin = (showunfin? 1 : 0);
      data.showempty = (showempty? 1 : 0);
      data.categorie_key_arr = categorie_key_arr;
      data.reg_key_arr = reg_key_arr;
      data.dist_key_arr = dist_key_arr;
      data.loc_key_arr = loc_key_arr;
      data.bld_key_arr = bld_key_arr;
      data.disc_key_arr = disc_key_arr;
      data.srtgroep_key_arr = srtgroep_key_arr;
      data.srtdeel_key_arr = srtdeel_key_arr;
      data.moredetail = moredetail;
      data.srtgebouw_key_arr = srtgebouw_key_arr;
      data.groep_str_arr = groep_str_arr;
      data.srtcontrole_key_arr = srtcontrole_key_arr;
      data.frequentie_arr = frequentie_arr;
      data.kp_key_arr = kp_key_arr;
      data.verantw_key = verantw_key;
      data.beheerder_key = beheerder_key;
      data.incbtw = incbtw;
      data.toyear = toyear;
      data.groupby = groupby;
      data.deel = deel;
      data.fitness_score1_from = fitness_score1_from;
      data.fitness_score1_through = fitness_score1_through;
      data.fitness_score1_from_neg = fitness_score1_from_neg;
      data.fitness_score1_through_neg = fitness_score1_through_neg;
      data.fitness_score1_from_pos = fitness_score1_from_pos;
      data.fitness_score1_through_pos = fitness_score1_through_pos;
      data.priority_score2_from = priority_score2_from      ;
      data.priority_score2_through = priority_score2_through;
      data.mjbMoved = mjbMoved;
      data.mjbFreezed = mjbFreezed;
      data.mjbXcped = mjbXcped;
      data.mjbStatus2 = mjbStatus2;
      data.mjbStatus3 = mjbStatus3;
      data.jaren = jaren;
    }
    FcltMgr.openModalDetail(url,
                            subject,
                            data);
  }
}
