<% /*
     $Revision$
     $Id$
*/ %>
<!-- #include file="../shared/FlexFiles.inc" -->
<%
// Alleen nog in gebruik voor CAD/PrintFG.asp, daar nog eens uit-schrijven

// Stuur het resultaat rechtstreeks naar het Response object, essentieel om encoding te sturen
// params: mode, srtnotificatie
function STR2Stream(xmlstr, xslfile, Stream, params)
{
  params = params || {};
  var xslfile = Server.MapPath(xslfile);

  var xslt = new ActiveXObject("Msxml2.XSLTemplate.6.0");
  var xsldoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.6.0");
  var xslproc;
  xsldoc.async = false;
  xsldoc.setProperty("AllowXsltScript", true);
  xsldoc.load(xslfile);

  if (xsldoc.parseError.errorCode != 0)
  {
     var myErr = xsldoc.parseError;
     __Log("XML2STR3 Error in stylesheet ("+xslfile+"): " + myErr.reason);
     Response.Write ("<html><body><b>Error in stylesheet ("+xslfile+"):<br></b>" + myErr.reason + "</body></html>");
  }
  else
  {
     xsldoc.resolveExternals = true; // anders op de volgende regel al:
                                     // A reference to variable or parameter 'srtnotificatiecode' cannot be resolved
     xslt.stylesheet = xsldoc;
     var xmldoc = new ActiveXObject("Msxml2.DOMDocument.6.0");
     xmldoc.async = false;
     xmldoc.loadXML(xmlstr);
     if (xmldoc.parseError.errorCode != 0) {
        var myErr = xmldoc.parseError;
        __Log("XML2STR3 Error in xmlfile: " + myErr.reason);
        return ("<html><body><b>Error in xmlfile:<br></b>" + myErr.reason + "</body></html>");
     } else {
        xslproc = xslt.createProcessor();
        xslproc.input = xmldoc;
        xslproc.addParameter("mode", params.mode);
        xslproc.addParameter("srtnotificatiecode", params.srtnotificatie);
        xslproc.addParameter("rooturl", rooturl);
        xslproc.addParameter("custpath", custpath);
        // xslproc.output = Stream; niet rechtstreeks, we moeten nog nabewerken voor QRC
        xslproc.transform();
        p_bodyhtml = xslproc.output;

        var startPos = p_bodyhtml.indexOf("qrc=") + 4;
        var quote = p_bodyhtml.substr(startPos, 1);
        var eindPos =  p_bodyhtml.indexOf(quote, startPos + 2);
        if (startPos > 4 && eindPos > startPos)
        {
            var qrc = p_bodyhtml.substring(startPos + 1, eindPos);
            qrc = qrc.replace(/\&amp;/g, "&"); // Het was nog HTML/XML-encoded
            var xc = new ActiveXObject("SLNKDWF.QRCode");
            xc.Text = qrc;
            __Log("Creating QRC: " + qrc);
            var oXML = new ActiveXObject("Msxml2.DOMDocument.6.0");
            oNode = oXML.createElement("encodeddata");
            oNode.dataType = "bin.base64"; // Zeer snelle oplossing
            oNode.nodeTypedValue = xc.GetAsPNG();
            var b64 = oNode.text;

            var newbody = p_bodyhtml.substr(0, startPos - 4) + "src=\"data:image/png;base64," + b64 + "\"" + p_bodyhtml.substr(eindPos + 1);
            p_bodyhtml = newbody;
        }

        // Nu frc-codering opzoeken <img frc="M=SML:K=34417:R=R128x128"/>
        var startPos = p_bodyhtml.indexOf("frc=") + 4;
        var quote = p_bodyhtml.substr(startPos, 1); // enkele of dubbele quote
        var eindPos =  p_bodyhtml.indexOf(quote, startPos + 2);
        while (startPos > 4 && eindPos > startPos)
        {
            var flexcode = p_bodyhtml.substring(startPos + 1, eindPos);
            var props = flexProps2(flexcode);
            if (!props.files.length)
            {   // Geen bestanden gevonden? Dan hele img-tag gewoon er uit halen
                var eindPos =  p_bodyhtml.indexOf(">", startPos + 2);
                // Let op: door de -9 werkt het alleen als de frc het eerste attribuut is van de img
                var newbody = p_bodyhtml.substr(0, startPos - 9) + p_bodyhtml.substr(eindPos + 1);
                p_bodyhtml = newbody;
            }
            else
            {
                var filedata =  props.files[0];
                if (filedata.resized)
                    var file = filedata.resized;
                else
                    var file = props.AttachPath + props.files[0].name;

                var fileStream = new ActiveXObject("ADODB.Stream")
                fileStream.Open();
                fileStream.Type = 1; //adTypeBinary
                fileStream.LoadFromFile(file);
                fileStream.Position = 0; // We gaan nu over in uitvoermode

                var oXML = new ActiveXObject("Msxml2.DOMDocument.6.0");
                oNode = oXML.createElement("encodeddata");
                oNode.dataType = "bin.base64"; // Zeer snelle oplossing
                oNode.nodeTypedValue = fileStream.Read(fileStream.Size);
                fileStream.Close();
                if (filedata.tempdelete)
                {
                    var fso = Server.CreateObject("Scripting.FileSystemObject");
                    fso.DeleteFile(filedata.tempdelete);
                }

                var b64 = oNode.text;
                // TODO: Niet altijd als png, soms ook JPG, hoewel het goed lijkt te gaan in de meeste browsers
                var newbody = p_bodyhtml.substr(0, startPos - 4) + "src=\"data:image/png;base64," + b64 + "\"" + p_bodyhtml.substr(eindPos + 1);
                p_bodyhtml = newbody;
            }
            var startPos = p_bodyhtml.indexOf("frc=", eindPos) + 4;
            var quote = p_bodyhtml.substr(startPos, 1);
            var eindPos =  p_bodyhtml.indexOf(quote, startPos + 2);
        }

        Stream.Write(p_bodyhtml);
        if (params.log_postfix)
        {
            var log_file = __Log2FileName(params.log_postfix);
            var fileStream = Server.CreateObject("ADODB.Stream");
            fileStream.Open();
            fileStream.WriteText(p_bodyhtml);
            fileStream.SaveToFile(log_file, 2); // 2=overwrite
            fileStream.Close();
        }
     }
  }
}

// returns the complete and appropriate XSL filename of my company, including path etc.
function GetStylesheet(xmlnode, concept)
{
    var fso = new ActiveXObject("Scripting.FileSystemObject");

    var resxslsheet = custpath + "\\xsl\\" + xmlnode + "_concept.xsl";
    if (!concept || !fso.FileExists(Server.MapPath(resxslsheet)))
        var resxslsheet = custpath + "\\xsl\\" + xmlnode + ".xsl";
    if (!fso.FileExists(Server.MapPath(resxslsheet)))
        var resxslsheet = custpath + "\\xsl\\cust.xsl";
    if (!fso.FileExists(Server.MapPath(resxslsheet)))
        var resxslsheet = rooturl + "\\appl\\shared\\default.xsl";
    __Log('xsl-sheet to be used: '+resxslsheet);

    return resxslsheet;
}

function get_fac_xml(session_id)
{
    var sql = "SELECT fac_xml_xml"
            + "  FROM fac_xml"
            + " WHERE fac_session_id = " + safe.quoted_sql(session_id)
            + " ORDER BY fac_xml_volgnr";
    var oRs = Oracle.Execute( sql);
    var xml_content_arr = [];
    while (!oRs.eof)
    {
        xml_content_arr.push(oRs("fac_xml_xml").value);
        oRs.moveNext();
    }
    var xml_content = xml_content_arr.join("");
    oRs.Close();
    __Log("XML is {0} karakters. Opgehaald in {1} chunks.".format(xml_content.length, xml_content_arr.length));
    return xml_content;
}
function make_xml(params)
{
    var sql_params = safe.quoted_sql(params.xmlnode)
                   + ", " + params.key + " , "
                   + safe.quoted_sql(customerId)
                   + ", '$AspSession$'"
                   + ", " + (params.xtrakey ? params.xtrakey : 'NULL')
                   + ", " + (params.where ? safe.quoted_sql(params.where) : "''");

    if (String(Oracle.RealConnection.Properties("Provider Name")).match(/OraOLEDB/i))
    {
        var sql = "SELECT xml.make_xml2(" + sql_params + ") xml_blob FROM dual";
        var oRs = Oracle.Execute(sql);
        var xml_content = oRs("xml_blob").Value;
        if (!xml_content)
            shared.record_not_found();
		oRs.Close();
        __Log("XML blob is {0} karakters.".format(xml_content.length));
    }
    else // MSDAORA kan niet rechtstreeks BLOB's ophalen
    {
        var sql = "BEGIN xml.make_xml(" + sql_params + "); END;";
        Oracle.Execute(sql);
        var xml_content = get_fac_xml('$AspSession$');
    }
    if (Session("logging")&1)
        __Log2File(xml_content, params.xmlnode + params.key);
    return xml_content;
}

// Stuurt het resultaat rechtstreeks naar het Response object
//function FCLT2XMLResponse (xmlnode, key, xtrakey, pcompany, mode, where, srtnotificatie)
function FCLT2XMLResponse (params) {
    // params.
    //  xmlnode
    //  key
    //  xtrakey
    //  company   bedrijf waarvan stylesheet gebruikt moet worden (-1=self), tenzij stylesheet is meegegeven
    //  mode
    //  where
    //  srtnotificatie
    //  stylesheet
    // of nostyle
    //  concept

    var sql = '';

    if (params.key != -1)
    {
        var xml_content = make_xml(params);

        if (params.nostyle)
        {
            Response.Clear;
            Response.ContentType = "text/xml";
            Response.Write(xml_content);
        }
        else
        {
            if (!params.stylesheet)
                stylesheet = GetStylesheet(params.xmlnode, params.concept);
            else
                stylesheet = params.stylesheet;

            STR2Stream(xml_content, stylesheet, Response, params);
        }
        __Log("Done writing XML");
    }
    return true;

}

// Veel gebruikte functies vanuit API's

// http://davidwalsh.name/convert-xml-json
function xmlToJson(xml)
{
  // Create the return object
  var obj = {};

  if (xml.nodeType == 1)
  { // element
    // do attributes
    if (xml.attributes.length > 0)
    {
      obj["@attributes"] = {};
      for (var j = 0; j < xml.attributes.length; j++)
      {
        var attribute = xml.attributes.item(j);
        obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
      }
    }
  }
  else if (xml.nodeType == 3)
  { // text
    obj = xml.nodeValue;
  }

  // do children
  if (xml.hasChildNodes())
  {
    for(var i = 0; i < xml.childNodes.length; i++)
    {
      var item = xml.childNodes.item(i);
      var nodeName = item.nodeName;
      if (typeof(obj[nodeName]) == "undefined")
      {
        // JGL Added: Only one Textnode is simplified
        if (item.nodeType == 3 && xml.childNodes.length == 1)
            return item.nodeValue;

        obj[nodeName] = xmlToJson(item);
      }
      else
      {
        if (typeof(obj[nodeName].push) == "undefined")
        {
          var old = obj[nodeName];
          obj[nodeName] = [];
          obj[nodeName].push(old);
        }
        obj[nodeName].push(xmlToJson(item));
      }
    }
  }
  return obj;
};

// Luie oplossing: Oracle kan dit simpeler dan JavaScript.
function XMLtoJsDate(xmlDate)
{
    var sql = "SELECT TO_DATE(REPLACE("+safe.quoted_sql(xmlDate)+",'T',' '), 'YYYY-MM-DD HH24:MI:SS') FROM DUAL";
    //var sql = "SELECT TO_CHAR (TRUNC (TO_DATE(REPLACE("+safe.quoted_sql(xmlDate)+",'T',' '), 'YYYY-MM-DD HH24:MI:SS'), 'HH') + (15 * ROUND (TO_CHAR (TRUNC (TO_DATE(REPLACE("+safe.quoted_sql(xmlDate)+",'T',' '), 'YYYY-MM-DD HH24:MI:SS'), 'MI'), 'MI') / 15)) / 1440, 'DD-MM-YYYY HH24:MI:SS') FROM DUAL";
    var oRs = Oracle.Execute(sql);
    var dt = new Date(oRs(0).Value);
    oRs.Close();
    return dt;
}

function XMLval(xml, tag)
{
    if (!xml)
        return null;
    var xx = xml.getElementsByTagName(tag);
    if (!xx || !xx.length)
        return null;
    xx = xx[0].childNodes
    if (!xx || !xx.length)
        return null;
    return xx[0].nodeValue;
}

%>
