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

     File:           fac_setting.asp
     Description:
     Parameters:     fac_key
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/audithistory.inc" -->
<!-- #include file="fac.inc" -->

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

var fac_key = getQParamInt("fac_key");

var authPRSSYS = user.checkAutorisation("WEB_PRSSYS");
var authFACFAC = user.checkAutorisation("WEB_FACFAC", true);
var authFACTAB = user.checkAutorisation("WEB_FACTAB", true);

function prettyJson(j)
{
  try
  {
    var xx = JSON.stringify(JSON.parse(j), null, 2);
    if (xx == "null")
        return "";
    return xx;
  }
  catch (e)
  {
    return j;
  };
};

var sql = "SELECT * FROM fac_setting s, prs_v_perslid_fullnames pf"
        + " WHERE s.prs_perslid_key = pf.prs_perslid_key(+)"
        + "   AND fac_setting_key ="+fac_key;

var oRs = Oracle.Execute(sql);
var functie_key = oRs("fac_functie_key").Value;
var sname = oRs("fac_setting_name").value;

var canView = authFACFAC ||
              (oRs("fac_setting_flags").Value & 1) ||
              (authFACTAB && (functie_key == authFACTAB.autfunctionkey || sname == 'flexfilespath'));

user.auth_required_or_abort(canView); // moet zichtbaar zijn voor PRSSYS

var isProtected = (functie_key != authPRSSYS.autfunctionkey);
canChange = (!isProtected ||
             authFACFAC && functie_key == authFACFAC.autfunctionkey ||
             authFACTAB && (functie_key == authFACTAB.autfunctionkey || sname == 'flexfilespath'))

%>

<html>
  <head>
<%  FCLTHeader.Generate(); %>
    <script type="text/javascript">

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

      async function doSubmit()
      {
        document.activeElement.blur(); // trigger laatste onChanges

        // Standaard checks op verplichte velden, datum formaat, numeriek en float formaat, currency formaat.
        if (!await validateForm("u2"))
          return false;

        var stype = ("<%=oRs("fac_setting_type").value%>").toLowerCase();
        var vtype = $("#pvalue").val().trim().toLowerCase();
        var rtype = 0;
        if (vtype != "")
        {
        	switch (stype)
        	{
        		case "string":
      	  		{
    	    			break;
  	      		}
  	      		case "array":
  	      		{
  	      		  break;
  	      		}
	        	case "boolean":
        			{
        				rtype = ((vtype=='true'||vtype=='false')
        								? 0
        								: 1
        								);
        				break;
      	  		}

    	    	case "number":
  	      		{
	        			rtype = (isNaN(parseInt(vtype, 10))
        								? 1
        								: (isGoodNumber(vtype,true,false,-1,-1)
        									? 0
        									: 1)
        								);
        				break;
      	  		}
    	    	case "float":
  	      		{
	        			rtype = (!isFinite(parseFloat(vtype))
        								? 1
        								: (isGoodNumber(vtype,false,false,-1,-1)
        									? 0
        									: 1)
        								);
        				break;
        			}
        	  case "json":
         	    {
                try
                {
                  vtype = JSON.stringify(JSON.parse(vtype)); // test en formatteer plat
                  if (vtype == "null")
                    vtype = "";
                  $("#pvalue").val(vtype); // zet de platte tekst terug in de database
                }
                  catch (e)
                {
                  rtype = 1;
                }
        	      break;
        	    }
        		default:
        			{
        				rtype = 2;
        			}
        	}
      	}
        if (rtype > 0)
        {
        	if (rtype == 1)
        	{
                FcltMgr.alert("waarde moet van het type " +stype+ " zijn.");
    			}
    			else
    			{
    				FcltMgr.alert("Unknown type " +stype+ ".");
    			}
    			return false;
    		}
        document.forms.u2.submit();
      }

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

    </script>
  </head>

  <body class="editmode">
<%  SUBFRAME_START();
    buttons = []
    if (canChange)
        buttons.push ({title: L("lcl_submit"),  icon: "fa-fclt-save", action: "doSubmit()" });
    buttons.push( {title: L("lcl_cancel"), icon: "fa-fclt-cancel", action: "doCancel()" } );
    if (fac_key > 0)
    {
      var historytitle = sname;
      // Als er audit history is, dan voegt de functie een extra button aan het meegegeven object buttons toe.
      AUDIT_HISTORY_BUTTON(buttons,
                           { tablekeyarray: [fac_key],
                             tablename: "fac_setting",
                             historytitle: historytitle });
    }

    IFRAMER_HEADER("Setting", buttons);
%>
      <form name=u2
            method="post"
            action="fac_setting_save.asp?fac_key=<%=fac_key%>"
            target="hidFrameSubmit"
            onSubmit="doSubmit();">
<%
function clr(oRs, fld)
{
    var val = oRs(fld).Value;
    if (oRs("fac_setting_type").value != "number" || val == "" || !String(oRs("fac_setting_name").value).match(/color/ig))
        return "";

    var hex = "000000" + parseInt(val).toString(16);
    hex = hex.substring(hex.length - 6, hex.length);
    var ttl = "0x" + hex;
    var clr = " style='border:1px solid black;width:16px;height:16px;background-color:" + "#" + hex + "'";
    return " <span title='"+ ttl +"' " + clr + ">&nbsp;&nbsp;&nbsp;&nbsp;</span>";
}

function hexttl (setting_type, val)
{
    if (setting_type == "number")
        return "0x" + parseInt(val).toString(16);
    return "";
}
        BLOCK_START("fac_set", L("lcl_fac_setting_block"), { "icon": "fa-gears" });
          if (isProtected)
        {
%>        <tr><td colspan="2" class="facsetreado"><%=L("lcl_fac_setting_fcltonly")%></td></tr><%
        }
          ROFIELDTR("fld"      , L("lcl_fac_setting")    , sname);
          ROFIELDTR("fld"      , L("lcl_fac_module")     , oRs("fac_setting_module").value);
          ROTEXTAREATR("fldtxt", L("lcl_fac_descr")      , oRs("fac_setting_description").value);
          ROFIELDTR("fld"      , L("lcl_fac_set")        , oRs("prs_perslid_naam_full").value);
          ROFIELDTR("fld"      , L("lcl_fac_time")       , toDateTimeString(oRs("fac_setting_datum").value));

          if (oRs("fac_setting_default").Value != Application("SET_DEFAULT_" + sname) && typeof Application("SET_DEFAULT_" + sname) != "undefined")
          {
            ROFIELDTR("fld", "<span style='background-color:red;color:white'>Default value does not match<br>the one cached by {0}</span>".format(Application("DEFAULTS_SET_BY_CUSTOMER")), Application("SET_DEFAULT_" + sname));
          }

          if (oRs("fac_setting_type").Value != Application("SET_T_" + sname) && !(sname in settings.aspdefaults))
          {
            ROFIELDTR("fld", "<span style='background-color:red;color:white'>Type does not match<br>the one cached by {0}</span>".format(Application("DEFAULTS_SET_BY_CUSTOMER")), Application("SET_T_" + sname));
          }

          var setting_type = oRs("fac_setting_type").value;
          ROFIELDTR("fld"      , L("lcl_fac_settingtype"), setting_type);
          var actual = S(sname);
          if (setting_type == "json")
          {
            ROTEXTAREATR(            "fld"   , L("lcl_fac_default") , prettyJson(oRs("fac_setting_default").value));
            if (canChange)
              RWTEXTAREATR("pvalue", "fldtxt disabled", L("lcl_fac_value")    , prettyJson(oRs("fac_setting_pvalue").Value) , {maxlength: 4000, no_bb_codes: true});
            else
              ROTEXTAREATR(          "fldtxt", L("lcl_fac_value")    , prettyJson(oRs("fac_setting_pvalue").Value));
          }
          else
          {
            ROFIELDTR(               "fld"   , L("lcl_fac_default") + clr(oRs, "fac_setting_default") , oRs("fac_setting_default").value, { title: hexttl(setting_type, oRs("fac_setting_default").value) });
            if (canChange)
            {
              if (actual && actual.length > 50)
                RWTEXTAREATR("pvalue",    "fld"   , L("lcl_fac_value")  + clr(oRs, "fac_setting_pvalue")  , oRs("fac_setting_pvalue").value, { no_bb_codes: true });
              else
                RWFIELDTR("pvalue",    "fld"   , L("lcl_fac_value")  + clr(oRs, "fac_setting_pvalue")  , oRs("fac_setting_pvalue").value);
            }
            else
            {
              ROFIELDTR(             "fld"   , L("lcl_fac_value") + clr(oRs, "fac_setting_pvalue"), oRs("fac_setting_pvalue").value);
              // Dit kan voor bijvoorbeeld flexfilespath nog afwijken via settings.cache
            }
            if (sname.toLowerCase() in settings.overrule)
            {
                ROFIELDTR("fld", "<span style='background-color:red;color:white'>Custenv.wsc overrule</span>", settings.overrule[sname.toLowerCase()]);
            }
            if (oRs("fac_setting_pvalue").value != actual &&
                oRs("fac_setting_default").value != actual)
            {
              ROTEXTAREATR("fldtxt", L("lcl_fac_effective") + clr(oRs, "fac_setting_default") , String(actual));
            }
          };
        BLOCK_END();
        IFACE.FORM_END();

        var trackurl = 'fac_admtracking_list.asp?showall=1&zoek=S(' + sname + ')';
%>
      </form>
      <% SUBFRAME_END(); %>
      <iframe src="../Shared/empty.html" name="hidFrameSubmit" style="display:none"></iframe>
    <div id="result">
     <iframe width="100%" height="100%" src="<%=trackurl%>"
             name="workFrame" id="workFrame"  onload='FcltMgr.iframeLoaded(this)'
             frameborder="0" scrolling="no"></iframe>
    </div>
  </body>
</html>
<% ASPPAGE_END(); %>
