<% /*
     $Revision$
     $Id$

     File:               shared/header.inc
     Description:        Generieke serverside header functie.
                         Stelt de HTML header samen op basis van de meegegeven eisen.

     Parameters:         params:
                            title
                            outputmode  (default 0=screen)
                            plugins []
                            js []
     Context:           Eenmalig per ASP, automatisch via shared.inc
     Result:
     Note:              Gebruikt veel de globale rooturl die tegenwoordig autodetect is
                        Deprecated aanroepen als volgt kunnen gewoon verwijderd worden
                            FCLTHeader.Generate({ root: "../../appl/" });
                            FCLTHeader.Set({root: "../../../appl/"});

*/

/************************************************************/
_jqueryver = "jquery-1.11.3"; // Pas ook expired.asp aan en FacmgtTools.asp
_jqueryuiver = "jquery-ui-1.11.4.custom";
_jqueryuiver_css = "jquery-ui.custom";

if (typeof FCLTHeader != "undefined")
{
    Response.Write("install.inc is indirect dubbel included. Dat mag niet.")
    Response.End;
}

FCLTHeader =
{
    _plugins : [],

    _params: { title: getQParam("_titel_", null),
                outputmode: 0,
                plugins: [], js: [], css: [], extrahead: [] },

    _myPush: function (arr, itm)
             {
                 var j;
                 for (j = 0; j < arr.length; j++)
                 {
                     if (typeof itm == "string" && arr[j].toLowerCase() == itm.toLowerCase()
                         || arr[j] == itm)
                         return; // hij is er al
                 }
                 arr.push(itm);
             },

    Title: function(title)
    {
        // TODO: Titel van het tabje zetten.
        FCLTHeader._params.title = title;
    },

    Set: function(params)
    {
        var i;
        for (i in params)
            FCLTHeader._params[i] = params[i];
    },

    Requires: function(params)
              {
                  if (JSON_Result)
                    __SafeLog("<span style='background-color:#0ff'>JSON_Result staat aan, dan is FCLTHeader.Requires erg onlogisch.</span>");

                  if (!params) params = {};

                  var i, j;
                  // 'Explodeer' de plugins naar onderdelen
                  if (params.plugins)
                      for (i = 0; i < params.plugins.length; i++)
                      {
                          this._plugins[params.plugins[i]] = true;
                          var i;
                          switch (params.plugins[i])
                          {
                              case "jQuery":
                                  FCLTHeader.Requires({js: ["jQuery.js", "FcltJquery.js"]});
                                  FCLTHeader.Requires({js: ["jquery.toast.min.js"],
                                                       css: [rooturl + "/appl/localscripts/jquery.toast.min.css"]});
                                  break;
                              case "suggest":
                                  FCLTHeader.Requires({js: [rooturl + "/appl/shared/suggest/suggest.js"],
                                                      css: [rooturl + "/appl/shared/suggest/suggest.css"]});
                                  break;
                              case "kenmerk":
                                  FCLTHeader.Requires({js: ["jquery-ui.js", "modal_kenmerken.js", rooturl + "/appl/shared/kenmerk_js.asp"],
                                                      css: []});
                                  break;
                                  break;
                              default: eval("INTERNAL_ERROR_PLUGIN_"+params.plugins[i]+"_IS_ONBEKEND");
                          }
                      }

                  if (params.js)
                      for (i = 0; i < params.js.length; i++)
                      {
                        if (params.js[i].toLowerCase() != "fcltmgr.js")
                          FCLTHeader._myPush(FCLTHeader._params.js, params.js[i]);
                      };

                  if (params.css)
                      for (i = 0; i < params.css.length; i++)
                      {
                          FCLTHeader._myPush(FCLTHeader._params.css, params.css[i]);
                      };

                  if (params.extrahead)
                    FCLTHeader._myPush(FCLTHeader._params.extrahead, params.extrahead);
              },

    _fso:Server.CreateObject("Scripting.FileSystemObject"),
    AddTimeStamp: function(fPath, isOptional)
        {
            fPath = fPath.toLowerCase(); // canonical can improve caching
            if (fPath.indexOf(rooturl.toLowerCase()) == 0)
                fPath = rooturl + fPath.substring(rooturl.length); // Afblijven van rooturl-deel, cookies verdwijnen anders
            try
            {
                var f = this._fso.GetFile(Server.MapPath(fPath));
                var ts=new Date(f.DateLastModified);
                return fPath + "?" + Math.floor(ts.getTime()/1000);
            }
            catch(e)
            {
                if (isOptional)
                    return false; // niet erg
                Response.Write("<p><b>Internal error: kan bestand " + fPath + " niet vinden/openen</b></p>");
                Response.Write(e.description);
                Response.End;
            }
        },
    AddStylesheet: function(fPath, isOptional)
        {
            var timedpath = this.AddTimeStamp(fPath, isOptional);
            if (timedpath)
            {
                %>
         <link rel="stylesheet" href="<%=timedpath%>" type="text/css"><%
            }
        },
    _templateCss: rooturl + "/temp/" + customerId + ".css",

    // params
    //   cssmode: 0: is normale customer css
    //            1: is default css
    //            2: concept css uit params.csstemplate
    Generate: function (params)
    {
        if (!params) params = {};

        if (params.outputmode == 2 || params.outputmode == 6) // Excel (incl. flex)
        {
          if (S("excel_mode") == 1)
          {
            params.outputmode = 4;
          }
          else
          {
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader ("content-disposition", "inline; filename=facilitor.xls");
            Response.CacheControl = "private"; // UWVA#38253 : Anders problemen met IE8
%>     <meta http-equiv="Content-Type" content="text/html;charset=<%=Response.Charset%>"><%
            return; // Excel is heel kaal
          }
        }

        if (params.outputmode == 4) // csv
        {
          Response.ContentType = "text.csv";
          Response.AddHeader ("content-disposition", "attachment; filename=facilitor.csv");
          return; // csv is heel kaal
        }

%>     <meta http-equiv="Content-Type" content="text/html;charset=<%=Response.Charset%>">
     <%=S("http_meta_head")%>
     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
 <%
         // FSN#14103 Voorkom back-button problemen
         // user_lang en rooturl resp. voor date.js en FcltMgr.js
%>         <script type="text/javascript">
<% if (!params.mobile) { %>
                window.history.forward(1);
<% } %>
                var user_lang = "<%=safe.jsstring(user_lang)%>";
                var rooturl = "<%=safe.jsstring(rooturl)%>";
<% if (Response.Expires <= 0) { /* niet als gecached, te irritant */ %>
                var userId = "<%=safe.jsstring(customerId)+"/"+user_key%>";
<% } %>
                var LCL = {}; // Bouw het clientside LCL-array voor teksten die in js gebruikt worden
                var RVT_token = "<%=safe.jsstring(protectRequest.theToken())%>";
<%          lcl.buildClientLCL();
            var filters = getQParam("fcltfilters", "");
            if (filters)
            {
                Response.Write("\nvar fcltfilters = '" + safe.jsstring(filters) + "';");
            }%>
           </script>
<%
         if (FCLTHeader._params.title)
         {
           %><title><%=safe.html(FCLTHeader._params.title)%></title><%
         }
         // FcltMgr.js altijd
%>         <script type="text/javascript" src="<%=this.AddTimeStamp(rooturl + '/appl/LocalScripts/FcltMgr.js')%>"></script><%

         if (params.outputmode == 1 || params.outputmode == 5) {       // Printen is vrij kaal
            FCLTHeader.AddStylesheet(rooturl+"/appl/shared/default-print.css");
            if (getQParam('autosortby', "") || getFParam('autosortby', "")) // Deze twee wel nodig bij printen
            {
                %><script type="text/javascript" src="<%=this.AddTimeStamp(rooturl+'/appl/LocalScripts/' + _jqueryver + '.min.js')%>"></script><%
                %><script type="text/javascript" src="<%=this.AddTimeStamp(rooturl+'/appl/LocalScripts/sorttable.js')%>"></script><%
            }
            return;
         }
         var theme = // S("cssfordesktop") ||
                     "/appl/Localscripts/theme/" + _jqueryuiver_css + ".min.css";
         FCLTHeader.AddStylesheet(rooturl + theme);
         FCLTHeader.AddStylesheet(rooturl + "/appl/img/css/font-awesome.min.css");

         for (var i = 0; i < FCLTHeader._params.css.length; i++)
         {
             var pad = FCLTHeader._params.css[i];
             if (pad.indexOf("/") == -1)
                 pad = rooturl+"/appl/shared/" + pad;
             FCLTHeader.AddStylesheet(pad);
         }
         if (params.mobile)
            FCLTHeader.AddStylesheet(custpath + "/mcust.css", true)
         else
         {
            this.testTemplateCssRefresh();
            if (!this._fso.FileExists(Server.MapPath(this._templateCss)))
                this.generateTemplateCss();
            var agent = String(Request.ServerVariables("HTTP_USER_AGENT"));
            if (agent.indexOf("MSIE") > 0)
            {
                Response.Write("\n<!--[if lte IE 8]>");
                    FCLTHeader.AddStylesheet(rooturl+"/appl/shared/ie-fix.css"); // Alleen IE8 en ouder
                Response.Write("\n<![endif]-->");
            }

            // 0=normaal, 1=kale default, 2=concept
            var previewfile = rooturl + "/temp/" + customerId + "_concept.css";
            switch (params.cssmode)
            {
                case 2:
                    this.generateTemplateCss(params.csstemplate, previewfile);
                    FCLTHeader.AddStylesheet(previewfile);
                    break
                case 1:
                    this.generateTemplateCss(FCLTHeader.defaultTemplate, previewfile);
                    FCLTHeader.AddStylesheet(previewfile);
                    break
                default:
                    FCLTHeader.AddStylesheet(this._templateCss, true); // Template, optional
            }
            if (device.test(device.isTouch))
                FCLTHeader.AddStylesheet(rooturl+"/appl/shared/touch.css");
            if ((params.cssmode || 0) == 0)
            {
                FCLTHeader.AddStylesheet(custpath + "/cust.css", true); // optional
                FCLTHeader.AddStylesheet(custpath + "/custenv.css", true); // optional, handig voor testomgevingen
            }
         }
         for (var i = 0; i < FCLTHeader._params.js.length; i++)
         {
             var pad = FCLTHeader._params.js[i];
            if (typeof Session("Logging")=="undefined" || Session("Logging") == 0)
            {
                 if (pad.toLowerCase() == "jquery.js")
                   pad = _jqueryver + ".min.js";
                 if (pad.toLowerCase() == "jquery-ui.js")
                 {
                   pad = _jqueryuiver + ".min.js";
                 }
            }
            else
            {
                 if (pad.toLowerCase() == "jquery.js")
                    pad = _jqueryver + ".js";
                 if (pad.toLowerCase() == "jquery-ui.js")
                   pad = _jqueryuiver + ".js";
            }

             if (pad.indexOf("/") == -1)
                 pad = rooturl+"/appl/LocalScripts/" + pad;
%>
         <script type="text/javascript" src="<%=this.AddTimeStamp(pad)%>"></script><%
         }

         for (var i = 0; i < FCLTHeader._params.extrahead.length; i++)
         {
             FCLTHeader._params.extrahead[i]();
         }

         // IE8 heeft moeite met de :before van font-awesome bij gecachte pagina's
         // Dit lijkt te helpen
         // http://stackoverflow.com/a/10209030/569090
         var agent = String(Request.ServerVariables("HTTP_USER_AGENT"));
         if (agent.indexOf("MSIE") > 0)
         {   %>
              <!--[if lte IE 8]>
              <script type="text/javascript">
                if (window.$)
                $(function () {
                    var sheets = document.styleSheets;
                    for(var s = 0, slen = sheets.length; s < slen; s++) {
                        sheets[s].href = sheets[s].href;
                    }
                });
                </script>
              <![endif]-->
        <% }
        if (S("fac_tabframes") > 0)
        {
            %>
              <script>
                if (window.$ && window.iface)
                    $(iface.tabFrames);
                </script>
            <%
        }
     },

    defaultTemplate : // De defaults
    {
        fontfamily: "Tahoma, Verdana, Arial, Helvetica, sans-serif",
        textcolor: "#333",
        backgroundcolor: "#fffffe",
        headerimage: "../appl/pictures/banner.png",
        loginimage: "../appl/pictures/loginbg.jpg",
        blockheaderbackgroundcolor: "#fffffe",
        blockheadercolor: "#000",
        buttonbackgroundcolor: "#78C8E6",
        buttoncolor: "#fff",
        buttonhoverbackgroundcolor: "#004f80",
        buttonhovercolor: "#fff",
        dividercolor: "#ddd",
        frameheaderbackgroundcolor: "#78C8E6",
        frameheadercolor: "#ffffff",
        headerbackgroundcolor: "#fff",
        headercolor: "#666",
        iconbackgroundcolor: "rgba(255,255,255,0.15)",
        iconcolor: "#fff",
        iconhoverbackgroundcolor: "#004f80",
        iconhovercolor: "#ffffff",
        icontextcolor: "#ffffff",
        inlineactionbackgroundcolor: "#ffffff",
        inlineactioncolor: "#f26522",
        labelbackgroundcolor: "#78C8E6",
        labelcolor: "#333",
        linkcolor: "#2222cc",
        linkhovercolor: "#f26522",
        logincolor: "#000000",
        menubackgroundcolor: "#f8f8f8",
        menuitembackgroundcolor: "#fff",
        menuitemcolor: "#000",
        menuitemhovercolor: "#e6effa",
        menukophoverbackgroundcolor: "#b6dffa",
        menukophovercolor: "#004f80",
        mgtmenubackgroundcolor: "transparent",
        mgtmenucolor: "#004f80",
        mywelcomebackgroundcolor: "#78C8E6",
        mywelcomecolor: "#fff",
        persmenubackgroundcolor: "transparent",
        persmenucolor: "#004f80",
        portalkopcolor: "#333",
        profmenubackgroundcolor: "transparent",
        profmenucolor: "#004f80",
        requiredbordercolor: "#a00000",
        showblockheaderbackgroundcolor: "#fafafa",
        tableheaderbackgroundcolor: "#004f80",
        tableheadercolor: "#fff"
    },

    // tpl en cssfile worden alleen gebruikt bij concept/preview, anders zijn ze leeg
    generateTemplateCss : function(tpl, cssfile)
    {
        if (typeof tpl == "undefined")
            var custtemplate = S("csstemplate");
        else
            var custtemplate = tpl;

        var outfname = Server.MapPath(cssfile || this._templateCss);
        __Log("Regenerating template {0}".format(outfname));

        var inFile = this._fso.OpenTextFile(Server.MapPath(rooturl + "/appl/shared/default.csx"));

        var inCss = inFile.ReadAll();
        for (itm in this.defaultTemplate) // vervang alle bekende variabelen
        {
            var val = this.defaultTemplate[itm];
            if (itm in custtemplate)
                val = custtemplate[itm];
            var regexp = new RegExp("\\=\\="+itm+"\\=\\=", 'gi');
            inCss = inCss.replace(regexp, val);
        }

        // http://stackoverflow.com/questions/5522733/removing-comments-in-javascript-using-ruby
        inCss = inCss.replace(/\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//ig, ""); // Verwijder alle commentaar
        inCss = inCss.replace(/\n\s+/g, "\n"); // alle leading spaties schrappen
        inCss = inCss.replace(/\n\n/g, "\n"); // lege regels schrappen

        try
        {
            var outFile = this._fso.OpenTextFile(outfname, 2, true); // 2=write, true=create?
        }
        catch (e)
        {
            Response.Write("ERROR: Unable to write " + outfname + "<br>" + e.description);
            Response.Write("<br>Make sure IUSR user has modify permissions to this folder on the webserver");
            Response.End;
        }
        outFile.WriteLine("/*********************************");
        outFile.WriteLine(" * GENERATED FILE, DO NOT MODIFY *");
        outFile.WriteLine(" *********************************/");
        outFile.Write(inCss);

        __Log("Template file {0} has been generated.".format(outfname));
        inFile.Close();
        outFile.Close();
    },
    // Kijk of default.csx nieuwer is dan onze temp-css. Dan verversen
    testTemplateCssRefresh: function ()
    {
       if (this._fso.FileExists(Server.MapPath(this._templateCss)))
       {
           var fcss = this._fso.GetFile(Server.MapPath(this._templateCss));
           var tcss = new Date(fcss.DateLastModified);
       }
       else
           tcss = 0;
       var fcsx = this._fso.GetFile(Server.MapPath(rooturl + "/appl/shared/default.csx"));
       var tcsx = new Date(fcsx.DateLastModified);
       var hinc = this._fso.GetFile(Server.MapPath(rooturl + "/appl/shared/header.inc"));
       var tinc = new Date(hinc.DateLastModified);
       if (tcsx > tcss || tinc > tcss)
       {
           __Log("{0} is older ({1}) than default.csx ({2}), refreshing it.".format(this._templateCss, toDateTimeString(tcss, true), toDateTimeString(tcsx, true)));
           this.generateTemplateCss();
       }
    }
}
%>
