<% /*
    $Revision$
    $Id$

    File:        default.inc
    Description: Gaat over alle settings
    Parameters:
    Context:     Vanuit ELK asp bestand
    Note:        Sinds 5.2.2 zitten de settings in de database
*/

var FCLTVersion="2016.3";
var FCLTMinDatabaseSchema="30";

var custpath = rooturl + "/cust/" + customerId;  // path to customer files

var hiresTimer = null;

/* global */
settings =
{
    overrule: {},

    cache : { perfmon_threshold:      { v: 2000 }, // is al nodig om de settings uit de database te kunnen halen
              // Onderstaande settings hebben een default die custpath afhankelijk is.
              // In de database kunnen ze nog wel overruled worden
              image_path_virtual:     { v: custpath },
              flexfilespath:          { v: Server.MapPath(custpath + "/flexfiles") },
              bdradrfiles_path:       { v: Server.MapPath(custpath + "/bdradrfiles") },

              fg_dwf_path:            { v: Server.MapPath(custpath + "/dwf/") + "/" },
              fg_dwf_path_concept:    { v: Server.MapPath(custpath + "/dwf/") + "/concept/" },
              fg_vlucht_path:         { v: Server.MapPath(custpath + "/dwf/") + "/vlucht/" },
              fg_symbols_path:        { v: Server.MapPath(custpath + "/dwf/") + "/symbols/" },
              fg_dwf_path_prj:        { v: Server.MapPath(custpath + "/dwf/") + "/prj/" },

              // Merk op dat onderstaande paden (ook) via http benaderd worden. Daarom in
              // eerste instantie nog geen Server.MapPath
              // Sommige staan nog onder /flexfiles/ voor backwards compatibiliteit hoewel
              // logischer is om ze ooit allemaal onder een /photos/ te plaatsen
              menu_image_path:        { v: custpath + "/flexfiles/menu/" },
              prs_image_path:         { v: custpath + "/flexfiles/prs/" },
              res_image_path:         { v: custpath + "/photos/" },
              bes_image_path:         { v: custpath + "/photos/BES/" },
              ins_image_path:         { v: custpath + "/photos/INS/" },
              mrk_image_path:         { v: custpath + "/flexfiles/MRK/" },
              mlds_image_path:        { v: custpath + "/flexfiles/MLD/IMAGES/STDM/" }
            },

    // Laad alle settings uit de database
    loadSET : function(force)
    {
        if ( !force && typeof Application("SET_TM_" + customerId) != "undefined")
        {
            if (typeof CACHE_checkfreshness == "undefined")
                return; // we hebben ze al gecached en we gaan geen freshness controleren
            // Ok, freshness controleren
            var sql = "SELECT MAX(fac_setting_datum) max_date"
                    + "  FROM fac_setting";
            var oRs = Oracle.Execute(sql);
            var max_date = new Date(oRs("max_date").Value);
            oRs.Close();
            var lastCache = new Date(Application("SET_TM_" + customerId));
            if (max_date <= lastCache)
            {   // Dan misschien alleen default.csx compileren
                FCLTHeader.testTemplateCssRefresh();
                return; // Cache is verder vers genoeg
            }
            __DoLog("Forced settings cache reload. Cache was loaded " + toDateTimeString(lastCache, true) + ", last setting is " + toDateTimeString(max_date, true), "#ffff00");
        }

        Application.Lock();

        if (typeof Application("SET_INSTANCE_TIME") == "undefined")
        {
            Application("SET_INSTANCE_TIME") = new Date().getTime(); // Estimated application pool start
            Application("SET_INSTANCE_RANDOM") = shared.random(32);
        }

        var sql = "SELECT fac_setting_name,"
                + "       fac_setting_type,"
                + "       coalesce(fac_setting_pvalue, fac_setting_default) fac_setting_value"
                + "  FROM fac_setting";
        var oRs = Oracle.Execute(sql);
        while (!oRs.Eof)
        {
            var n = oRs("fac_setting_name").Value;
            var t = oRs("fac_setting_type").Value;
            var v = oRs("fac_setting_value").Value;
            if (!v && n in this.cache) // Default waarde is al in ASP gezet
            {
                v = this.cache[n].v;
                t = typeof v;
            }
            Application("SET_T_" + n) = t; // Is voor alle klanten gelijk
            Application("SET_" + customerId + "_" + n) = v;
            //Response.Write(oRs("fac_setting_name").Value + ": " + typeof v);
            oRs.MoveNext();

        }
        oRs.Close();
        // Eigenlijk moet DBLANG ook gewoon een setting worden. Simuleer dat hier
        oRs = Oracle.Execute("SELECT fac_version_lang FROM fac_version");
        Application("SET_T_DB_LANG") = "string"; // Is voor alle klanten gelijk
        Application("SET_" + customerId + "_DB_LANG") = oRs("fac_version_lang").Value;
        oRs.Close();

        Application("SET_" + customerId) = toDateTimeString(new Date());
        Application("SET_TM_" + customerId) = new Date().getTime();
        var sql = "SELECT MAX(adm_tracking_date)"
                + "  FROM adm_tracking"
                + " WHERE adm_tracking_revision IS NOT NULL";
        var oRs = Oracle.Execute(sql);
        Application(customerId + "_ADMTRACK") = new Date(oRs(0).Value).getTime();
        oRs.Close();

        if (force)
            FCLTHeader.generateTemplateCss();
        Application.UnLock();
    },
    // Get setting value
    // finalTry -->geef fatal error bij problemen
    //             (zonder finalTry proberen we eerst de cache te verversen)
    finalTry: false, // semi-globale ipv. parameter om nasty-recursion te voorkomen
    get_setting : function (s, defval, nooverrule)
    {
        if (!nooverrule && s.toLowerCase() in settings.overrule)
            return settings.overrule[s.toLowerCase()];

        var v = Application("SET_" + customerId + "_" + s);
        if (typeof v == "undefined")
            var v = Application("SET_DEFAULT_" + s); // Overrule.DEFAULT uit custenv.wsc

        try
        {
            if (typeof v == "undefined")
            {
                if (s in this.cache)
                    return this.cache[s].v; // Alleen voor perfmon_threshold nodig ...
                else
                    throw { description: "Setting is missing. Perhaps it is time to upgrade the database." };
            }
            var t = Application("SET_T_" + s);
            switch (t)
            {
                case "string":
                    v = v || "";
                    break;
                case "number":
                    v = parseInt(v);
                    break;
                case "float":
                    v = parseFloat(v);
                    break;
                case "boolean":
                    v = (v == "true") || (v == "1") || (v.toLowerCase() == "yes");
                    break;
                case "array":
                    v = v? v.split(",") : [];
                    break;
                case "json":
                    try
                    {
                      v = eval("(" + v + ")");
                    }
                    catch (e)
                    {   // Zou niet mogen gebeuren maar vanwege zeer hoge impact (gebruiker
                        // kan echt niets meer) toch maar onderscheppen.
                      __DoLog("eval van options mislukt: " + e.description, "#FF0000")
                      __DoLog(v);
                      v = "";
                    }
                    break;
            }
            //__Log("Setting " + s + " is type " + t + " en v=" + v + " ("+(typeof v)+")");
            return v;
        }
        catch(e)
        {
            if (settings.finalTry)
            {
                if (typeof defval != "undefined")
                    return defval;
                __DoLog("Could not retrieve setting " + s + "\n" + e.description, "FF0000");
                var txt = "Could not retrieve setting <strong>" + s + "</strong><br>" + e.description;
                var sql = "SELECT MAX(adm_tracking_date)"
                        + "  FROM adm_tracking"
                        + " WHERE adm_tracking_name = 'FAC_SET.SRC'";
                var oRs = Oracle.Execute(sql);
                if (!oRs.Eof)
                {
                    __DoLog("FAC_SET.SRC was last loaded " + toDateTimeString(oRs(0).Value));
                }
                oRs.Close()
                eval("INTERNAL_ERROR_MISSING_SETTING_"+s);
            }
            else
            {   // Kan gebeuren vlak na een upgrade als mensen binnenkomen via SSO of via een API
                // CACHE_checkfreshness is alleen gezet op de voorpagina maar daar komen die twee niet per se langs
                // Met name in de API wil ik CACHE_checkfreshness niet aanzetten: te duur. Daarom robuust bouwen
                settings.finalTry = true;
                settings.loadSET(true);
                return settings.get_setting(s, defval); // laatste poging
            }
        }
    },
    // Set setting value (res_t1 gebruikt dat bijvoorbeeld)
    // Alleen zeer tijdelijk effect voor rest van het bestand
    overrule_setting : function (s, v)
    {
        settings.overrule[s.toLowerCase()] = v;
    }
}

// Shorthand
function S(s, defval)
{
    return settings.get_setting(s, defval)
}
%>
