// ******************************************
// * $Id$
// *
// *   UserException()
// *   RaiseAnError()
// *   TestAndRaiseAnXMLError()
// *   SafeLoadTextXML()
// *   SafeLoadFileXSL()
// *   XML2HTML()
// *   fetchXMLContent()
// *   mergeXMLAttachments()
// *   Hexify()
// *
// * XML en XSL functies.
// *
// ******************************************
//
function UserException(number, source, message)
{
   this.number = number;
   this.source = source;
   this.description = message;
}

function RaiseAnError(e, p)
{
    throw new UserException(e + 1000, "UserException", p);
}

function TestAndRaiseAnXMLError(p, iXml)
{
    if (iXml.parseError.errorCode != 0)
    {
        RaiseAnError( iXml.parseError.errorCode
                    , p + "\n" + iXml.parseError.reason
                        + " regel " + iXml.parseError.line
                              + "(" + iXml.parseError.filepos + ")"
                    );
    }
}

function SafeLoadTextXML(xmlText)
{
    var iXml = new ActiveXObject("Msxml2.DOMDocument.6.0");
    iXml.async = false;
    iXml.loadXML(xmlText);
    TestAndRaiseAnXMLError("Error in xmlData", iXml);

    return iXml;
}

function SafeLoadFileXSL(xslPath)
{
    var iXsl = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.6.0"); // Moet FreeThreaded voor XSLTemplate
    iXsl.async = false;
    iXsl.setProperty("AllowXsltScript", true);
    iXsl.load(custabspath + "/" + xslPath);
    iXsl.resolveExternals = true; // anders SOAP problemen om de template functie te vinden
    TestAndRaiseAnXMLError("Error loading file " + xslPath, iXsl);

    return iXsl;
}


function XML2HTML( body
                 , xslPath
                 , srtnotificatie
                 , mode
                 )
{
    // Transform body=xml according to xslPath=xslfilenaam with optionel srtnotification parameter (e.g. RESBEV)
    // Output is supposed to be a HTML string but really depends on the XSL content
    var xslt   = new ActiveXObject("Msxml2.XSLTemplate.6.0");
    var xslProc;

    var xslDoc = SafeLoadFileXSL(xslPath);
    var result = "";
    var xmlDoc = SafeLoadTextXML(body);

    xslDoc.resolveExternals = true; // anders op de volgende regel al:
                                    // A reference to variable or parameter 'srtnotificatiecode' cannot be resolved
    xslt.stylesheet = xslDoc;

    var xslProc = xslt.createProcessor();
    xslProc.input = xmlDoc;
    xslProc.addParameter("srtnotificatiecode", srtnotificatie);
    xslProc.addParameter("mode", mode);
    xslProc.transform();
    result = xslProc.output;

    return result;
}




function fetchXMLContent( node
                        , refkey
                        , xrefkey
                        , where
                        , userlang
                        )
{
    var xml_content = "";

    try
    {
        var xrefkeystr = (xrefkey == -1 ? "NULL" : safe.quoted_sql(String(xrefkey)));
        // we geven de gewenste taal mee aan de Oracle sessie, die dat verder zal gebruiken
        var sql = "BEGIN lcl.setuserlanguage (" + safe.quoted_sql(userlang) + "); END;"
        Log2File(3, sql);
        Oracle.Execute(sql);
        //
        var sql_params = safe.quoted_sql(node)
                                  + ", " + refkey
                                  + ", " + safe.quoted_sql(customerId)
                                  + ", '$PutOrdersSession$'"
                                  + ", " + xrefkeystr
                                  + ", " + safe.quoted_sql(where);
        var oradriver = Oracle;
        if (!oradriver.Properties)
            oradriver = oradriver.RealConnection; // Vanuit ASP
        if (String(oradriver.Properties("Provider Name")).match(/OraOLEDB/i))
        {
            var sql = "SELECT xml.make_xml2(" + sql_params + ") xml_blob FROM dual";
            Log2File(2, sql);
            var oRs = Oracle.Execute(sql);
            var xml_content = oRs("xml_blob").Value||"";
    		oRs.Close();
    		if (xml_content)
                Log2File(2, "XML blob is {0} karakters.".format(xml_content.length));
            else
                Log2File(1, "XML blob is leeg. Verwijderd record?");
        }
        else // MSDAORA kan niet rechtstreeks BLOB's ophalen
        {
            var sql = "BEGIN xml.make_xml( " + sql_params + "); END;";
            Log2File(2, sql);
            Oracle.Execute(sql);
            //
            var sql = "SELECT fac_xml_xml"
                    + "  FROM fac_xml"
                    + " WHERE fac_session_id = '$PutOrdersSession$'"
                    + " ORDER BY fac_xml_volgnr";
            Log2File(3, sql);
            var xml_content_arr = [];
            var oRXs = Oracle.Execute(sql);
            while( !oRXs.Eof)
            {
                xml_content_arr.push(oRXs("fac_xml_xml").value);
                oRXs.MoveNext();
            }
            var xml_content = xml_content_arr.join("");
            oRXs.Close();
            Log2File(2, "XML is {0} karakters. Opgehaald in {1} chunks.".format(xml_content.length, xml_content_arr.length));
        }
    }
    catch(e)
    {
        Log2File(0, "Error: " + e.description);
        xml_content = "";
    }
    finally
    {
        LogString2File(2, "make_xml", xml_content, "xml");
    }
    return xml_content;
}


function mergeXMLAttachments(iXml)
{
    // Doorzoek iXml op <!FCLTmeldingattachment>345</FCLTmeldingattachment>
    // en vervang die door alle flexkenmerken er onder
    // <Iattachements>
    //     <attachment>...hexdata...</attachtment>
    //      <name>naam</name>
    //      <size>1235</size>
    //    </attachment>
    // </Iattachments>
    var NodeList = iXml.documentElement.selectNodes("//FCLTmeldingattachment");
    if (NodeList.length > 0)
    {
        Log2File(1, "*> mergeXMLAttachments");

        for (var index=0; index < NodeList.length; index++)
        {
            var node = NodeList[index];
            var meldingkey = trimall(node.attributes.getNamedItem("meldingkey").text);
            var kenmerkkey = trimall(node.attributes.getNamedItem("kenmerkkey").text);
            var nodename   = trimall(node.attributes.getNamedItem("nodename").text);
            var AttachPath = S("flexfilespath") + "/MLD/" + subfolderKey("M", meldingkey) + "/" + kenmerkkey;
            Log2File(1, "AttachPath: " + AttachPath);

            var objFso = new ActiveXObject("Scripting.FileSystemObject");
            if (objFso.FolderExists(AttachPath))
            {
                var objFiles = objFso.GetFolder(AttachPath);
                var allFiles = new Enumerator(objFiles.files);
                for (; !allFiles.atEnd(); allFiles.moveNext())
                {
                    var attFile = allFiles.item();
                    Log2File(1, "Adding attachment: " + attFile.path + " (" + attFile.Size + " bytes)");
                    var elemAttachments = iXml.createElement(nodename);
                    var elemAtt = iXml.createElement("attachment");
                    elemAtt.text = Hexify(attFile.path);
                    elemAttachments.appendChild(elemAtt);
                    elemAtt = iXml.createElement("name");
                    elemAtt.text = attFile.name;
                    elemAttachments.appendChild(elemAtt);
                    elemAtt = iXml.createElement("size");
                    elemAtt.text = attFile.Size;
                    elemAttachments.appendChild(elemAtt);
                    node.parentNode.appendChild(elemAttachments);
                }
            }
            node.parentNode.removeChild(node); // dummy fcltattachments weg
        }
        Log2File(2, "*< mergeXMLAttachments");
    }
    return iXml;
}

function Hexify(p_path)
{
    var oStream = new ActiveXObject("ADODB.Stream");
    oStream.charset = "Windows-1252";
    oStream.Open();
    oStream.Type = 2; // adTypeText

    oZIP = new ActiveXObject("SLNKDWF.Zip");
    oZIP.FileToHexStream(p_path, oStream);

    oStream.Position = 0;
    ReadBytes = 131072; // optimaal volgens http://support.microsoft.com/kb/280067
    var result = "";
    while (!oStream.EOS)
    {
        result = result + oStream.ReadText(ReadBytes);
    }

    return result;
}
