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

     File:               mld_link.asp
     Description:        (Ont)koppelen afhandeling van een melding
     Parameters:
         mld_key         Melding
*/ %>

<%
var JSON_Result = true;
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/save2db.inc" -->
<!-- #include file="mld.inc" -->

<%
protectRequest.validateToken();
var mld_key = getFParamInt("mld_key");
var result = { message: "", success: false };

var this_mld = mld.func_enabled_melding(mld_key);
var mld_melding = mld.mld_melding_info(mld_key);
lcl.set_dialect(mld_melding.srtdisc_key, "MLD_SRTDISCIPLINE_KEY");

var parent_key = getFParamInt("parent_key", -1, true); // Als niet meegegeven doen we unlink

if (parent_key > 0)
{ // Link child melding
  user.anything_todo_or_abort(this_mld.canLink || this_mld.canAccept);

  var sql = "SELECT mld_melding_key FROM mld_melding WHERE mld_melding_key = " + parent_key;
  if (Oracle.Execute(sql).Eof)
    result.message = L("lcl_linkedparent_notfound");
  else
  { // Is gekozen parent melding zelf niet een child (child(mld_key) --> parent(parent_key) -x-> C).
    var sql = "SELECT 1"
            + "  FROM mld_melding m"
            + " WHERE m.mld_melding_parentkey IS NULL"
            + "   AND mld_melding_key = " + parent_key;
    if (Oracle.Execute(sql).Eof || mld_key == parent_key)
      result.message = L("lcl_mld_linkedparent"); // Parent is een child (De parent_key is gevuld).
    else
    { // De parent_key is niet gevuld.
      // Is gekozen child melding zelf niet een parent (C -x-> child(mld_key) --> parent(parent_key)).
      var sql = "SELECT 1"
              + "  FROM mld_melding m"
              + " WHERE m.mld_melding_parentkey = " + mld_key;
      if (!Oracle.Execute(sql).Eof)
        result.message = L("lcl_mld_linkedchild"); // Child is een parent (Child wordt gebruikt als parent_key).
      else
      {
        result.warning = mld.link_child_to_parent(mld_key, parent_key);
        result.success = true;
      }
    }
  }
}
else
{ // Unlink child melding
  user.anything_todo_or_abort(this_mld.canUnlink);

  var sql = "UPDATE mld_melding"
          + "   SET mld_melding_parentkey = NULL"
          + " WHERE mld_melding_key = " + mld_key;
  Oracle.Execute(sql);
  mld.trackmeldingupdate(mld_key, L("lcl_unlinked"));
  result.success = true;
}

Response.Write(JSON.stringify(result));
%>

<% ASPPAGE_END(); %>
