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

    File:           zendesk.asp

    Description:    Conversie van xml naar json voor ZENdesk koppeling
    Parameters:
    Context:        Vanuit Putorders

    Notes:          Informatie m.b.t. Zendesk API : https://developer.zendesk.com/api-reference/
*/
DOCTYPE_Disable = true;
ANONYMOUS_Allowed = 1;
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/save2db.inc" -->
<!-- #include file="../Shared/Shared.inc" -->
<!-- #include file="../Shared/xml_converter.inc" -->
<!-- #include file="../api2/model_prs_bedrijfadres.inc" -->
<%
    var ll = getQParamInt("logging", 0);
    if (ll > 0)
        __Logging = ll; // Voor de rest van dit bestand

    var bdradr_key = getQParamInt("bdradr_key", -1); // is meegegeven voor templates die via @/appl/exp/topdesk.asp werken
    if (bdradr_key > 0)
    {
        var bdradr_data = new model_prs_bedrijfadres({ internal: true }).REST_GET({ filter: { id: bdradr_key } , include: [ "srtnotifications" ]});
        __DoLog(bdradr_data);
    }

    function getRequestParams(p_method, p_action, p_params)
    {
        var errmsg = "";
        var missing_id = false;
        var req_conn = { auth:        p_params.api_auth
                       , baseurl:     p_params.base_url
                       };
        var doel = getAction(p_action); // Gebruik hier de parameter uit de aanroep.
                                        // req_conn.actie wordt gewijzigd bij attachments als p_params.info.boundary bestaat.
        switch (p_method)
        {
            case "GET":     req_conn.ext_url = doel + (p_params.info.externid ? "/"+p_params.info.externid : "");
                            req_conn.methode = "GET";
                            req_conn.actie = p_action;
                            req_conn.content = "application/json";
                            break;
            case "POST":    req_conn.ext_url = doel + (p_params.info.params ? p_params.info.params : "");
                            req_conn.methode = "POST";
                            req_conn.actie = p_action;
                            req_conn.content = (p_params.info.mime ? p_params.info.mime : "application/json");
                            break;
            case "PUT":     missing_id = (p_params.info.externid ? false : true);
                            req_conn.ext_url = doel + "/" + p_params.info.externid;
                            req_conn.methode = "PUT";
                            req_conn.actie = p_action;
                            req_conn.content = "application/json";
                            break;
            case "DELETE":  req_conn.ext_url = doel + (p_params.info.params ? p_params.info.params : "");
                            req_conn.methode = "DELETE";
                            req_conn.actie = p_action;
                            req_conn.content = "application/json";
                            break;
            default:        req_conn.methode = "";
        }

        if (req_conn.methode == "" || missing_id)
        {
            errmsg = (missing_id ? "unknown id in " : "No method found for executing ") + doel;
        }
        return { success: (errmsg == "")
               , errmsg: errmsg
               , req_conn: req_conn
               }
    }   // getRequestParams

    function doRequest(req_conn, req_data)
    {
        var request_result = { success: false
                             , status: -1
                             , errmsg: ""
                             , data: {}
                             }
        try
        {
            var http_request = Server.CreateObject("WinHTTP.WinHTTPRequest.5.1");
            http_request.open(req_conn.methode, req_conn.baseurl + req_conn.ext_url, false); // Synchroon
            switch (req_conn.methode)
            {
                case "POST":    var body_data = (req_conn.actie == "attachment" ? req_data : JSON.stringify(req_data));
                                http_request.setRequestHeader("Authorization", req_conn.auth);
                                http_request.setRequestHeader("Accept", "application/json");
                                http_request.setRequestHeader("Content-Type", req_conn.content);
                                http_request.send(body_data);
                                break;
                case "PUT":     var body_data = (req_conn.actie == "attachment" ? req_data : JSON.stringify(req_data));
                                http_request.setRequestHeader("Authorization", req_conn.auth);
                                http_request.setRequestHeader("Accept", "application/json");
                                http_request.setRequestHeader("Content-Type", req_conn.content);
                                http_request.send(body_data);
                                break;
                case "GET":     http_request.setRequestHeader("Authorization", req_conn.auth);
                                http_request.setRequestHeader("Accept", "application/json");
                                http_request.send();
                                break;
                case "DELETE":  http_request.setRequestHeader("Authorization", req_conn.auth);
                                http_request.setRequestHeader("Accept", "application/json");
                                http_request.send();
                                break;
            }
            //
            request_result.status = http_request.status;
            var status_ok = [200,201,204,206];
            if (inArray(request_result.status, status_ok))
            {   // Request is goed verlopen.
                request_result.success = true;
                request_result.data = (http_request.responseText ? JSON.parse( http_request.responseText) : {});
            }
            else
            {   // De tekst van de foutstatus.
                request_result.errmsg = http_request.statusText
                                      + ":\n" + http_request.responseText;
            }
        }
        catch (e)
        {   // Het gaat al fout bij het maken van de request.
            request_result.status = 602;
            request_result.errmsg = "Request connection error: " + e.description;
        }
        return request_result;
    }   // doRequest

    function callRequest(p_request, p_data_to_sent)
    {
        __Log(">>callRequest");
        var bevinding = {};
        if (p_request.info.method != 'NONE')
        {
            var conn_params = getRequestParams(p_request.info.method, p_request.info.action, p_request);
            if (conn_params.success)
            {
                __Log({"conn_params": conn_params.req_conn, "data": p_data_to_sent});
                if (p_request.info.noRequest)
                {
                    bevinding = { result: { success: true
                                          , status: 200
                                          , message: ""
                                          }
                                , data: {ticket: {custom_fields: {}, fields: {}, audit: {}}}
                                }
                }
                else
                {
                    var conn_result = doRequest(conn_params.req_conn, p_data_to_sent);
                    if (conn_result.success)
                    {
                        bevinding = { result: { success: true
                                              , status: conn_result.status
                                              , message: conn_result.errmsg
                                              }
                                    , data: conn_result.data
                                    };
                    }
                    else
                    {   // Een foutmelding van request of een algemene fout.
                        bevinding = { result: { success: false
                                              , status: conn_result.status
                                              , message: conn_result.errmsg
                                              }};
                    }
                }
            }
            else
            {   // Er is iets fout gegaan met het maken van de request parameters.
                bevinding = { result: { success: false
                                      , status: 601
                                      , message: conn_params.errmsg
                                      }};
            }
        }
        else
        {
            bevinding = { result: { success: true
                                  , status: 200
                                  , message: "er hoeft geen bericht verstuurd te worden"
                                  }};
        }
        return bevinding;
    }   // callRequest

    function encryptAuth(api_user, api_key)
    {
        var oCrypto = new ActiveXObject("SLNKDWF.Crypto");
        var encoded = "Basic " + oCrypto.base64(api_user + "/token:" + api_key);
        return encoded;
    }   // encryptAuth

    function cloneObject(obj)
    {
        var cloned_obj = JSON.parse(JSON.stringify(obj));
        return cloned_obj;
    }   // cloneObject

    function getTypeOf(value)
    {
        if (typeof value === "string" || value instanceof String)               return "isString";
        if (typeof value === "number" && isFinite(value))                       return "isNumber";
        if (typeof value === "boolean")                                         return "isBoolean";
        if (typeof value === "symbol")                                          return "isSymbol";
        if (typeof value === "undefined")                                       return "isUndefined";
        if (typeof value === "function")                                        return "isFunction";
        if (value === null)                                                     return "isNull";
        if (value && typeof value === "object" && value.constructor === Array)  return "isArray";
        if (value && typeof value === "object" && value.constructor === Object) return "isObject";
        if (value && typeof value === "object" && value.constructor === RegExp) return "isRegExp";
        if (value instanceof Error && typeof value.message !== "undefined")     return "isError";
        if (value instanceof Date)                                              return "isDate";
        return "isUnknown";
    }   // getTypeOf

    function objectlist_to_array(p_objectlist)
    {
        var t = getTypeOf(p_objectlist);
        switch (t)
        {
            case "isUndefined": var obj_arr = [];             break; // geen bijlagen
            case "isObject":    var obj_arr = [p_objectlist]; break; // 1 bijlage
            case "isArray":     var obj_arr = p_objectlist;   break; // 2 of meer bijlagen
            default:            var obj_arr = [];
        }
        return obj_arr;
    }   // objectlist_to_array

    function getMimeType(p_filename)
    {
        var mimetypes = { "":          null
                        , "3gp":       "video/3gpp"
                        , "7z":        "application/x-7z-compressed"
                        , "avi":       "video/x-msvideo"
                        , "bmp":       "image/bmp"
                        , "csv":       "application/csv"
                        , "doc":       "application/msword"
                        , "docx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        , "dot":       "application/msword"
                        , "dwf":       "model/vnd.dwf"
                        , "dwg":       "image/vnd.dwg" //  application/acad  image/x-dwg
                        , "eml":       "message/rfc822"
                        , "encrypted": "application/octet-stream"
                        , "gif":       "image/gif"
                        , "gz":        "application/gzip"
                        , "gzip":      "application/gzip"
                        , "jpeg":      "image/jpeg"
                        , "jpg":       "image/jpeg"
                        , "m4v":       "video/m4v"
                        , "mcw":       "application/msword"
                        , "mov":       "video/quicktime"
                        , "mp4":       "video/mp4"
                        , "msg":       "application/vnd.ms-outlook"
                        , "oft":       "application/vnd.ms-outlook"
                        , "pdf":       "application/pdf"
                        , "png":       "image/png"
                        , "ppt":       "application/vnd.ms-powerpoint"
                        , "pptx":      "application/vnd.openxmlformats-officedocument.presentationml.presentation"
                        , "rar":       "application/vnd.rar"
                        , "rtf":       "application/rtf"
                        , "tif":       "image/tiff"
                        , "tiff":      "image/tiff"
                        , "txt":       "text/plain"
                        , "vsd":       "application/vnd.ms-visio"
                        , "xls":       "application/vnd.ms-excel"
                        , "xlsx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        , "xml":       "application/xml"
                        , "zip":       "application/zip"
/*                      , "webp":      "image/webp"
                        , "webm":      "video/webm"
                        , "weba":      "audio/weba"
                        , "mp3":       "audio/mpeg"
                        , "wav":       "audio/wav"
                        , "json":      "application/json"
                        , "js":        "text/javascript"
*/                      }

        if (new RegExp(S("flexAllowedExt"), "ig").test(p_filename))
        {
            var arr = p_filename.split(".");
            var ext = ((arr.length > 1) ? arr.pop() : "");
            var mimetype = mimetypes[ext.toLowerCase()];
        }
        else
        {
            __Log("Niet ondersteunde extensie van " + p_filename);
        }
        return mimetype;
    }   // getMimeType

    function load_headerdata()
    {
        __Log("load_headerdata");
        // Lees de xml-data uit de html-header.
        var xmlReq = Server.CreateObject("MSXML2.DOMDocument.6.0");
        xmlReq.load(Request);
        // Converteer de xml naar json-dataobject.
        var objreq = xmlToJson(xmlReq);
        return objreq.facilitor;
    }   // load_headerdata

    // *************************************************************************
    function test_loader()
    {
        __Log("TEST_LOADER");
        function loadMSXML(x)
        {
            var fso = new ActiveXObject("Scripting.FileSystemObject");
            var file_ext = x.file.slice(-4);
            var ForReading = 1;
            var f1 = fso.OpenTextFile(x.file, ForReading );
            var text = f1.ReadAll();
            f1.Close();
            if ((text.substr(0,14) != "<?xml version=") && (file_ext == ".xml"))
            {   // Bij ontbreken van encoding in de xml-file treedt de fout
                // "An invalid character was found in the text content"
                // op als er diakritische tekens in het xml-bestand staan.
                // Voeg daarom encoding toe.
                text = "<?xml version='1.0' encoding='windows-1250'?>" + "\n\r" + text;
            }

            x.doc = new ActiveXObject("MSXML2.DOMDocument.6.0");
            x.doc.async = false;
            x.doc.loadXML(text);
            x.err_code = x.doc.parseError.errorCode;
            x.err_msg = (x.doc.parseError.errorCode != 0 ? x.doc.parseError.reason : "");
            return x;
        }

        var custpath = "../../CUST/WELK";
        var loader = { success: false
                     , status: -1
                     , xml: { file: Server.MapPath(custpath + "/xsl/" + "OPDR_00_make_xml.xml") }
                     , xsl: { file: Server.MapPath(custpath + "/xsl/" + "zendesk.xsl") }
                     };
        loader.xml = loadMSXML(loader.xml);
        loader.xsl = loadMSXML(loader.xsl);
        loader.success = (loader.xml.err_code == 0 && loader.xsl.err_code == 0);
        __Log( {"load_err": { "xml": {"path": loader.xml.file, "code":loader.xml.err_code, "msg":loader.xml.err_msg}
                            , "xsl": {"path": loader.xsl.file, "code":loader.xsl.err_code, "msg":loader.xsl.err_msg}
                            }
               });

        var result = { success: false
                     , status: (loader.xml.err_code != 0 ? loader.xml.err_code : loader.xsl.err_code)
                     , message: (loader.xml.err_code != 0 ? loader.xml.err_msg : loader.xsl.err_msg)
                     , data: {}
                     }
        if (loader.success)
        {
            if ((debug & 2) == 0)
            {
                var transform = new ActiveXObject("MSXML2.DOMDocument.6.0");
                transform.async = false;
                transform.validateOnParse = true;
                loader.xml.doc.transformNodeToObject(loader.xsl.doc, transform);
                //__Log(transform.documentElement.xml);
                result = { success: (transform.parseError.errorCode == 0)
                         , status: transform.parseError.errorCode
                         , message: (transform.parseError.errorCode != 0 ? transform.parseError.reason : "")
                         }
                if (result.success)
                {
                    var obj = xmlToJson(transform);
                    delete obj.xml;
                    result.data = obj;
                }
            }
            else
            {
                var obj = xmlToJson(loader.xml.doc);
                delete obj.xml;
                result.data = obj;
            }
        }
        __Log(result);
        return result.data.facilitor;
    }   // test_loader

    function getAction(p_action)
    {
        var actions = { "ticket": "/api/v2/tickets"
                      , "attachment": "/api/v2/uploads"
                      , "upsert_user": "/api/v2/users/create_or_update"
                      , "request": "/api/v2/requests"
                      , "brand": "/api/v2/brands"
                      , "organization": "/api/v2/organizations"
                      , "group": "/api/v2/groups"
                      }
        var v_endpoint = actions[p_action];
        return v_endpoint;
    }   // getAction

    function uploadAttachments(p_request, p_data)
    {
        __Log("uploadAttachments");
        var v_success = true;
        var v_token_arr = [];
        var v_comment_arr = [];
        var v_request = cloneObject(p_request);
        var bijlagen = objectlist_to_array(p_data.bijlagen);
        for (var i=0; i < bijlagen.length; i++)
        {   // Ga de bijlagen een voor een uploaden.
            var bijlage = bijlagen[i];

            var sql = "SELECT r.fac_bijlagen_disk_directory"
                    + "     , r.fac_bijlagen_filename"
                    + "     , r.fac_bijlagen_file_size"
                    + "  FROM fac_bijlagen r"
                    + "     , fac_bijlagen b"
                    + " WHERE b.fac_bijlagen_root_key = r.fac_bijlagen_key"
                    + "   AND b.fac_bijlagen_verwijder IS NULL"
                    + "   AND r.fac_bijlagen_verwijder IS NULL"
                    + "   AND b.fac_bijlagen_key = " + bijlage.bijlagekey;
            var oRs = Oracle.Execute(sql);
            var f_path = oRs("fac_bijlagen_disk_directory").Value;
            var f_name = oRs("fac_bijlagen_filename").Value;
            var f_size = oRs("fac_bijlagen_file_size").Value;
            var filepath = S("flexfilespath") + "/" + f_path + "/" + f_name;
            oRs.Close();

            v_request.info = { method: "POST"
                             , action: "attachment"
                             , params: "?filename=" + safe.url(f_name)
                             , mime: getMimeType(f_name)
                             };

            if (v_request.info.mime)
            {   // Alleen inlezen als er een geldige mime-type is.
                v_request.info.boundary = "eWmWdiyWZVsqRAlEjgwicQsLnvXBJAVw"; // random genoeg, als het maar niet voorkomt in de data
                v_request.info.filename = f_name;
                v_request.info.filesize = f_size;
                //
                var BinaryStream = new ActiveXObject("ADODB.Stream");
                BinaryStream.Type = 1; // adTypeBinary
                BinaryStream.Open();
                BinaryStream.LoadFromFile(filepath);
                var data_to_sent = BinaryStream.Read;
                //
                var bevinding = callRequest(v_request, data_to_sent);   // verstuur de bijlage
                if (bevinding.result.success)
                {
                    v_comment_arr.push("Attachment [" + f_name + " ("+ f_size +")] toegevoegd.");
                    v_token_arr.push(bevinding.data.upload.token);
                    //bevinding.data.upload.attachment.id;
                    //bevinding.data.upload.attachment.url;
                    //bevinding.data.upload.attachment.content_url;
                }
                else
                {
                    v_comment_arr.push("Attachment [" + f_name + " ("+ f_size +")] kon niet worden toegevoegd,\n"
                                      +"status: " + bevinding.result.status + " " + bevinding.result.message
                                      );
                    v_success = false;
                }
            }
            else
            {
                v_comment_arr.push("Attachment [" + f_name + " ("+ f_size +")] kon niet worden toegevoegd,\n"
                                  +"status: 602 Niet ondersteunde bestand extensie"
                                  );
                v_success = false;
            }
        }

        if (bijlagen.length > 0)
        {   // Data van bijlagen kan nu verwijderd worden.
            delete p_data.bijlagen.bijlage;
            __Log({"bijlagen":v_comment_arr.join("\n")});
        }

        if (v_success)
        {   // Alle bijlagen geupload of er zijn geen bijlagen meegegeven.
            var v_attachment = { result: { success: true
                                         , status: 201
                                         , message: ""
                                         }
                               , tokens: v_token_arr
                               };
        }
        else
        {   // Minimaal een van de uploads is niet gelukt. Alles weer verwijderen.
            var v_attachment = { result: { success: false
                                         , status: 406
                                         , message: v_comment_arr.join("\n")
                                         }
                               };
            for (var i=0; i<v_token_arr.length; i++)
            {
                v_request.info = { method: "DELETE"
                                 , action: "attachment"
                                 , params: "/" + v_token_arr[i]
                                 };
                var bevinding = callRequest(v_request);
                if (bevinding.result.status != 204) // 204=no content
                {
                    __Log("Fout bij verwijderen bijlage: " + bevinding.result.status + ": " + bevinding.result.message);
                }
            }
        }
        return v_attachment;
    }   //uploadAttachments

    function getTicket(p_data, p_bijlagen)
    {
        __Log("getTicket");
        var v_data = {};
        v_data.ticket = cloneObject(p_data.opdracht);
        // custom_fields moet een array worden.
        v_data.ticket.custom_fields = objectlist_to_array(v_data.ticket.custom_fields);
        if (p_bijlagen.length > 0)
        {   // bijlage tokens meegeven
            v_data.ticket.comment.uploads = p_bijlagen;
        }
        return v_data;
    }   // getTicket

    function getTicketComment(p_data, p_bijlagen, p_request)
    {
        function getObjectValue(p_obj_data, p_node)
        {
            var v_node_arr = p_node.split(".");
            var v_obj = p_obj_data;
            for (var i=0; i<v_node_arr.length; i++)
            {   // ittereer door object tot aangegeven veld.
                v_obj = v_obj[v_node_arr[i]];
            }
            return v_obj;
        }

        function setObjectValue(p_obj_data, p_node, p_value)
        {
            var v_node_arr = p_node.split(".");
            var v_obj = p_obj_data;
            var i;
            for (i=0; i<v_node_arr.length-1; i++)
            {
                v_obj = v_obj[v_node_arr[i]];
            }
            v_obj[v_node_arr[i]] = p_value;
            return p_obj_data[v_node_arr[0]];
        }

        __Log("getTicketComment");
        var v_ticket = p_data.notitie;
        v_ticket.ticket.comment.body = shared.stripbbcodes(v_ticket.ticket.comment.body); // verwijder opmaak codes uit notitie
        if (p_bijlagen.length > 0)
        {   // bijlage tokens meegeven
            v_ticket.ticket.comment.uploads = p_bijlagen;
        }

        var v_notitie = { result: { success: false
                                  , status: 610
                                  , message: "No comment found"
                                  }
                        };
        // Zoek een waarde op en voeg die aan het object toe.
        if (p_data.lookup_list && p_data.lookup_list.lookup)
        {
            var lookup_request = cloneObject(p_request);
            var v_lookup_list = cloneObject(p_data.lookup_list.lookup);
            if (v_lookup_list && getTypeOf(v_lookup_list) != "isArray")
            {
                v_lookup_list = [v_lookup_list];
            }
            for (var i=0; i<v_lookup_list.length; i++)
            {
                __Log("opzoeken: " + v_lookup_list[i].action);
                var lookup_data_to_sent = v_lookup_list[i].data;
                //__Log(lookup_data_to_sent);
                lookup_request.info = { method: v_lookup_list[i].method
                                      , action: v_lookup_list[i].action
                                      , noRequest: false // forceer dat opzoeken in ieder geval wel mag
                                      };

                var lookup_result = callRequest(lookup_request, lookup_data_to_sent);
                v_notitie.result = lookup_result.result; // Bij meerder lookup's blijft alleen de status van de laatste bewaard!
                if (lookup_result.result.success)
                {   // Vul de waarde in die net is opgezocht.
                    var v_lookup_value = getObjectValue(lookup_result.data, v_lookup_list[i].src);
                    __Log("gevonden: " + v_lookup_value);
                    v_ticket = setObjectValue(p_data, v_lookup_list[i].dest, v_lookup_value);
                }
            }

            v_notitie.notitie = v_ticket;
        }
        else
        {   // Er staat geen lookup en lookup_list node in de xml.
            v_notitie = { result: { success: true
                                  , status: 200
                                  , message: ""
                                  }
                        , notitie: v_ticket
                        };
        }
        return v_notitie;
    }   // getTicketComment

    function editResponseData(p_mode, p_data)
    {   // De parameter p_data is ByRef. Kopieer deze en verwijder daaruit de niet relevante nodes.
        // Voeg het resultaat weer toe aan p_data.
        __Log("editResponseData");
        var data_received = cloneObject(p_data.data);
        delete data_received.ticket.custom_fields; // bevat alleen lege velden
        delete data_received.ticket.fields;        // bevat alleen lege velden
        if (p_mode == "OPDRACHT")
        {
            delete data_received.audit;            // nu niet nodig maar bevat misschien wel nuttige informatie
        }
        delete p_data.data;
        p_data.data = data_received;
        // geen return !
    }   // editResponseData

    function update_mldopdr(p_methode, p_actie, p_ticket)
    {
        if (p_methode == "POST" && p_actie == "ticket")
        {
            __Log("update_mldopdr");
            var zendesk_id = (isNaN(p_ticket.id) ? 0 : p_ticket.id); // Dit is het ticket-id van Zendesk, gegeven als integer, zie https://developer.zendesk.com/api-reference/ticketing/tickets/tickets/.
            var facilitor_id = (shared.isGoodNumber(p_ticket.external_id, true,true, -1, -1) ? parseInt(p_ticket.external_id) : 0); // Dit is de mld_opdr_key uit Facilitor, gegeven als string.
            if (zendesk_id > 0 && facilitor_id > 0)
            {
                var sql = "UPDATE mld_opdr"
                        + "   SET mld_opdr_externnr = " + safe.quoted_sql(String(zendesk_id))
                        + "     , mld_opdr_id = " + safe.quoted_sql(String(zendesk_id))
                        + " WHERE mld_opdr_key = " + facilitor_id;
                Oracle.Execute(sql);
            }
        }
    }   // update_mldopdr

    function zendesk_main(facilitor)
    {
        var v_bevinding = {};
        var v_data = facilitor.zendesk.data;
        var v_request = facilitor.zendesk.request;
        v_request.api_auth = encryptAuth(v_request.api_user, v_request.api_key);

        // eerst de bijlagen versturen
        var bevinding = uploadAttachments(v_request, v_data);
        v_bevinding.result = bevinding.result;
        v_bevinding.attach = bevinding;
        if (bevinding.result.success)
        {   // Er zijn geen bijlagen of alle bijlagen zijn succesvol geupload.
            var v_bijlagen = bevinding.tokens;

            switch (v_request.mode)
            {
                case "OPDRACHT":    var data_to_sent = getTicket(v_data, v_bijlagen);
                                    var bevinding = callRequest(v_request, data_to_sent);
                                    v_bevinding.result = bevinding.result;
                                    v_bevinding.ticket = bevinding;
                                    if (bevinding.result.success)
                                    {
                                        editResponseData("OPDRACHT", bevinding);
                                        update_mldopdr(v_request.info.method, v_request.info.action, bevinding.data.ticket);
                                    }
                                    break;
                case "NOTITIE":     var bevinding = getTicketComment(v_data, v_bijlagen, v_request);
                                    v_bevinding.result = bevinding.result;
                                    v_bevinding.comment = bevinding;
                                    if (bevinding.result.success)
                                    {
                                        var data_to_sent = bevinding.notitie;
                                        var bevinding = callRequest(v_request, data_to_sent);
                                        v_bevinding.result = bevinding.result;
                                        v_bevinding.ticket = bevinding;
                                        if (bevinding.result.success)
                                        {
                                            editResponseData("NOTITIE", bevinding);
                                        }
                                    }
                                    break;
            }
        }
        // else: Eventuele fouten staan al in bevindingen die terugkomen uit uploadAttachments().
        return v_bevinding;
    }   // zendesk_main

    // *************************************************************************
    // *************************************************************************
    __Log("*> ZENdesk.api");
    // debug:   0 geen debugging
    //          1 gebruik xxx_make_xml.xml en transformeer deze met zendesk.xsl
    //          2 gebruik xxx_transformed.xml zonder zendesk.xsl (dus een al getransformeerde xml, bijv. voor toegevoegde bijlage data)
    var debug = 0;

    var facilitor = ((debug > 0) ? test_loader() : load_headerdata());
    var bevinding = {};

    __Log({"DATA_LOADED":facilitor});
    if (facilitor && facilitor.zendesk)
    {
        bevinding = zendesk_main(facilitor);
    }
    else
    {   // Ongeldige json-data
        bevinding = { result: { success: false
                              , status: 600
                              , message: "ongeldige invoer"
                              }};
    }

    if (bevinding.result.message != "")
    {   // Een serieuze fout nadrukkelijk in de logging zetten.
        __DoLog( bevinding.result.status + ": " + bevinding.result.message
               , (bevinding.result.success ? "" : "#ff0000")
               );
    }

    bevinding.response_status = (bevinding.result.success ? 200 : 400);
    __Log({"Bevinding:": bevinding});
    __Log("*< ZENdesk.api: " + bevinding.response_status);
    Response.Status = bevinding.response_status;
    //Response.Write(JSON.stringify(bevinding));
%>
<% ASPPAGE_END(); %>
