<%@ 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 this page. 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 thema_key = getQParamInt("thema_key", -1);
var themaI_key = getQParamInt("themaI_key", -1);
var bordlabel_key = getQParamInt("bordlabel_key", -1);
var res_disc_key_arr = getQParamIntArray("res_disc", []);
var res_van = getQParamDate("res_van", null);
var zoom = getQParamFloat("zoom", 2);

var LegendaFilter = "L"; // assume legendaFilter = L (parameter in desktop legenda.asp)
var inoutMode = 0; // assume inoutmode = 0 (parameter in desktop legenda.asp)
var scenario_key = 0; // assume scenario_key = 0 (parameter in desktop legenda.asp)

if (thema_key == -1)  // 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();

sql = "SELECT DISTINCT (id.ins_discipline_key) ins_discipline_key"
    + "  FROM res_v_aanwezigdeel rd, ins_v_aanwezigdeel id "
    + " WHERE rd.res_ins_deel_key = id.ins_deel_key AND rd.res_discipline_key IN (" + res_disc_key_arr.join(",") + ")";
oRs = Oracle.Execute(sql)
var ins_disc_key = oRs("ins_discipline_key").Value; // VERONDERSTELT 1-op-1, we pakken iig de eerste ins_discipline
oRs.Close();


var imgurl = "../cad/mySlnk2IMG.asp?mode=0";
imgurl += "&imageonly=1"; // er komt geen &asMap dus temp hoeft niet bewaard te worden
imgurl += "&scenario_key=0&vkey=" + verdieping_key;
imgurl += "&paperColor="+S("fg_paperColor");
imgurl += "&labelpos=" + S("fg_labelposition");
imgurl += "&discs=" + ins_disc_key;
if (thema_key > 0) {
    imgurl += "&thema=" + thema_key;
}
if (themaI_key > 0) {
    imgurl += "&themai=" + themaI_key;
}
if (bordlabel_key > 0) {
    imgurl += "&label=" + bordlabel_key;
}
if (res_van) {
    imgurl += "&datumfilter="+res_van.getTime();
}
// 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>
    var imgWidth;
    var imgHeight;
    $(function() {
        $("div#mobplan").css("maxHeight", $(window).height() * 0.8);
        $("div#mobplan img").click(function (e) {
            var posX = event.offsetX * <%=sizeX%> / ($("div#mobplan").width() * (imgWidth / $("div#mobplan").width())),
                posY = event.offsetY * <%=sizeY%> / ($("div#mobplan").height() * (imgHeight / $("div#mobplan").height()));
        $.getJSON( "<%=safe.jsstring(imgurl)%>&asFND=1&findX={0}&findY={1}".format(posX, posY),
                   process_info);
        } );
        $("div#mobplan img").on("load", function(e)
        {
            // save image width and height
            imgWidth = $(this).width();
            imgHeight = $(this).height();
            // scroll to center of image
            $(this).parent().scrollLeft(($(this).width() - $(this).parent().width()) / 2);
            $(this).parent().scrollTop(($(this).height() - $(this).parent().height()) / 2);
        }) // JGL: Waarom? .load();

        var img = document.getElementById('plattegrond-img');
        var container = document.getElementById('mobplan');
        var scale = 1, posX = 0, posY = 0, lastX = 0, lastY = 0, startX = 0, startY = 0, dragging = false;

        function clamp(val, min, max) {
            return Math.max(min, Math.min(max, val));
        }

        function setTransform() {
            var cw = container.clientWidth;
            var ch = container.clientHeight;

            // Compute pan bounds based on container size & scale
            var minX = -(cw * scale - cw) / 2;
            var maxX =  (cw * scale - cw) / 2;
            var minY = -(ch * scale - ch) / 2;
            var maxY =  (ch * scale - ch) / 2;

            posX = clamp(posX, minX, maxX);
            posY = clamp(posY, minY, maxY);

            lastX = posX;
            lastY = posY;

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

        img.addEventListener('load', function() {
            scale = 1;
            posX = 0;
            posY = 0;
            lastX = 0;
            lastY = 0;
            setTransform();
        });

        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;
                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();
        });
    });
    function process_info(data)
    {
        if (data.ContourKey)
        {
            console.log("Object: " + data.ContourKey);
            if (data.ContourKey.match(/^I:/)) // INS_DEEL
            {
              window.location.href = "<%=rooturl%>/appl/pda/reserveringen.asp?ins_key=" + data.ContourKey.substring(2) + "&res_van=<%=(new Date(res_van).getTime())%>";
              //var url = "./ins_change.asp?deel_key=" + data.ContourKey.substring(2);
            }
            else if (data.ContourKey.match(/^R:/)) // RUIMTE
            {
              //var url = "./ins_change.asp?deel_key=" + data.ContourKey.substring(2);
            }

        }
    }
  </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="height:auto;display:block;margin:0 auto;" src="<%=safe.htmlattr(imgurl)%>" id="plattegrond-img">
    </div>
<%
    // En nu nog de legenda
    if (thema_key != -1 || themaI_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 = " + (themaI_key > 0 ? themaI_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 has_date_filter = hasColumn(viewName, "FCLT_F_DATUM", "DATE");

            var isUpdatable = (themaType & 0x80) == 0x80;

            if (isUpdatable)
                var wkveld = "waarde_key" // veld  moet er dan ook zijn!
            else
                var wkveld = "null waarde_key";

            if ((themaType & 0x18) == 0x10) // Objecten
            {
                // Toon legendawaarden die bij *een* object voorkomen, anders te ingewikkeld met disc en zo
                var waardenSQL = "select distinct waarde, null waarde_key"
                               + "  from " + viewName + " th";
            }
            else if ((themaType & 0x18) != 0x08) // ruimtes
            {
                if (isUpdatable && LegendaFilter=="L") // alles op locatie
                {
                    var waardenSQL = "select waarde, "+wkveld
                                   + "  from " + viewName + " th, alg_ruimte ar, "
                                   + "       alg_verdieping av, alg_gebouw ab,"
                                   + "       alg_verdieping av1, alg_gebouw ab1" // 1 versies 'zoeken' locatie
                                   + " where th.alg_ruimte_key = ar.alg_ruimte_key"
                                   + "   and ar.alg_verdieping_key = av.alg_verdieping_key"
                                   + "   and av.alg_gebouw_key = ab.alg_gebouw_key"
                                   + "   and av1.alg_verdieping_key = " + verdieping_key
                                   + "   and ab1.alg_gebouw_key = av1.alg_gebouw_key"
                                   + "   and ab.alg_locatie_key = ab1.alg_locatie_key"
                }
                else
                {
                    var waardenSQL = "select waarde, "+wkveld
                                   + "  from " + viewName + " th"
                    if (!isUpdatable || LegendaFilter=="V")
                    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;
                }
            }
            else // werkplekken
            {
                var waardenSQL = "select waarde, null waarde_key"
                               + "  from " + viewName + " th, prs_werkplek pw, alg_ruimte ar "
                               + " where th.prs_werkplek_key = pw.prs_werkplek_key"
                               + "   and pw.prs_alg_ruimte_key = ar.alg_ruimte_key"
                               + "   and alg_verdieping_key = " + verdieping_key;
            }

            if (hasColumn(viewName, 'fclt_f_3d_user_key', 'NUMBER'))
                 waardenSQL += " AND th.fclt_f_3d_user_key = " + user_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)%> </div>
        <%
              oRs.MoveNext();
              }
              oRs.Close();

            }
    }
    CONTENT_END();
    FOOTER();
    PAGE_END();
PDA_PAGE_END(); %>
	</body>
</html>
<% ASPPAGE_END(); %>