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

    File:        prodsearch.asp
    Description: Toont producten die voldoen aan het zoekwoord
    Parameters:  string s
    Context:     vanuit de algemene header, wellicht van buitenaf (eigen portal?)
    Note:        Autorisatie: de zoekresultaten moeten binnen de (write!?) scope van de user vallen
                 er wordt nog even genegeerd voor welke functie die discipline dan geautoriseerd is.

    TODO: Weegfactor: Als een zoektekst bij een artikel-omschrijving wordt gevonden is
                      dat natuurljk veel 'belangrijker' dan wanneer dat bij de disciplineomschrijving wordt gevonden

        Vervolgens wordt er in Facilitor naar de ingevoerde string gezocht in:
       v • Bestelcatalogi
       v • Groepen uit bestelcatalogi
       v • Artikelen uit bestelcatalogi
       v • Vakgroepen
       v • Herkenningsteksten bij vakgroepen
       v • Ruimte/catering/object catalogi bij reserveringen
       v • Namen en opmerkingen van reserveerbare zalen
       v • Omschrijvingen van cateringartikelen
       v • Omschrijvingen van reserveerbare objecten.
*/ %>
<!--#include file="../Shared/common.inc" -->
<!--#include file="../Shared/iface.inc" -->
<!--#include file="../Shared/flexfiles.inc" -->
<!--#include file="../shared/data_recordset.inc" -->
<!--#include file="../Shared/resultset_table_v2.inc" -->
<!--#include file="../shared/rater.inc" -->
<!--#include file="fac.inc" -->
<!--#include file="../res/res.inc" -->
<!--#include file="../res/res_plan_room_v2.inc" -->
<!--#include file="../Shared/discxalg3d.inc" -->
<!--#include file="../Shared/calendar.inc" -->
<!--#include file="../FAC/prodsearch.inc" -->

<%
FCLTHeader.Requires({js: ["../localscripts/raty/jquery.raty.min.js"]});


var inc_queries = ["mldstdm", "resruimte", "resartikel", "resdeel", "bescatalogus", "besartikelgroep", "besartikel", "faq", "prsperslid"];
var filter = {  s:            { val: getQParam("s",""),       lcl: L("lcl_search") }
             ,  soort:        { val: getQParam("soort", ""),  lcl: L("lcl_srch_entiteit") }
             ,  date_from_ms: { val: getQParamInt("date_from_ms", null),  lcl: L("lcl_date") }
             ,  satisfaction: { val: getQParamInt("satisfaction", 0),  lcl: L("lcl_res_oordeel") }
             ,  locatieKey: -1
             ,  gebouwKey: -1
             ,  verdiepingKey: -1
             };

if (filter.s.val.match(/^[mc][a-z]*[0-9]+/i)) // Meldingen en contracten kunnen extra letters hebben
  Server.Transfer("itemsearch.asp"); // die doet dat maar
if (filter.s.val.match(/^[bra][0-9]+/i)) // BES, RES en Afspraak alleen numeriek
  Server.Transfer("itemsearch.asp");
if (filter.s.val.match(/^#+/)) // objecten
  Server.Transfer("itemsearch.asp");

var counter_key = -1;
if (filter.s.val)
    counter_key = shared.registeraction("search", { info: filter.s.val });

supper = filter.s.val.toUpperCase();
var showall = getQParamInt("showall", 0) == 1;
var autosearch = getQParamInt("autosearch", 0) == 1;
var autosoort = getQParam("autosoort","");
if (autosoort)
    autosearch = true;

if (!filter.soort.val)
  filter.soort.val = autosoort;

var w_discs = write_discs();
var queries = prodsearch_queries(w_discs, filter);
var q_items = [];
if (filter.soort.val)
{
  for (item in queries[filter.soort.val].histogram)
  {
    q_items[item] = getQParam(item, "");
    if (!filter[item])
      filter[item] = {};
    filter[item].val = getQParam(item, "");
  }
}

function makestrong(tekst, zoek)
{
    if (!zoek)
        return tekst;
    var wrds = zoek.split(" ");
    var i = 0;
    var rearr = [];
    while (i < wrds.length)
    {
        if (wrds[i].length)
            rearr.push(escapeRegExp(wrds[i]));
        i ++;
    }
    var re = new RegExp(rearr.join("|"), 'ig');
    return tekst.replace (re, "<strong>$&</strong>");
}

function fncolType(oRs)
{  // Bepaal evt. localized omschrijvingen
   // Nog preciezer bepalen wat het beste is, met name in geval dat kolom extra een waarde heeft
   var srt = oRs.Fields("soort").Value;
   txt = queries[srt].intern;
   if (oRs.Fields("extra").Value != null)
   {
        var extra_1 = oRs.Fields("extra").Value;
        var extra_2 = oRs.Fields("extra2").Value || "";
        var resstr = (oRs.Fields("ishtmlsafe_extra").value ? extra_1 + "\n" + extra_2  : safe.html(shared.stripbbcodes(extra_1 +"\n"+ extra_2)));
        txt = makestrong(resstr, filter.s.val);
   }
   return txt;
}

function fnrowData(oRs, processParams)
{
   var module = oRs.Fields("soort").Value;
   var data = {url: "", ttl: ""};
   switch (module) {
      case "mldstdm":
          if (oRs.Fields("xurl").Value)
          {
            data.url = oRs.Fields("xurl").Value;
          } else {
            data.url = "appl/mld/mld_melding.asp?mld_defaultstdmelding="+oRs.Fields("product_key").Value;
          }
          data.ttl = L("lcl_complain");
          break;
      case "resruimte":
          data.url = "appl/res/res_reservering.asp?res_ruimte_key="+oRs.Fields("product_key").Value;
          data.ttl = L("lcl_reservation");
          if (processParams && processParams.disc_key)
          {
            data.deepurl = oRs.Fields("deepurl").Value;
            data.disc = processParams.disc_key;
          }
          break;
      case "resartikel":
          data.url = "appl/res/res_reservering.asp?restype=CV&res_artikel_key="+oRs.Fields("product_key").Value;
          data.ttl = L("lcl_reservation");
          break;
      case "resdeel":
          data.url = "appl/res/res_reservering.asp?restype=CV&res_deel_key="+oRs.Fields("product_key").Value;
          data.ttl = L("lcl_reservation");
          break;
      case "bescatalogus":
      case "besartikelgroep":
      case "besartikel":
          data.url = "appl/bes/bes_bestelling.asp?artikel_key="+oRs.Fields("product_key").Value+"&dis_key="+oRs.Fields("disc_key").Value;
          data.ttl = L("lcl_bes_srtdeel_full");
          break;
      case "faq":
          data.url = "appl/fac/fac_faq.asp?faq_key="+oRs.Fields("product_key").Value;
          if (oRs.Fields("xurl").Value)
            data.url = oRs.Fields("xurl").Value;
          data.ttl = L("lcl_faq_item");
          break;
      case "prsperslid":
          data.url = "appl/fac/fac_user_info_phone.asp?prs_key="+oRs.Fields("product_key").Value;
          break;
    }
    if (counter_key > 0)
    {
        if (data.url.slice(0,4) != "http") // intern
        {
            if (data.url.indexOf("?") == -1)
                data.url += "?x=x";
            data.url += "&from_search_key=" + counter_key; // Wordt in common.inc later opgepikt
        }
    }

  return JSON.stringify(data);
}

function fncolAction(oRs)
{
   var module = oRs.Fields("soort").Value;
   var url= "";  // om zoiets toe te gaan voegen
   var icon = "";
   var hint = "";
   switch (module) { //63749: Upgrade naar fontawesome 6 //gaat dit wel goed straks?
        case "mldstdm":
            icon = "fa-comment";
            if (oRs.Fields("foto").Value != null) {
                if (oRs.Fields("foto").Value.match(/^fa-/i))
                    icon = oRs.Fields("foto").Value
                else
                    icon = S("mlds_image_path") + oRs.Fields("foto").Value;
            }
            hint = L("lcl_do_melding_hint");
            break;
        case "resruimte":
            icon = "fa-map-marker";
            if (oRs.Fields("foto").Value != null)
            {
                icon = oRs.Fields("foto").Value;
                if (!icon.match(/^(http|fa-)/i))
                    icon = S("res_image_path") + icon;
            }
            hint = L("lcl_do_reservering_hint");
            break;
        case "resartikel":
            icon = "fa-utensils";
            if (oRs.Fields("foto").Value != null)
            {
                icon = oRs.Fields("foto").Value;
                if (!icon.match(/^(http|fa-)/i))
                    icon = S("res_image_path") + "artikel/" + icon;
            }
            hint = L("lcl_do_reservering_hint");
            break;
        case "resdeel":
            icon = "fa-calendar-alt";
            if (oRs.Fields("foto").Value != null)
            {
                icon = oRs.Fields("foto").Value;
                if (!icon.match(/^(http|fa-)/i))
                    icon = S("res_image_path") + "deel/" + icon;
            }
            hint = L("lcl_do_reservering_hint");
            break;
        case "bescatalogus":
        case "besartikelgroep":
        case "besartikel":
            icon = "fa-shopping-cart";
            if (oRs.Fields("foto").Value != null)
            {
                icon = oRs.Fields("foto").Value;
                if (!icon.match(/^fa-/i) && icon.indexOf("/") == -1) // Nog geen enkele slash? Dan moet het wel lokaal zijn.
                    icon = S("bes_image_path") + icon;

                if (icon.match(/\.pdf$/i))
                    icon="fa-file-pdf";
            }
            hint = L("lcl_do_bestelling_hint");
            break;
        case "faq":
            icon = "fa-book";
            hint = L("lcl_faq_item");
            break;
        case "prsperslid":
            var thisPrs = new Perslid(oRs.Fields("product_key"));
            icon = thisPrs.photoinfo().photopaththumb;
            hint = L("lcl_person");
            break;
    }
    if (icon.match(/^fa-/i))
        return "<span class='prodicon' title='"+safe.htmlattr(hint)+"'>" + I(safe.htmlattr(icon) + " fa-3x") + "</span>";
    else
        return "<img class='details prodimg' alt='" + safe.htmlattr(hint) + "' src='" + safe.htmlattr(icon) + "' title='"+ safe.htmlattr(hint) + "'>";
}

function fncolProduct(oRs)
{
    var resstr = safe.html(shared.stripbbcodes(oRs.Fields("product").Value));
    resstr = makestrong(resstr, filter.s.val);

    if (filter.soort.val == "resruimte" && oRs.Fields("satisfaction").Value)
    {
        var likesymbol = rater(oRs.Fields("satisfaction").Value / 2, { readonly: true } );
        resstr = "<table><tr><td>" + resstr + "</td><td>" + likesymbol + "</td></tr></table>";
    }
    return "<span class='pscapt'>"+resstr+"</span>";
}

function fncolPrijs(oRs)
{
    if (oRs.Fields("prijs").Value)
        return S("currency_pref") + safe.curr(oRs.Fields("prijs").Value);
    else
        return "";
}

function fncolGeneric(txt, noicon)
{
    return safe.html(txt);
}

function fncolSoort(srt, noicon)
{
    if (noicon)
        return queries[srt].intern;
    var l_icon = queries[srt].icon;
    return I(l_icon) + " " + queries[srt].intern;
}

function suggest_box_histogram (titel, histograms, kolom, params)
{
    var histogram = histograms[kolom.toUpperCase()];
    if (!histogram)
        return [];

    // histogram.sort(); helaas, histogram is niet zo veel Array als je zou denken
    var myhist = [];
    for (itm in histogram)
        myhist.push({ txt: itm, val: histogram[itm] });

    if (myhist.length == 1)
        return [myhist[0].txt];

    myhist.sort(function (a, b) { // Eerst op aantal, dan op tekst
                if (a.val != b.val)
                    return b.val - a.val;
                else if (a.txt > b.txt )
                    return 1;
                else
                    return -1;
           });

    params = params || {};
    var fncol = params.fncol || fncolGeneric;
    var keycol = params.keycol || "prod";
    var result = [];

%>
  <table class="filter" width="100%">
  <tr><th colspan="2"><%=safe.html(titel)%></th></tr>
<%
    var i;
    for (i = 0; i < myhist.length && i<=20; i ++)
    {
       var itm = myhist[i];
       result.push(itm.txt)
%>
    <tr><td onclick="refresh_filter({ '<%=kolom.toLowerCase()%>': '<%=safe.jsstring(String(itm.txt))%>' })">
             <p title="<%= fncol(String(itm.txt), true) %>" class="trunc"><%= fncol(String(itm.txt)) %></p>
         </td>
         <td class="count">(<%=itm.val%>)</td>
         </tr>
<%
    }
    if(myhist.length > 20)
    {
%>
       <tr><td colspan="2" class="meer"><%=L("lcl_more")%></td></tr>
<%
    }
%></table><%
    return result;
}

function suggest_box_resruimte (titel, histograms, kolom, params)
{
%>
  <table class="filter" width="100%">
  <tr><th><%=safe.html(titel)%></th></tr>
  <tr><td>
<%
    FCLTcalendar("date_from",
               { xlabel : "Vanaf",
                 datum: filter.date_from_ms.val>0?new Date(filter.date_from_ms.val):null,
                 initEmpty: filter.date_from_ms.val?0:1,
                 trclass: "primsearch",
                 volgnr: 1
               });
%></td></tr><%
    var likesymbol = rater(filter.satisfaction.val||1, {});
%><tr><td><div id='raterfilter'></div></td></tr>

</table>
<script>
  $(function ()
    {
        $("#raterfilter").raty({
            score: (<%=filter.satisfaction.val%>)/2,
            showHalf : true,
            half : true,
            path: '../localscripts/raty/img/',
            width: 120
            })
        });
</script>
<%
}

%>
<html>
<head>
 <% FCLTHeader.Generate() %>
   <script  type="text/javascript" >
    <% if (filter.s.val.length>0) {%>
      FcltMgr.setTitle(L("lcl_search_result") + " " + "<%=safe.jsstring(filter.s.val)%>");
        <%}%>

      var JSONdata = "<%=safe.jsstring(JSON.stringify(filter))%>";
      var filter = JSON.parse(JSONdata);

      function prod_edit(row)
      {
        var resData = JSON.parse(row.getAttribute("ROWDATA"));
        if (resData)
        {
          if (resData.url.slice(0,4) == "http")
          {
              FcltMgr.windowopen(resData.url);
              FcltMgr.stopPropagation(event);
          }
          else
          {
              FcltMgr.openDetail(resData.url, resData.ttl);
          }
        }
      }

      function refresh_filter(newfilter)
      {
          var item;
          var url = "prodsearch.asp?width_px=" + $(window).width();
          <% if (autosearch) { %>
           url += "&autosearch=1"
          <% } %>
          filter.s.val =  $('#searchText').val();
          if ($("div#raterfilter input[name=score]").length)
            filter.satisfaction.val = 2 * $("div#raterfilter input[name=score]").val();
          filter.date_from_ms.val = $("#date_from").val();

          for (item in newfilter)
          {
              if (!filter[item])
                 filter[item] = {};
              filter[item].val = newfilter[item];
          }

          for (item in filter)
          {
              var v = filter[item].val;
              if (v)
              {
                if (v instanceof Date)
                    v = v.getTime();
                url += "&" + item + "=" + myEncode(v);
              }
          }

          window.location.href = url;
      }
   </script>
   <% /* #prodsearch td zet wat stijlen waar wij last van hebben. Terugzetten: */ %>
    <style>
        table.planbord td.plantd { padding:0px!important; margin:0px!important; }
        table.planbord, table.planbord td { border:0px!important; }
        table.planbord { margin-left:20px; }
    </style>
   </head>

<body id="listbody">
   <table id="container" width="100%">
      <tr><td colspan="2">
         <form id="srch" onsubmit="refresh_filter({ <%= autosoort? " soort: ''" : "" %>}); return false;">
            <div class="container fclt-container-md ">
                <div class="row justify-content-center">
                    <div class="col-md-6">
                        <div class="search-container">
                            <input type="text" id="searchText" class="form-control search-input" value="<%=safe.htmlattr(filter.s.val)%>" placeholder="<%=safe.htmlattr(L('lcl_srch_placeholder'))%>">
                            <span class="default-clickable-icon searchIcon">
                                <%=I("fa-search search-icon fa-lg")%>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
         </form>
      </td></tr>
      <tr><td id="breadcrums" colspan="2">
         <% // breadcrums
            for (item in filter)
            {
                if (item == "s")
                    continue;
                if (filter[item].val && filter[item].val != "-1")
                {//title='"+safe.htmlattr(oRs("description").Value||"")+"'
                    if (item=="vakgroep")
                        var lbl = queries[filter.soort.val].vakgroep; // titel verschilt per soort
                    else
                        var lbl = filter[item].lcl;
                    switch (item)
                    {
                        case 'soort':
                            var xx = queries[filter[item].val].intern;
                            break;
                        case 'date_from_ms':
                            var xx = toDateString(new Date(filter[item].val))
                            break;
                        case 'satisfaction':
                            var xx = L("lcl_res_oordeel") + ": " + filter[item].val
                            break;
                        default:
                            var xx = getQParam(item , filter[item].val);
                            break;
                    }

                    var txt = "<span class='default-clickable-icon' title='"+L("lcl_srch_remove")+"' onclick='refresh_filter({"+item+": \"\"})'>" + I("fa-times", { fastyle: "fas" } ) + "</span>";
                    Response.Write(txt);
                    var txt = /* lbl + ": " + */ "<span class='tag'>" + safe.html(xx) + "</span>";
                    Response.Write(txt);
                }
            }
         %>
      </td></tr>
      <tr>
         <td id="results">
<%
    if (!autosearch) // Die mag ook met lege of korte string.
    {
        if (filter.s.val.length == 0) {
            Response.End;
        }
        if (filter.s.val.length < 2)
        {
            Response.Write("<p class='prodsrchmess'>"+L("lcl_fac_search_too_short")+"</p>");
            Response.End;
        }
    }
    var sqln = prodsearch_sql(filter, queries, w_discs, q_items, inc_queries);
    Oracle.Execute("alter session set nls_comp = 'LINGUISTIC' NLS_SORT = 'BINARY_AI'"); // Zodat mülLer gevonden wordt
    var rst = new ResultsetTable({sql:sqln,
                                   keyColumn: "product_key",
                                   ID: "prodtable",
                                   rowData: fnrowData,
                                   showAll: showall,
                                   noPrint:true,
                                   noLoading: true, // scrollbar verdwijnt anders?
                                   buildHistogram: true,
                                   emptySetString: "" // Doen we zelf verderop
                                  });

    rst.addColumn(new Column({hasActions: true, caption:"", content:fncolAction, align: "center" }));
    rst.addColumn(new Column({caption: "", content:fncolProduct}));
    rst.addColumn(new Column({caption: "", content: fncolType, combine:true}));
    rst.addColumn(new Column({caption: "", content:fncolPrijs, datatype: "currency", combine:true}));

    rst.addAction({action: "prod_edit", isDefault: true});

    var histogram = rst.processResultset();
    var reginfo = { info: filter.s.val } ;

	if (counter_key > 0 && histogram && typeof histogram == "object" && "SOORT" in histogram)
	{
	    reginfo.result = JSON.stringify(histogram["SOORT"]);
        shared.registeraction("searchresult", { refkey: counter_key,
                                                info: JSON.stringify(histogram["SOORT"])
                                              });
    }

    var allEmpty = (histogram == -1);
    if (allEmpty)
    {
        var emptySetString = "<p class='prodsrchmess'>"+L("lcl_fac_emptyprodset1") + "<cite>"+ safe.html(filter.s.val) + "</cite>" + L("lcl_fac_emptyprodset2") +"</p>";
        Response.Write("<div id='rstable'><TABLE><tr><td>" + emptySetString + "</td></tr></div>");
        Response.End;
    }

if(0)
for (col in rst.Counter)
{
    for (itm in rst.Counter[col])
        Response.Write("<br>histogram["+col+"]: " + safe.html(itm) + " " + rst.Counter[col][itm]);
}
// TODO styling eruit
%>
         </td>
         <td style="width: 150px; vertical-align: top; padding: 0 5px 0 12px;">
<%
if (filter.soort.val == "resruimte")
{
    suggest_box_resruimte(L("lcl_date") + "/" + L("lcl_res_oordeel"));
}
var soorten = suggest_box_histogram(L("lcl_srch_entiteit"), rst.Counter, "soort", { fncol: fncolSoort });

// Als er onverwacht maar één soort is gaan we de pagina herladen maar dan met
// filtering op die soort. Dan krijgen we uitgebreidere queries en meer suggest-boxen
if (!filter.soort.val && soorten.length == 1)
{
%>
    <script>refresh_filter({ autosoort: "<%=soorten[0]%>" });</script>
<%
    Response.End;
}
                if (soorten.length == 1) // dan meer detail histogrammen
                {
                    for (histo in queries[soorten[0]].histogram)
                    {
                        suggest_box_histogram(queries[soorten[0]].histogram[histo].lcl, histogram, histo, {});
                    }
                }
%>
         </td>
      </tr>
   </table>
</body>
</html>
<% ASPPAGE_END(); %>
