<% /*
     $Revision$
     $Id$

     File:          iface.inc
     Description:   generic interface functions for buttons and maybe more
*/ %>
<!-- #include file="../img/icons.inc" -->

<%
if (JSON_Result)
    __SafeLog("<span style='background-color:#0ff'>JSON_Result staat aan, dan is iface.inc includen erg onlogisch.</span>");

FCLTHeader.Requires({ plugins: ["jQuery"], js: ["iface.js"]})
var isPrinting = getQParamInt("print", 0) == 1;

function CreateButton(tekst, onClick, btn, params) //akey, id, params)
{
  btn = btn || {};
  params = params || {}; // voor alle buttons
  var hasIcon = (params.showIcons || btn.showIcon) && btn.icon;
  var cls = (params.isDialog? "dialog ": "") + (hasIcon? "hasIcon ": "") + (btn.xclass ? btn.xclass : "");
  if (!params.isDialog && tekst)
  {
    if (!btn.tooltip) // Alles voor de eerste \n komt in de button, alles erna in de tooltip
    {
        var arr = tekst.split("\n");
        tekst = arr[0];
        // In de tooltip hoeven we de tekst niet (ook) nog een keer te tonen
        // Let wel: Omdat we ooit responsive op een klein scherm de teksten
        //          onderdrukken dan moet de tooltip toch blijven
        //arr.shift(); // eerste er af
        btn.tooltip = arr.join("\n");
    }
  }
  var display = params.display || 'block';
  %><li <%=params.vertical? ' style="display:'+display+'"' : ''%> class='<%= cls %>'
  <%=(btn.tooltip?' title="' + safe.htmlattr(btn.tooltip) + '"' : "")%>
  <%=(btn.singlepress?" singlepress=1":"")%>
  onClick="iface.button.click(event, this)"
  fcltClick="<%=onClick%>"
  <%= btn.id != null ?'id="' + btn.id + '"' : '' %>><%
  if (hasIcon) {
      Response.Write(I(btn.icon) + "&nbsp;");
      if (params.isDialog && btn.tooltip)
      {
          %><div class="dialogtext"><%= btn.tooltip %></div><%
      }
      else
      {
          if (tekst)
            Response.write("<span class='icontxt'>"+safe.html(tekst)+"</span>");
      }
  } else {
      Response.write(safe.html(tekst));
  }
  %></li><%
}

// Buttons is een hash
// Velden: title, action en id
// params: {    showIcons   : false    boolean om (alleen) de icons te tonen en niet de teksten
//              showText    : true     boolean om de tekst te doen
//              vertical    : false
//              autoshowOnly: false
//              autoshow    : false
//         }
var HAMBUTTONS = ["print.png", "email.png", "csv.png", "fa-print", "excel.png", "fa-table", "fa-refresh", "page_refresh.png", "legenda.png"];
function CreateButtons(buttons, params)
{
  params = params || {};
  if (typeof params.showText == "undefined") params.showText = true;

  if (buttons)
  {
%>  <div id="buttons" class="<%= params.vertical?'vertical ':''%> <%= params.isDialog?'dialog':''%>">
      <ul onclick="FcltMgr.stopPropagation(event);">
<%
      if (1&&params.entersubmit)
      { // too bad this hidden button takes up some space, especially with the vertical buttons
        %><li class="hiddenbutton"><input type="submit" style="height:0;width:0"></li><%
      }
      var hambuttons = [];
      for (var i=0; i< buttons.length; i++)
      {
          var btn = buttons[i];
          if (!params.autoshowOnly || btn.autoshow)
          if (!params.isModal && inArray(btn.icon, HAMBUTTONS))
            hambuttons.push(i)
          else
            CreateButton(btn.title, btn.action, btn, params);
      }
      if (hambuttons.length)
      {
        var btn = { icon: "fa-bars", tooltip: L("lcl_more"), id: "printhamburger",
                    action: "$('li.byHamburger').toggleClass('hidden');FcltMgr.resized();" }
        CreateButton(null, btn.action, btn, params );

        // z-index floating header = 10, so z-index hamburger = 11
        Response.write("<div id=\"buttons\" class=\"hambdropdown\"><ul onclick=\"FcltMgr.stopPropagation(event);\">");
        for (var x in hambuttons) {
            var btn = buttons[hambuttons[x]];
            btn.xclass = 'hidden byHamburger';
            CreateButton(btn.title, "$('li.byHamburger').toggleClass('hidden');" + btn.action, btn, { showIcons: true, vertical: true });
        }
        Response.write("</ul></div>");
      }
 %>
      </ul>
    </div><div id='layoutfixer' style='clear:right'></div><%
  }
}


// to group fields within an edit page
var __blockactive__ = false;
function BLOCK_START(id, title, params) {
    params = params || {};
     if (__blockactive__) ERROR_NESTED_BLOCK_START_DETECTED;
    __blockactive__ = true;
%><!-- BLOCK_START <%=id%> -->
<div id="<%=id%>" class="fcltblock" <%=params.hidden? ' style="display:none"' : ''%>>
   <div class="fcltblockhead"><%=title%>
<%
        if (params.buttons && params.buttons.length)
        {
          %><div class="blockbuttoncontainer" style="float:right;"><%
          CreateButtons(params.buttons, { showIcons: true} );
          %></div><%
        }
%>
   </div>
   <div class="inside" id="<%=id%>List">
      <table class="fcltblocktab" width="100%"><%
}
function BLOCK_END() {
    if (!__blockactive__) ERROR_BLOCK_END_WITHOUT_BLOCKSTART;
    __blockactive__ = false;
%>      </table>
   </div>
</div>
<!-- BLOCK_END --><%
}

/* optional params: { title: "Titel",
                      initHeight: "400px", // grove instelling
                      initHide : true,
                      refreshOnClose: true, // zet oorspronkelijk src terug na FcltClose van child
                      FcltClose: function aan te roepen na FcltClose van child
                    }
 */
function IFRAMER(id, url, params)
{
    params = params||{};
    var cls = "fcltframe";
    if ("tabframe" in params && !params.tabframe)
        cls += " notabframe";
%><div id="frm_<%=id%>" class="<%=cls%>">
<%
    if (params.buttons)
        CreateButtons(params.buttons)
    if (params.initHide && !S("fac_tabframes"))
        url+="&collapsed=1";
%>
    <div class="inside">
      <iframe id="<%=id%>" name="<%=id%>" frameborder="0" width="100%" height="<%=params.initHeight||'20px'%>"
              src="<%=url%>"
              <%=params.refreshOnClose? " orgsrc='" + url + "'" : ""%>
              <%=params.srcparent? " srcparent='" + params.srcparent + "'" : ""%>
              <%=params.FcltClose? " FcltClose=\"" + params.FcltClose + "\"" : ""%>
              onload="FcltMgr.iframeLoaded(this);">
      </iframe>
    </div>
</div><%
}

function IFRAMER_HEADER(titel, buttons, params)
{
    var iscoll = getQParamInt("collapsed",0)==1;
%>
    <script>
        $(document).ready(function()
        {
          headertofooter();
          <% if (iscoll) { %>
             $(".fcltframeheader").next().toggle(); <%
          }
          %>
        });
    </script>
      <div class="fcltframeheader <%= iscoll && !(params && params.nocollaps) ? ' collapsed' : ''%>" <%=params && params.nocollaps? "" : "onclick=\"$(this).next().toggle();$(this).toggleClass('collapsed');FcltMgr.resized(window);updateTableHeaders()\""%>>
        <span style="float:left"><nobr><%=titel %>&nbsp;<span id="iframerextratitle"></span></nobr></span><%
        if (buttons) {
            %><div class="buttoncontainer" style="float:right;"><%
            CreateButtons(buttons, { showIcons: true })
            %></div><%
        }
    %></div>

    <%
}

// Bij leeg label krijg je helemaal geen <td>'s
function AFIELD(pclass, plabel, phref, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty)
    return; // snel klaar

  if (plabel) {
      %><td class="label"><label <%=params && params.id? ' for=\"' + params.id + '\"' : ''%>><%=plabel? plabel + ":" : ""%></label></td>
        <td><%
  }
%>
  <a class="<%=pclass%>" <%=params && params.id? ' id=\"' + params.id + '\"' + ' name=\"' + params.id + '\"' : ''%> href="<%=safe.htmlattr(phref)%>" <%=params && params.onclick? ' onclick=\"' + safe.jsstring(params.onclick) + '\"' : ''%>
  <%=(params.html? " " + params.html + " " : "")%>><%=safe.html(pvalue)%></a>
  <%=((params.rating && params.rating.score) ? rating.stars(params.rating.score, params) : "")%>
<%
  if (plabel) { %>
    </td><%
  }
}

function AFIELDTR(pclass, plabel, phref, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty)
    return; // snel klaar

  %><tr <%=params.trclass?"class='"+params.trclass+"'":""%>>
      <% if (!plabel) { %><td class="label"></td><td><% } %>
      <%AFIELD(pclass, plabel, phref, pvalue, params)%>
      <% if (!plabel) { %></td><% } %>
  </tr><%
}

// Bij leeg label krijg je helemaal geen <td>'s
function ROFIELD(pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty)
    return; // snel klaar

// Vanuit API2 model
  if (pvalue != null && typeof pvalue == "object" && "name" in pvalue)
    pvalue = pvalue["name"];

  if (plabel) {
      %><td class="label"><label <%=params && params.id? ' for=\"' + params.id + '\"' : ''%>><%=plabel? plabel + ":" : ""%></label></td>
        <td><%
  }
  var input = "<span"

  // De classes
  input += " class='readonly " + pclass;
  if (params.infoPointer)
    input += " details";
  if (params.type == 'button')
    input += " button";
  input += "'"; // Einde class

  if (params.type == 'button') /* volgens mij is een readonly button vrij zeldzaam */
    input += " type='button'";
  if (params.id)
    input += " id='" + params.id + "' name='" + params.id + "'";
  if (params.title)
    input += " title='" + params.title + "'";

  if (params.html)
    input += " " + params.html + " ";

  if (params.infoPointer)
  {
    if (params.infoPointer.Url.indexOf("status_info.asp") > 0)
        prot_url = protectQS.create(params.infoPointer.Url);
    else
        prot_url = params.infoPointer.Url;

    if (params.infoPointer.NewWindow)
    {
        var fnclick = "window.open(\"" + safe.jsstring(prot_url) + "\")";
    }
    else if (params.infoPointer.Modal)
    {
      fnclick = "FcltMgr.openModalDetail(\"" + safe.jsstring(prot_url) + "\""
                      + ", { titel: \"" + safe.jsstring(params.infoPointer.Title||"") + "\" })";
    }
    else
    {
      fnclick = "FcltMgr.openDetail(\"" + safe.jsstring(prot_url) + "\""
                      + ", { reuse: true, titel: \"" + safe.jsstring(params.infoPointer.Title||"") + "\" })";
    }
    input += " onclick='" + safe.htmlattr(fnclick) + "'";
  }
  input += ">"  + safe.html(pvalue) + "</span>";
  Response.Write(input);
  if (params.selector) {
    FCLTselector(params.selector.fieldName, params.selector.sql, params.selector.params);
  }
  if (plabel) { %>
        </td><%
  }
}

function ROFIELDTR(pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty)
    return; // snel klaar

  if (plabel && params.translate && S("multi_language_option"))
  {
    var fn = "iface.translate('"+params.translate.fld+"', "+params.translate.key+", this.innerText, '"+safe.jsstring(pvalue)+"', 'input')"
    if (params.org_lcl)
        var fn = "iface.overrule('"+safe.jsstring(params.org_lcl)+"')"
    plabel = "<span class='facmgtmultilang' onclick='"+safe.htmlattr(fn)+"'>" + plabel + "</span>";
  }

  %><tr <%=params.trclass?"class='"+params.trclass+"'":""%>>
      <% if (!plabel) { %><td class="label"></td><td><% } %>
      <%ROFIELD(pclass, plabel, pvalue, params)%>
      <% if (!plabel) { %></td><% } %>
  </tr><%
}

function ROTEXTAREATR(pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty)
    return; // snel klaar

  if (plabel && params.translate && S("multi_language_option"))
  {
    var fn = "iface.translate('"+params.translate.fld+"', "+params.translate.key+", this.innerText, '"+safe.jsstring(pvalue)+"', 'textarea')"
    if (params.org_lcl)
        var fn = "iface.overrule('"+safe.jsstring(params.org_lcl)+"')"
    plabel = "<span class='facmgtmultilang' onclick='"+safe.htmlattr(fn)+"'>" + plabel + "</span>";
  }

  %><tr <%=params.trclass?"class='"+params.trclass+"'":""%>>
      <%if (plabel) {%><td class="label"><label><%=plabel? plabel + ":" : ""%></label></td><% } %>
      <td <%=(params.tdhtml_ta? " " + params.tdhtml_ta : "")%>><div class="readonly fclthtml <%=pclass%>"<%=(params.html? " " + params.html + " " : "")%><%=params && params.id? ' id=\"' + params.id + '\"' : ''%>><%=safe.fclthtml(pvalue, params.mldlink)%></div></td></tr><%
}

// params.html wordt er ook tussen geplakt (onclick bijvoorbeeld)
function RWFIELD(pname, pclass, plabel, pvalue, params)
{
    pvalue = safe.nvl(pvalue);
    params = params||{};
    if (plabel) {
        %><td class="label"><label for="<%=pname%>"><%=plabel?plabel+":":""%></label></td><td>
<%  }
    if (params.fronttext) {
      %><%=params.fronttext%>
<%  }
  var lclass = pclass;
  if (params.infoPointer) lclass += " details";
  if (params.extraclass)  lclass += " " + params.extraclass;
  if (!params.readonly && params.required) lclass += " required";
  if (!params.readonly && params.requiredor0) lclass += " required required0isoke";
  var inputtype = (isBadInput()? " type='text'" : " type='number'");
  var lstep="";
  switch (params.datatype) {
    case "number" :      lclass += " number"; break;
    case "float" :       lclass += " float"; break;
    case "currency" :    lclass += " currency"; lstep= " step='0.01'"; break;
    case "text" :        inputtype = " type='text'"; break;
    case "button" :      inputtype = " type='button'"; break;
    default :            inputtype = ""; break;
  }
%>
  <input class="<%=lclass%>" <%=inputtype%><%=lstep%> name="<%=pname%>" id="<%=pname%>" value="<%=Server.HTMLEncode(pvalue)%>"
  <%=(params.maxlength? " maxlength="+params.maxlength : "")%>
  <%=(params.readonly? " readonly " : "")%>
  <%=(params.html? " " + params.html + " " : "")%>
  <%
  if (params.infoPointer)
  { // Hebben we anno 2015.1 nog wel ergens een RWFIELD met infopointer?
    %> onclick="FcltMgr.openDetail('<%=safe.jsstring(params.infoPointer.Url)%>', { reuse: true, titel: '<%=safe.jsstring(params.infoPointer.Title||"")%>' })"<%
  }
  %>><%
  if (params.selector) {
    FCLTselector(params.selector.fieldName, params.selector.sql, params.selector.params);
  }
  if (params.extrabutton) {
    %>
    &nbsp;<input type="button" class=" <%= safe.htmlattr(params.extrabutton.pclass) %>" onclick="<%=safe.htmlattr(params.extrabutton.onclick)%>">
    <%
  }
  if (params.reartext) {
    %><%=params.reartext%>
<%}
  if (params.endicon)
   {
    %><i class='fa <%=params.endicon%> endicon'></i>
<%}
      if (plabel) { %>
        </td><%
  }
}

// Sommige browsers ondersteunen het input type='number' en dan gaat het fout als wij
// er iets met een komma instoppen.
function isBadInput()
{
    var agent = "" + Request.ServerVariables("HTTP_USER_AGENT");
    if (agent.indexOf("Chrome")>=0)
        return true;
    if (agent.indexOf("Firefox")>=0)
        return true;
    if (agent.indexOf("Safari")>=0)
        return true;

    return false;
}

function RWFIELDTR(pname, pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty && params.readonly)
    return; // snel klaar

  %><tr <%=params.trid?"id='"+params.trid+"'":""%> <%=params.trclass?"class='"+params.trclass+"'":""%>>
      <% if (!plabel) { %><td class="label"></td><td><% } %>
      <%RWFIELD(pname, pclass, plabel, pvalue, params)%>
      <% if (!plabel) { %></td><% } %>
  </tr><%
}

function RWTEXTAREATR(pname, pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty && params.readonly)
    return; // snel klaar

  %><tr <%=params.trclass?"class='"+params.trclass+"'":""%>>
      <%if (plabel) {%><td class="label"><label for="<%=pname%>"><%=plabel? plabel + ":" : ""%></label></td><% } %>
      <td <%=(params.tdhtml_ta? " " + params.tdhtml_ta : "")%>>
        <textarea class="<%=pclass%>"
            <%=(params.html? " " + params.html + " " : "")%>
            <%=' id=\"' + pname + '\"' + ' name=\"' + pname + '\"'%>
            <%=" maxlength="+(params.maxlength||4000)%>
            <%=(params.readonly? " readonly " : "")%>><%=safe.textarea(pvalue)%></textarea>
      </td>
    </tr><%
}

// Zie save2db.inc type "check": we voegen een hidden field has_xxxx toe
// params.html wordt er ook tussen geplakt (onclick bijvoorbeeld)
// DEPRECATED
function CHECKBOX(pclass, pid, pvalue, params)
{
  params = params||{};
%>
  <input type="hidden" id="has_<%=pid%>" name="has_<%=pid%>" value="1" <%=params.readonly? " disabled" : ""%>>
  <input type="checkbox" id="<%=pid%>" name="<%=pid%>"
         class="<%=pclass%>" <%=pvalue? "CHECKED " : ""%> <%=params.hidden?"style=\"visibility:hidden\"" : ""%>
         <%=params.readonly? " disabled" : ""%>
         <%=params.html? params.html : ""%>>
<%
}

function RWCHECKBOXTR(pname, pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty && params.readonly)
    return; // snel klaar
 %>
  <tr <%=params.trclass?"class='"+params.trclass+"'":""%>>
<%
  if (!params.boxfirst) {
    if (plabel) {
        %><td class="label"><label for="<%=pname %>"><%=plabel?plabel+":":""%></label></td><td><%
      } else {
        %><td class="label"></td><td><%
      }
      CHECKBOX(pclass, pname, pvalue, params)
      if (params.posthtml)
        Response.Write(params.posthtml);
      if (plabel) { %></td><% }
    } else {
      %><td colspan="2"><% CHECKBOX(pclass, pname, pvalue, params) %><%
    if (plabel) {
      %><label for="<%=pname %>"><%=plabel?plabel:""%></label></td><%
    } else {
      %></td><%
    }
  }
  %></tr><%
}

function CHECKBOXTR(plabel, pclass, pid, pvalue, params) // DEPCRECATED, backward compatible
{
    RWCHECKBOXTR(pid, pclass, plabel, pvalue, params);
};

function ROCHECKBOXTR(pclass, plabel, pvalue, params)
{
  params = params||{};
  if ((pvalue == null || pvalue == "") && params.suppressEmpty)
    return; // snel klaar
  if ((pvalue == 0) && params.suppressNo)
    return; // snel klaar
  if ((pvalue) && params.suppressYes)
    return; // snel klaar

  pvalue = (pvalue?L("lcl_Yes"):L("lcl_No"));
  ROFIELDTR(pclass, plabel, pvalue, params)
}

// Functie t.b.v. tijd velden
// altijd :-syntax
// serverside versie
function decimalToHour(val)
{
    if (!val || val == 0)
        return "";
    var mintime = Math.abs(val) != val; // is tijd negatief of positief
    var hh = Math.floor(Math.abs(val) + 0.5 / 60); // reken met positief tijd
    var mm = Math.floor((Math.abs(val) - hh) * 60 + 0.5);

    var timestr = String(hh) + ":" + String((mm < 10? "0" : "") + mm);
    return (mintime ? "-" + timestr : timestr); // voeg eventueel weer min-teken toe
}

// Kopie in ../shared/iface.inc
IFACE =
{
    FORM_END: function()
    {
        protectRequest.inputToken();
    }
}

function I(icon)
{
    if (icon in ICONS)
        icon = ICONS[icon];
    if (icon.match(/^fa-/))
        return "<i class='fa fa-fw {0}'></i>".format(icon);
    else
        return "<img alt='' src='{0}/appl/pictures/{1}'>".format(rooturl, icon);
}
%>