<% /*
     $Revision$
     $Id$

     File:    fac/fac_header.asp
     Context: iframe vanuit appl/fac/Facilitor.asp

*/
%>
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/productsearch.inc" -->
<%

// Kijk in welke omgeving we volgens de database zitten,
// en toon dat prominent als dat niet de productie is.
var sql = "SELECT COALESCE(fac_version_otap, 'P') otap, "
        + "       fac.getdbversion() dbversion,"
        + "       fac_version_cust, "
        + "       fac_version_schema "
        + "  FROM fac_version";
var oRs = Oracle.Execute(sql);
// Dit kan heel onduidelijke problemen geven met putorders en genexport. Controleer daar hier op.
if (!oRs("fac_version_cust").Value)
    abort_with_warning("fac_version_cust is niet gezet in de database. Doe dat eerst.");

var otap = oRs("otap").value;
if (otap == "P") otap = "";
var dbversion = oRs("dbversion").value;
var schemaversion = oRs("fac_version_schema").Value;
var facilitorversion = FCLTVersion + "@" + dbversion;
oRs.Close();

// function to deliver admin-tracking button at will
function admintracking(obj)
{
  if (user.has("WEB_FACTAB"))
  {
    Response.write("<div id='headerdate' onclick='FcltMgr.openDetail(\"appl/fac/fac_admtracking_search.asp\", L(\"lcl_menu_admtracking_search\"))' title='" + safe.htmlattr(L("lcl_facilitor_appl")) + " " + facilitorversion + "'>" + I("fa-calendar-star fa-2x") + "&nbsp;" + todayString() + "</div>");
  }
}

// function to deliver person search at will
function personsearch(params)
{
  if (!params || !params.touch)
  {
    var authparams = user.checkAutorisation("WEB_PHSRCH", true);
    %><div id="headersuggest"><%
    // Suggest om een persoon te vinden. Gebruikt de scope van de telefoongids
    if (authparams && authparams.PRSreadlevel < 9)
    {
      FCLTpersoonselector("sName_key", "sgPerson", { perslidKey: -1,
        moreinfo: true,
        no_table: true,
        filtercode: "PHB",
        whenEmpty: L("lcl_select_persoon_generic"),
        onChange: "setGlobalUser",
        autlevel: authparams.PRSreadlevel
      });
    }
    %></div><%
  }
}
// function to deliver product search at will
function productsearch(params)
{
  if (!params || !params.touch)
  {
    if (S("show_header_productsearch"))
    {
      Response.Write("<div id=\"headersearch\">");
      FCLTproductsearch ();
      Response.Write("</div>");
    }
  }
}

// functions to deliver loggedin user info at will
function loggedinusername()
{
  Response.write("<div class='username'>" + L("lcl_loggedin_as") + "<span>"+ safe.html(user.naam()) + "</span></div>");
}
function loggedinuserlocation()
{
  Response.write("<div class='userlocation'>" + (user.alg_locatie_key({withcurrent:true})>-1 ? I("fa-map-marker fa-2x")+(new Locatie(user.alg_locatie_key({withcurrent:true})).locatie_string()) : "") +"</span></div>");
}
function avatar()
{
  var info = user.photoinfo();
  if (info.isDefault)
  {
    var alle_namen = user.naam().split(" ");
    var initialen = alle_namen[0].substring(0,1);
    if (alle_namen.length > 1)
    {
      initialen += alle_namen[alle_namen.length - 1].substring(0,1);
    }
    Response.write("<div class='circle userphoto' title='" + L("lcl_avatardetails") + "'><span class='initials'>" + safe.html(initialen.toUpperCase()) + "</span></div>");
  }
  else
  {
    Response.write("<div class='userphoto' title='" + L("lcl_avatardetails") + "'><img id='photo' alt='" + safe.htmlattr(L("fac_profiel")) + " " + safe.htmlattr(L("lcl_photos")) + "' class='profile' src='" + safe.htmlattr(info.photopaththumb) + "'></div>");
  }
}

// function to deliver profile menu option at will
function profilePage()
{
  Response.write("<div class='profile'onclick='myInfo()'>" + I("fa-user fa-2x") + "&nbsp;" + L("lcl_prs_myprofile") + "</div>");
}

// function to deliver help menu button at will
function helppage()
{
  if (S("helppage_url") != "") {
    Response.write("<div id='headerhelp' onclick='openHelp()' title='"+L("lcl_help")+"'>" + I("fa-question", {"fastyle" : "far"}) + "</div>");
  }
}

// function to deliver language toggle buttons at will
function langtoggle()
{
  if (S("language_toggles").length > 1)
  {
    Response.write("<div id='langtoggle'>");
    for (lang in S("language_toggles"))
    {
      var code = S("language_toggles")[lang];
      var desc = lcl.languages[code];
      Response.write("<img onClick='changeLanguage(\"" + code + "\")'; title='" + safe.htmlattr(desc) + "' alt='" + safe.htmlattr(desc) + "' src=../pictures/"+ code + ".png>");
    }
    Response.write("</div>");
  }
}

function RegisterMobileOption()
{
  if ((S("mobile_enabled") & 1)) {
    Response.write("<div id='RegisterMobileOption' onClick='RegisterMobile()'>");
    Response.write("<div>" +  I("fa-mobile-signal-out fa-2x") + "&nbsp;" + L("lcl_qrc_authenticatie") + "</div>");
    Response.write("</div>");
    }
}

// function to change the interface at will; to be deprecated
function toggleInterfaceMobile()
{
  if ((S("mobile_enabled") & 1)) {
    Response.write("<div id='loadToggleInterfaceMobile' onClick='loadToggleInterfaceMobile()'>");
    Response.write("<div>" +  I("fa-mobile fa-2x") + "&nbsp;" + L("lcl_mobile_mobilemode") + "</div>");
    Response.write("</div>");
    }
}

function toggleInterfaceTouch()
{
    Response.write("<div id='loadToggleInterfaceTouch' onClick='loadToggleInterfaceTouch()'>");
    Response.write("<div>" + I("fa-tablet fa-2x") + "&nbsp;" + L("lcl_mobile_classicmode") + "</div>");
    Response.write("</div>");
}

function toggleInterfaceDesktop()
{
    Response.write("<div id='loadToggleInterfaceDesktop' onClick='loadToggleInterfaceDesktop()'>");
    Response.write("<div>" + I("fa-desktop fa-2x") + "&nbsp;" + L("lcl_desktop_classicmode") + "</div>");
    Response.write("</div>");
}

function Werklocatie()
{
  // Fast check to see if we have anything to do with geographics, else do nothing at all
  var sql= "SELECT 1 FROM alg_locatie WHERE alg_locatie_verwijder IS NULL AND (alg_locatie_vervaldatum > SYSDATE OR alg_locatie_vervaldatum IS NULL) AND ROWNUM = 1";
  var oRs = Oracle.Execute(sql);
  var anygeo = !oRs.eof;
  oRs.close();
  if (anygeo)
  {
    var xfunc = user.func_enabled("*", null, null, user_key, null, true);
    var canChange = (xfunc.canWrite("WEB_PROFIL")
                  || xfunc.canWrite("WEB_PRSMAN")
                  || xfunc.canWrite("WEB_PRSUSE"));
    if (canChange)
    {
        var myPrs = prs.prs_perslid(user_key, { withWL: true }); // geeft ook alle informatie
        var werklocatieLabel = myPrs.werklocatie.alg_locatie_key ? myPrs.werklocatie.aanduiding : L("lcl_where_am_i");
        Response.write("<div class='truncate nowrap' title='" + safe.htmlattr(werklocatieLabel) + "' onClick='editWerklocatie()'>");
        Response.write(I("fa-map-marker fa-2x") + "&nbsp;" + safe.html(werklocatieLabel));
        Response.write("</div>");
    }
  }
}

// function to deliver logoff button at will
function headerlogout()
{
  Response.write("<div id='headerlogout' onclick='logOff()'>" + I("fa-sign-out fa-2x") +"&nbsp;" + L("lcl_logoff") + "</div>");
}

// function to deliver touchsearch button at will
function touchsearch(params)
{
  if (params && params.touch)
  {
    Response.write("<div id='touchsearch' onclick='toProdsearch();'>" + I("fa-search fa-2x") + L("lcl_menu_fe_search") + "</div>");
  }
}

function todayString() {
    var d=new Date()

    return calendar_names.days[d.getDay()] + "&nbsp;" + d.getDate() + "&nbsp;"
            + calendar_names.months[d.getMonth()] + "&nbsp;" + d.getFullYear();
}

function generateHeader()
{
%>
<script type="text/javascript">
    function setGlobalUser (prs_key, prs_naam) {
        FcltMgr.setCaller({prs_key: prs_key, prs_naam: prs_naam});
        if (prs_key > 0)
            FcltMgr.openDetail("appl/fac/fac_user.asp?prs_key=" + prs_key);
    }
<%
    // Stukje meta consistentie controle op invalid objecten. Geeft regelmatig problemen
    // nadat ergens een dump is ververst.
    if (user.has("WEB_FACTAB"))
    {
        var sql = "SELECT COUNT(*) cnt"
                + "  FROM user_objects"
                + " WHERE status <> 'VALID'";
        var oRs = Oracle.Execute(sql);
        var cnt = oRs("cnt").Value;
        oRs.Close();
        if (cnt > 0)
        {   // probeer het automatisch op te lossen.
            __DoLog("Detected {0} invalid object(s)\nCalling DBMS_UTILITY.COMPILE_SCHEMA".format(cnt), "#f88");
            Oracle.Execute("BEGIN DBMS_UTILITY.COMPILE_SCHEMA(USER, FALSE); END;");
            // De LISTAGG kan er uit klappen als hij langer dan 4000 karakters wordt.
            // Dan heb je *zo* veel niet compileerbare invalid objecten dat je wel grotere problemen hebt denk ik.
            var sql = "SELECT COUNT(*) cnt, "
                    + "       LISTAGG(object_type || ' ' || object_name, CHR(13) || CHR(10)) WITHIN GROUP (ORDER BY object_name) objs"
                    + "  FROM user_objects"
                    + " WHERE status <> 'VALID'";
            oRs = Oracle.Execute(sql);
            var cnt2 = oRs("cnt").Value;
            var objs = oRs("objs").Value;
            oRs.Close();
            var txt = "Detected {0} invalid database object(s) in {1}@{2}.".format(cnt, Oracle.RealConnection.Properties("User Name"), Oracle.RealConnection.Properties("Data Source Name"));
            __DoLog("After compiling {0} invalid object(s) left:\n{1}".format(cnt2, objs||""), cnt2>0?"#f00":null);
            if (cnt2 == 0)
                txt += "\nAn automatic recompile solved that for you.";
            else
            {
                if (cnt2 == cnt)
                    txt += "\nAn automatic recompile did not help.";
                else
                    txt += "\nAfter automatic recompiling there are still {0} invalid objects remaining".format(cnt2);
                if (cnt2 < 10) // De logging heeft eventueel de hele lijst
                    txt += "<div style='margin-left:1em'>{0}</div>".format(safe.html(objs));
                txt = txt + "\nClick to <button onclick='show_errors()'>view all errors</button>";
            }
            %>
              function show_errors()
              {
                  FcltMgr.openDetail("appl/mgt/mgt_genericsql.asp?autoexec=1&sql=SELECT%20*%20FROM%20USER_ERRORS%20ORDER%20BY%20NAME,TYPE,SEQUENCE", 'Errors');
              }
              $(function () { FcltMgr.alert("<%=safe.jsstring(txt.replace(/\n/g,'<br>'))%>", { ishtmlsafe: true }) });
            <%
        }
    }

    if (S("puo_loglevel") > 1 && Application("otap_environment") != "O" && user.has("WEB_FACTAB"))
    {
        %>
          $(function () { $.toast({ text: "<%="Warning: puo_loglevel={0}".format(S("puo_loglevel"))%>", icon: "warning", position : 'top-left'}); });
        <%
    }
    if (Application("otap_environment") == "O" || __Logging > 0)
    {%>
        function startLogging(silent)
        {
            if (!silent)
                $.toast({ text: "Logging is now on", icon: "success", position : 'top-left'});
            $("#loggingon").hide();
            $("#loggingoff").show();
        }
        function stopLogging()
        {
            $.post("../shared/wislog.asp?logging=0");
            $.toast({ text: "Logging is now off", icon: "success", position : 'top-left'});
            $("#loggingoff").hide();
            $("#loggingon").show();
        }
     <%
        if (__Logging > 0)
            Response.Write("$(function() {startLogging(true) });");
    }
%>
</script>

<div id="headerblok" style='height:100%'>
<%
    if (Application("otap_environment") == "O" || __Logging > 0)
    {%>
        <div id="loggers">
            <button id='loggingoff' onclick='stopLogging()'>Stop logging</button>
            <a href='../shared/wislog.asp?logging=1' target='_blank'><button id='loggingon' onclick='startLogging()'>Start logging</button></a>
            <% if (Application("otap_environment") == "O") { %>
                <a href='./fac_StreamFile.asp?logger=0' target='_blank'><button id='loggingshow'>Open logging</button></a>
            <% } %>
        </div>
     <%
    }
    if (Session("org_user_key") > 0)
    {
        var other_key = parseInt(Session("org_user_key"), 10);
        var other = new Perslid(other_key);
        Response.Write("<div id='userimperson'>" + L("lcl_impersonate_active").format(safe.html(other.naam()) + "</div>"));
    }
    else if (L("lcl_facilitor_header_prefix") || otap)
    {
        Response.Write("<div id='headerprefix'>" + otap+" "+L("lcl_facilitor_header_prefix") + "</div>");
    }

  if (user_key != -1) {


    if (parseInt(schemaversion,10) < parseInt(FCLTMinDatabaseSchema,10))
    {
        var schematxt = "Need DB" + FCLTMinDatabaseSchema + " have DB" + schemaversion;
        Session("badschema") = schematxt;
        if (user.has("WEB_FACTAB"))
            Response.Write("<div id='badschema' title='"+Oracle.RealConnection.Properties("User Name")+'@'+Oracle.RealConnection.Properties("Data source")+"'>BAD SCHEMA. " + schematxt +"</div>");
        // else: gewone users niet direct lastigvallen.
        //       tijdens een (nieuw ingrijpende) hot-upgrade staan we het gewoon eventjes toe.
    }

   generateHeaderFunctions();
}
   %></div>
   <%
}
function generateHeaderFunctions (params)
{
    %>
  <script type="text/javascript">

    function openHelp()
    {
        if (FcltMgr._pageManager.name == "tabbedManager")
            var src = FcltMgr._pageManager._activeTab().src;
        else
            src = window.location.href;

        var url = 'appl/fac/help.asp?url='+escape(src);
        // Altijd in new window om cross-domain problemen te voorkomen
        FcltMgr.windowopen('../../'+url);
    }

    function myInfo()
    {
      FcltMgr.openDetail('appl/fac/fac_user_info.asp?');
    }

    function toMobile()
    {
          window.localStorage.setItem("interface", "mobile");
          top.location.href = rooturl + "/?interface=mobile";
    }

    function toDesktop()
    {
          window.localStorage.setItem("interface", "desktop");
          top.location.href = rooturl + "/?interface=desktop";
    }

    // prodsearch voor touch
    function toProdsearch()
    {
        FcltMgr.openDetail('appl/fac/prodsearch.asp');
    }

    function logOffCallback(json, textStatus)
    {
        parent.location.href = json.return_url;
    };

    function logOff()
    {
      var data = {};
      <% protectRequest.dataToken("data"); %>
      $.post("../aut/LogOff.asp",
             data,
             FcltCallbackAndThen(logOffCallback),
             "json");
    }

    function changeLanguage(lang)
    {
      var data = {};
      <% protectRequest.dataToken("data"); %>
      $.post("./set_language.asp?lang="+lang,
             data,
             FcltCallbackRefresh,
             "json");
    }

    //function prs_connectmobile()
    function RegisterMobile()
    {
        var url = "../prs/prs_perslid_qr.asp";
        FcltMgr.openModalDetail(url, L("lcl_qrc_authenticatie"));
    }

    function loadToggleInterfaceMobile()
    {
      var current_interface = window.localStorage.getItem("interface");
      window.localStorage.setItem("interface", (current_interface == "touch" ? "touch" : "mobile"));
      var url = rooturl + "?interface=" + (window.localStorage.getItem("interface"));
      top.location.href = url;
    }

    function loadToggleInterfaceTouch()
    {
      var current_interface = window.localStorage.getItem("interface");
      window.localStorage.setItem("interface", (current_interface == "mobile" ? "mobile" : "touch"));
      var url = rooturl + "?interface=" + (window.localStorage.getItem("interface"));
      top.location.href = url;
    }

    function loadToggleInterfaceDesktop()
    {
      var current_interface = window.localStorage.getItem("interface");
      window.localStorage.setItem("interface", (current_interface == "touch" ? "touch" : "desktop"));
      var url = rooturl + "?interface=" + (window.localStorage.getItem("interface"));
      top.location.href = url;
    }

    function editWerklocatie()
    {
        FcltMgr.openModalDetail("../prs/prs_move_huidigewerkplek.asp?prs_key=<%=user_key%>");
    }

    $(function()
    {
        setTimeout(function () {
          $("#headersearch .productklikker").on('click', function() {
              $("form#p").trigger("submit");
          });
        });
    });

  </script>
  <div id="headerfunctions">
        <%personsearch(params);%>
        <%productsearch(params);%>
        <%touchsearch(params);%>
        <%helppage();%>
        <%avatar();%>
    <!-- USROPTIONS  -->
  <script type="text/javascript">
    $(function() {
      $("div.userphoto").on("click", function(e)
                                     {
                                       e.stopPropagation();
                                       $("div#useroptions").toggle();
                                     });
      $("body").on("click", function(e)
                            {
                              if ($("div#useroptions").is(":visible"))
                                $("div#useroptions").hide();
                            });
    });
  </script>
    <div id="useroptions" style="display: none">
<%        admintracking({ trspan: true });
          langtoggle();
          profilePage();
          if (Session("interface") != "mobile")  RegisterMobileOption();
          if (user.has("WEB_PRSSYS"))
          {
            if (Session("interface") != "mobile")   toggleInterfaceMobile();
            if (Session("interface") != "touch")    toggleInterfaceTouch();
            if (Session("interface") != "desktop")  toggleInterfaceDesktop();
          }
          Werklocatie();
          headerlogout(); %>
    </div>
  </div>
<%
  }
%>
