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

    Description:    Select a CAD-theme to display
    Parameters:
    Note:           You should set S("fg_mobile_thema") to -1
                    and not use parameter thema_key
                    to get the selector. Else it will be bypassed

*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="./mobile.inc" -->
<!-- #include file="./iface.inc" -->
<%
var qrc = getQParamInt("qrc", 0) != 0;
var verdieping_key = getQParamInt("verdieping_key", user.alg_verdieping_key({withcurrent:true}));
var ruimte_key = getQParamInt("ruimte_key", -1); // voor highlight
var mld_key_dwgxy = getQParamInt("mld_key_dwgxy", -1);
var caddwgx = getQParamFloat("caddwgx", null); // x coördinaat van een specifieke plek in de ruimte die gehighlight moet worden.
var caddwgy = getQParamFloat("caddwgy", null); // y coördinaat van een specifieke plek in de ruimte die gehighlight moet worden.
var thema_key = getQParamInt("thema_key", S("fg_mobile_thema"));
var themai_key = getQParamInt("themai_key", -1);
var nothema = getQParamInt("nothema", 0) == 1;
var readonly = getQParamInt("readonly", 0) == 1;
var return_to = getQParam("return_to", "");
var zoom = getQParamFloat("zoom", 2);

if (thema_key == -1 && themai_key == -1 && !nothema)  // Dan vragen we een thema
{
  Server.Transfer("cad_thema_select.asp");
}

var sql = "SELECT alg_gebouw_naam||' - '||alg_verdieping_omschrijving verdieping_naam"
        + " FROM alg_verdieping v, alg_gebouw g"
        + " WHERE v.alg_gebouw_key = g.alg_gebouw_key"
        + "   AND alg_verdieping_key = " + verdieping_key;

var oRs = Oracle.Execute(sql);
var verdieping_naam = oRs("verdieping_naam").value;
oRs.Close();

// Welke disciplines mag ik (default) zien?
// Let op: ik kan wel een objectthema hebben gekozen, maar als de objectdiscipline niet
//         default aan staat, zie ik die vooralsnog niet. Ergens zou nog een Objectlaag-selectie tussen mogen.
sql = "SELECT DISTINCT d.ins_discipline_key"
    + " FROM fac_v_my_disciplines m, ins_v_aanwezigdiscipline d, ins_disc_params dp "
    + " WHERE d.ins_discipline_key=m.ins_discipline_key(+)" // outer join voor S("fg_publiclayers")
    + "   AND d.ins_discipline_min_level = 1"
    + "   AND dp.ins_disc_params_cadlayers IS NOT NULL"
    + "   AND BITAND(dp.ins_disc_params_type, 1) = 1" // binnen
    + "   AND BITAND(dp.ins_disc_params_type, 4) = 4" // default aan
    + "   AND dp.ins_discipline_key = d.ins_discipline_key"
    + "   AND (fac_functie_code IN ('WEB_INSMAN', 'INSUSE')"
      + (S("fg_publiclayers").length ? " OR d.ins_discipline_key IN (" + S("fg_publiclayers").join(",") + ")" : "")
      + " ) "
    + "   AND prs_perslid_key(+)="+user_key;
var oRs = Oracle.Execute(sql);
discs = [];
while (!oRs.Eof)
{
  discs.push(oRs("ins_discipline_key").Value);
  oRs.MoveNext();
}
oRs.Close();

var imgurl = "../cad/mySlnk2IMG.asp?mode=0"
           + "&scenario_key=0"
           + "&imageonly=1" // er komt geen &asMap dus temp hoeft niet bewaard te worden
           + "&vkey=" + verdieping_key
           + "&paperColor=" + S("fg_paperColor")
           + "&labelpos=" + S("fg_labelposition")
           + "&discs=" + discs.join(",")
           + (ruimte_key > 0
             ? "&highlight=" + ruimte_key
             : "")
           + (caddwgx != null && caddwgy != null
             ? "&caddwgx=" + caddwgx + "&caddwgy=" + caddwgy
             : "")
           + (mld_key_dwgxy > 0
             ? "&mld_key_dwgxy=" + mld_key_dwgxy
             : "")
           + (thema_key > 0
             ? "&thema=" + thema_key
             : "")
           + (themai_key > 0
             ? "&themai=" + themai_key
             : "")
           + (S("fg_mobile_label") > 0
             ? "&label=" + S("fg_mobile_label")
             : "");

// iphone7 resolution as reference
var sizeX = 1334;
var sizeY = 750;
// set image size to zoom factor
sizeX = 1920 / 2 * zoom;
sizeY = 1080 / 2 * zoom;
imgurl += "&sizeX=" + (1*sizeX);
imgurl += "&sizeY=" + (1*sizeY);
%>

<html>
  <head>
<% FCLTMHeader.Generate({}); %>
<script>
<%  if (!readonly)
    { %>
      // is er niet met bootstrap $(function() { $.mobile.zoom.enable(true); });

      var imgWidth;
      var imgHeight;
      $(function() {
          $("div#mobplan").css("maxHeight", $(window).height() * 0.8);

          var $img = $("div#mobplan img");
          var clickInProgress = false;

          $img.on("click", function (e) {
              if (clickInProgress) return;
              clickInProgress = true;

              var offset = $(this).offset();
              var posX = e.pageX - offset.left;
              var posY = e.pageY - offset.top;

              $.getJSON("<%=safe.jsstring(imgurl)%>&asFND=1&findX={0}&findY={1}".format(posX, posY), function(SlnkEvent) {
                  process_info(SlnkEvent);
                  // If navigation does not occur, allow clicking again after 2 seconds
                  setTimeout(function() { clickInProgress = false; }, 2000);
              });
          });

          $img.on("load", function(e) {
              imgWidth = $(this).width();
              imgHeight = $(this).height();
              $(this).parent().scrollLeft(($(this).width() - $(this).parent().width()) / 2);
              $(this).parent().scrollTop(($(this).height() - $(this).parent().height()) / 2);
          });
      });

      function process_info(SlnkEvent)
      {
        if (SlnkEvent.ContourLayer == "SLNK Contours")
        {
          var klikker = "";
          if (SlnkEvent.click_urlR && SlnkEvent.Key > 0)
          {
            klikker = SlnkEvent.click_urlR  + SlnkEvent.Key;
          }
          else
          {
            if ("<%=safe.jsstring(return_to)%>")
                klikker = "<%=rooturl%>/appl/pda/<%=safe.jsstring(return_to)%>&ruimte_key=" + SlnkEvent.Key;
          }
          if (klikker)
          {
              window.location.href = klikker
                                   + "&caddwgx=" + SlnkEvent.dwgX
                                   + "&caddwgy=" + SlnkEvent.dwgY;
          }
        }
      }
<%  } %>

    // Pinch-to-zoom and pan for the image (always enabled)
    $(function () {
        var img = document.querySelector('#mobplan img');
        if (!img) return;
        var lastScale = 1, scale = 1, lastX = 0, lastY = 0, posX = 0, posY = 0, startX = 0, startY = 0, dragging = false;

        function setTransform() {
            img.style.transform = "translate(" + posX + "px," + posY + "px) scale(" + scale + ")";
        }

        img.addEventListener('touchstart', function(e) {
            if (e.touches.length === 1) {
                dragging = true;
                startX = e.touches[0].clientX - lastX;
                startY = e.touches[0].clientY - lastY;
            }
        });

        img.addEventListener('touchmove', function(e) {
            if (e.touches.length === 1 && dragging) {
                e.preventDefault();
                posX = e.touches[0].clientX - startX;
                posY = e.touches[0].clientY - startY;
                lastX = posX;
                lastY = posY;
                setTransform();
            } else if (e.touches.length === 2) {
                e.preventDefault();
                dragging = false;
                var dx = e.touches[0].clientX - e.touches[1].clientX;
                var dy = e.touches[0].clientY - e.touches[1].clientY;
                var dist = Math.sqrt(dx*dx + dy*dy);

                if (!img._startDist) {
                    img._startDist = dist;
                    img._startScale = scale;
                } else {
                    var newScale = img._startScale * (dist / img._startDist);
                    scale = Math.max(1, Math.min(newScale, 5)); // Clamp zoom
                    setTransform();
                }
            }
        }, { passive: false });

        img.addEventListener('touchend', function(e) {
            dragging = false;
            img._startDist = null;
            img._startScale = scale;
            lastX = posX;
            lastY = posY;
        });

        // Optional: double tap to reset
        var lastTap = 0;
        img.addEventListener('touchend', function(e) {
            var now = new Date().getTime();
            if (e.touches.length === 0 && now - lastTap < 300) {
                scale = 1; posX = 0; posY = 0; lastX = 0; lastY = 0;
                setTransform();
            }
            if (e.touches.length > 0) {
                lastTap = 0;
            } else {
                lastTap = now;
            }
        });

        // Mouse wheel zoom (desktop)
        img.addEventListener('wheel', function(e) {
            e.preventDefault();
            var delta = e.deltaY < 0 ? 1.1 : 0.9;
            scale = Math.max(1, Math.min(scale * delta, 5));
            setTransform();
        });
    });
</script>
</head>
<body>
<%
  PAGE_START({id: "page-2-"+verdieping_key});
  HEADER({title: verdieping_naam, back:!qrc, home: !qrc});
  CONTENT_START();
%>
    <div id="mobplan" style="max-width:100%;overflow: scroll; touch-action:none;">
      <img alt="<%=L("lcl_room_cad")%>" style="max-width:100%;height:auto;display:block;margin:0 auto;touch-action:none;user-select:none;" src="<%=safe.htmlattr(imgurl)%>">
    </div>
<%

    if (thema_key != -1)
    {
      // vrij nauwkeurig gestript uit cad/legenda.asp

      sql = "SELECT ts.cad_legenda_key,"
          + lcl.xsqla('ts.cad_legenda_omschrijving','ts.cad_legenda_key')+","
          + "       ts.cad_legenda_discreet, "
          + "       tt.cad_thema_view, tt.cad_thema_type, tt.fac_functie_key"
          + "  FROM cad_legenda ts, cad_thema tt"
          + " WHERE tt.cad_thema_key = " + thema_key
          + "   AND tt.cad_legenda_key = ts.cad_legenda_key";
      oRs = Oracle.Execute(sql)

      if (!oRs.Eof)
      { // Is wel heel vreemd, een lege legenda
        var themaType = oRs("cad_thema_type").Value;
        var legendaOmschrijving=oRs("cad_legenda_omschrijving").value;
        var discreet=oRs("cad_legenda_discreet").value==1;
        var legenda_key=oRs("cad_legenda_key").value;
        var viewName = oRs("cad_thema_view").value;
        oRs.close();

        var wkveld = "null waarde_key";

        var waardenSQL = "select waarde, "+wkveld
                       + "  from " + viewName + " th, alg_ruimte ar "
                       + " where th.alg_ruimte_key = ar.alg_ruimte_key"
                       + "   and alg_verdieping_key = " + verdieping_key;

        if (discreet)
            sql = "SELECT "+ lcl.xsqla('ti.CAD_LEGENDAWAARDE_OMSCHR','ti.cad_legendawaarde_key')
                + ", ti.CAD_LEGENDAWAARDE_RGB, TH2.WAARDE_KEY, COUNT(*) aantal"
                + "  FROM CAD_LEGENDAWAARDE ti, (" + waardenSQL + ") TH2 "
                + " WHERE TI.CAD_LEGENDAWAARDE_VALUE = TH2.WAARDE "
                + "   AND ti.CAD_LEGENDA_KEY = " + legenda_key
                + " GROUP BY "+lcl.xsql('ti.CAD_LEGENDAWAARDE_OMSCHR','ti.cad_legendawaarde_key')+", ti.CAD_LEGENDAWAARDE_RGB, TH2.WAARDE_KEY"
                + " ORDER BY CAD_LEGENDAWAARDE_OMSCHR";
        else // Niet discreet-->alle waarden ongeacht voorkomen
            sql = "SELECT DISTINCT "+ lcl.xsqla('ti.CAD_LEGENDAWAARDE_OMSCHR','ti.cad_legendawaarde_key')
                + ", ti.CAD_LEGENDAWAARDE_RGB, "
                + "                fac.safe_to_number(CAD_LEGENDAWAARDE_VALUE)"
                + "  FROM CAD_LEGENDAWAARDE ti"
                + " WHERE ti.CAD_LEGENDA_KEY = " + legenda_key
                + " ORDER BY fac.safe_to_number(CAD_LEGENDAWAARDE_VALUE)" // Numeriek sorteren!
        oRs = Oracle.Execute(sql)
%>
        <div class='mlegendatitel'><%=safe.html(legendaOmschrijving)%></div>
<%
        v_count   = "";
        while (!oRs.EOF)
        {
          v_waarde_key = null;
          v_waarde  = oRs.Fields("CAD_LEGENDAWAARDE_OMSCHR").value;
          v_kleur   = oRs.Fields("CAD_LEGENDAWAARDE_RGB").value.replace(/ /g,'');
          if (discreet) {
              v_count = " (" + oRs.Fields("aantal").value + "x)";
              v_waarde_key  = oRs.Fields("waarde_key").value;
          }
%>
          <div class='mlegendaregel'><span style="background-color: #<%=safe.htmlattr(toHexValue(v_kleur))%>; padding: 0 10px;">&nbsp;&nbsp;</span> <%=safe.html(v_waarde)%> <%=v_count%></div>
<%
          oRs.MoveNext();
        }
        oRs.Close();
      }
    }
    CONTENT_END();
    FOOTER();
    PAGE_END();
PDA_PAGE_END(); %>
	</body>
</html>
<% ASPPAGE_END(); %>