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

    File:           cad_verify.asp.asp
    Description:    Analyseer de lagen van een dwf tekening
    Parameters:     dwf
                    concept (0/1)
    Context:
    Note:
*/
DOCTYPE_Disable = 1;
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file='../CAD/FGII.inc'-->
<!-- #include file="../Shared/json2.js" -->

<%
user.checkAutorisation("WEB_FACTAB");
if (Server.ScriptTimeout<600) Server.ScriptTimeout=600;

oSLNKDWF = new ActiveXObject("SLNKDWF.About");
tmStart = oSLNKDWF.usTimer;
FCLTHeader.Requires({ plugins: ["jQuery"] });

var concept = getQParamInt("concept", 0) == 1;
var dwf = getQParam("dwf", "");

var fullnameDWF = (concept?S("fg_dwf_path_concept"):S("fg_dwf_path")) + dwf;
var fso = new ActiveXObject("Scripting.FileSystemObject");
if (!fso.FileExists(fullnameDWF))
    dwf = "";

%>
<html>
  <head>
<%  FCLTHeader.Generate(); %>

    <script type="text/javascript">
        function resizeIframes()
        {
            //var height = parseInt(document.documentElement.clientHeight);
            //document.getElementById('MMap').style.height = (height) +"px";
        };
        function MMap_onClick(SlnkEvent)
        {
            return false; // Don't process
        }
        function onOtherDrawing()
        {
            var sel = document.getElementById("sDocuments");
            var dwf = $("#sDocuments").val();
            var concept = $("input:radio[name=concept]:checked").val();
            window.location.href = "<%=Request.ServerVariables("SCRIPT_NAME")%>?dwf=" + dwf + "&concept="+concept;
        }

        $().ready(
            function () {
                $(".lcont").click(function () { $("#lcont").val($(this).text()); myRefresh() });
                $(".llabel").click(function () { $("#llabel").val($(this).text()); myRefresh() });
                $("#actueel,#concept,#sDocuments").change(onOtherDrawing);
            })
        function init()
        {
            resizeIframes()
            MMap.Reset();
            MMap.SetIMGGenerator("../CAD/cad_verify_proc.asp");
            MMap.SetPaperColor(<%=S("fg_paperColor")%>);
            MMap.SetLabelPosition(2);
            //MMap.Refresh(true); // Do zoom extents
            myRefresh();
        }
        var contLayer = "<%=safe.jsstring(S("fg_contourlayers"))%>";
        var labelLayer = "<%=safe.jsstring(S("fg_labellayers"))%>";
        function myRefresh()
        {
            var custParam= "&dwf=<%=safe.jsstring(fullnameDWF)%>"
                         + "&layers=" + $('select#layers>option:selected').map(function(){ return this.text }).get().join(",");;
            if ($("#lcont").val() && $("#llabel").val())
                custParam += "&contLayer="+$("#lcont").val()
                           + "&labelLayer="+$("#llabel").val()
            MMap.SetCustomParameters(custParam)
            MMap.Refresh(); // Try not to zoom extents
        }
        function MMap_onMapperLoad(pSLNKEvent)
        {
          var ext = $('#extents');
          if (pSLNKEvent && pSLNKEvent.success)
          {
              var accuracy = 1-(Math.log(pSLNKEvent.scaleX)/Math.log(10));
              var daccuracy = 2+accuracy; // Voor de distance
              if (accuracy<0) accuracy = 0;
              if (daccuracy<0) daccuracy = 0;
              version = "";
              version += "DWG ("+pSLNKEvent.viewminX.toFixed(accuracy)+", "+pSLNKEvent.viewminY.toFixed(accuracy) +")";
              version +=   " - ("+pSLNKEvent.viewmaxX.toFixed(accuracy)+", "+pSLNKEvent.viewmaxY.toFixed(accuracy) + ")";
              version += "<br>= " + (pSLNKEvent.viewmaxX-pSLNKEvent.viewminX).toFixed(accuracy)+"x"+
                                 (pSLNKEvent.viewmaxY-pSLNKEvent.viewminY).toFixed(accuracy) + "mm";

              version += "<br>= " + ((pSLNKEvent.viewmaxX-pSLNKEvent.viewminX)*
                                     (pSLNKEvent.viewmaxY-pSLNKEvent.viewminY) / 1e6).toFixed(2) + "m<sup>2</sup>";
              ext.html(version);
          }
        }
    </script>

    <style>
        table#analyse td { border: 1px solid black; }
        xlabel { width: 40px; }
        .lcont, .llabel { cursor: pointer;
                          white-space: nowrap; }
        input#lcont,input#llabel { width: 180px; }
    </style>
</head>

<body <%=dwf==""?"x":""%>onLoad='init();'>
<%

%><label><input type="radio" id='actueel' name='concept' value='0' <%=concept?"":"checked"%>><%=L("lcl_fg_actueel")%></label>
  <label><input type="radio" id='concept' name='concept' value='1' <%=concept?"checked":""%>><%=L("lcl_fg_concept")%></label>
<%=(concept?S("fg_dwf_path_concept"):S("fg_dwf_path"))%><select id='sDocuments' style="width:300pt"><option value="">Kies een tekening</option>
<%
      pathName = concept?S("fg_dwf_path_concept"):S("fg_dwf_path");
      fso = new ActiveXObject("Scripting.FileSystemObject");
      if (fso.FolderExists(pathName) )
      {
         f1 = fso.GetFolder(pathName);
         fc4 = new Enumerator(f1.files);
         for (; !fc4.atEnd(); fc4.moveNext())
         {
             vTekening0 = fc4.item().Name;
             if (vTekening0.match(/.dwf$/i)||vTekening0.match(/.w2d$/))
             {
%>    <option <%=vTekening0==dwf?"selected='1'":""%>><%=Server.HTMLEncode(vTekening0)%></option>
<%
             }
         }
      }
%></select><%
if (dwf=="")
{
    //Response.Write(safe.html(fullnameDWF));
    Response.End;
}
xd = new ActiveXObject("SLNKDWF.DWFFile");
xd.Open(fullnameDWF)

xc = new ActiveXObject("SLNKDWF.Whip2PNG")
if (xd.EplotSections.Count == 0)
    xc.Load(fullnameDWF);
else
    xc.LoadStream(xd.EplotSections.Item(0));
//xc.Maximize=true
//xc.dwgScale=10
xc.SetDimensions(1200,800, 0, 0, 1, 180)
var dummy = xc.GetAsMAP(); // om een parse to forceren!

var layers = [];
//Response.Write("Lagen: " + xc.layerCount);
for (i = 0; i < xc.layercount; i++)
    layers[xc.LayerItem(i)] = 1;

function analyze(contlayer, labellayer)
{
    var y = new ActiveXObject("SLNKDWF.WhipFile")
    var opt = new ActiveXObject("SLNKDWF.Options")
    opt.SetOption("MINCONTSIZE",  S("fg_areaThreshold")) // 1 vierkante meter

    y.SetLayers("^"+contlayer.replace(/\|/g,"\\|")+"$", "^"+ labellayer.replace(/\|/g,"\\|")+"$")
    if (xd.EplotSections.Count == 0)
        y.Load(fullnameDWF);
    else
        y.LoadStream(xd.EplotSections.Item(0));

    var result = { nCont: y.ContourCount,
                   Labels: [],
                   Opp: 0
                 };
    var m2 = 0;
    for (var i2=0; i2 < y.ContourCount; i2++)
    {
        var c = y.ContourItem(i2);
        var oLabel = c.Key;
        var oOpp =   c.Area;
        if (oLabel && oOpp)
        {
            result.Labels.push(oLabel);
            result.Opp += oOpp/1e6;
        }
        //Response.Write((oLabel?oLabel.value:"Geen label gevonden") + ": " + oOpp.value);
    }

    return result;
}
%>
    <table border='0'><tr><td>
        <iframe id=MMap name=MMap src="../SlnkDWF/ToonIMG.asp?ShowButtons=1"
            frameborder='0' framespacing='0' scrolling=no
            style="border:1px solid blue" width="600"  height="400">
        </iframe>
    <div id='extents'>Visible: </div>
    <div>Area Threshold: <%= (S("fg_areaThreshold")/1e6).toFixed(2) %>m<sup>2</sup> <span style='font-size:small'>S("fg_areaThreshold") = <%= S("fg_areaThreshold") %>mm<sup>2</sup></span></div>
    </td><td valign='top'>
        <input type='button' onclick='myRefresh()' value='&lArr; Update'></label>
        <input type='button' onclick='$("#lcont,#llabel").val("");myRefresh()' value='Clear &dArr;'></label>
        <input type='button' onclick='$("#lcont").val("<%=S("fg_contourlayers")%>");$("#llabel").val("<%=S("fg_labellayers")%>");myRefresh()' value='Default &dArr;'></label><br>
        <label for='lcont'>Cont: &nbsp;</label><input id='lcont' type='text' value='<%=safe.htmlattr(S("fg_contourlayers"))%>'><br>
        <label for='llabel'>Label: </label><input id='llabel' type='text' value='<%=safe.htmlattr(S("fg_labellayers"))%>'><br>
        <select id='layers' multiple='1' size='25' onchange='myRefresh()'><option>__geen__</option>
            <%
                var ll = [];
                for (layer in layers)
                    ll.push(layer.toUpperCase());
                ll.sort();
                for (layer in ll)
                    Response.Write("<option selected='1'>"+safe.html(ll[layer])+"</option>");
            %>
        </select><br>(totaal <%=xc.layercount%> lagen)
                      <span style='background-color:#C4E4DF'>cont+label</span>
                      <span style='background-color:#FF0000'>cont-label</span>
    </td></tr></table>
<%
// Bepaal voor elke laag hoeveel contouren het zou opleveren
var contlayers = [];
var labellayers = [];
Response.Write("<table id='analyse' border=1>");
Response.Write("<tr><th>fg_contlayer</th><th>#cont</th><th>fg_labellayer</th><th>#label</th><th>Opp.</th><th>Labels</th></tr>");
var lastcont="";
for (contlayer in layers)
{
    var res = analyze(contlayer, ".*")
    if (res.nCont)
    {
        contlayers.push({ l: contlayer, n: res.nCont});
        //Response.Write("<br>C:"+contlayer + " n:"+res.nCont)
    }
}
for (labellayer in layers)
{
    var res = analyze(".*", labellayer, ".*")
    if (res.Labels.length)
    {
        labellayers.push({ l: labellayer, n: res.Labels.length});
        //Response.Write("<br>L:"+labellayer + " n:"+res.Labels.length)
    }

}

// nu matchen
for (contlayer in contlayers)
{
    cl = contlayers[contlayer];
    for (labellayer in labellayers)
    {
        ll = labellayers[labellayer];
        var res = analyze(cl.l, ll.l)
        if (res.Labels.length)
        {
            Response.Write("<tr><td class='lcont'>"+(lastcont==cl.l?"":cl.l) + "</td>"
                          +"<td>" + (lastcont==cl.l?"":res.nCont) + "</td>");
            Response.Write("<td class='llabel'>" + ll.l + "</td>"
                          +"<td>" + res.Labels.length + (res.Labels.length == ll.n?"":("/"+ll.n)) + "</td>"
                          +"<td style='text-align:right'>" + res.Opp.toFixed(1) + "mē</td>");
            Response.Write("<td>" + res.Labels.join(" ") + "</td></tr>");
            lastcont=cl.l;
        }
    }
}
Response.Write("</table>");
%>
<small>Deze pagina: <%= ((oSLNKDWF.usTimer - tmStart)/1000).toFixed() %>ms voor <%=contlayers.length%> * <%=labellayers.length%> combinaties,
       (<%=oSLNKDWF.DLLPath%>, <%=oSLNKDWF.VersionString%>, <%=oSLNKDWF.Buildtime%>)
</small>
  </body>
</html>
