var tm;
function callbackDone(data, textStatus, jqXHR)
{
    // jqXHR.getResponseHeader("ETag")
    $("#Status").text(jqXHR.status);
    $("#StatusText").text(textStatus);
    $("#Duration").text(Math.floor(new Date - tm) + "ms");
    var txt = String(jqXHR.responseText);
    $("#Result").text(txt);
    $("#ResultSize").text(txt.length);

    var objects_count = 1;
    if (jqXHR.responseText.indexOf("[") > 0)
    {
      var objects_name = jqXHR.responseText.substring(5, jqXHR.responseText.indexOf("[")-3);
      var objects_count = data[objects_name].length;
    }
    $("#Records").text(objects_count);
}
function callbackFail(jqXHR, textStatus, errorThrown)
{
    // FcltMgr.alert("FAIL: " + (typeof errorThrown == "string"?errorThrown:errorThrown.message));
    $("#Status").text(jqXHR.status + " " + (typeof errorThrown == "string"?errorThrown:errorThrown.message)).css("background-color", "red");
    $("#StatusText").text(textStatus);
    var txt = String(jqXHR.responseText);
    $("#Result").text(txt);
}
function doSubmit()
{
    $("#Status").text("Loading ... ").css("background-color", "");
    $("#StatusText").text("");
    $("#Records").text("");
    $("#Result").text("");
    var url = $("#url").val();
    var method = $("[name=method]:checked").val();
    if (method != "GET")
        var data = $("#xml").val();

    var apikey = $("#apikey").val();
    //jQuery.support.cors = true; // in IE niet al te moeilijk doen over cross-domain.
    tm = new Date;
    var cust_data = getCustBase($("#facid").val());
    if (cust_data.ApiHost != "")
    {
        var header = { "Authorization": cust_data.key
                     , "Accept": "application/json"
                     };
    }
    else
    {
        var header = { "X-FACILITOR-API-Key": apikey,
                       "X-CSRF-TOKEN": RVT_token,
                       "Content-type": "application/json"
                     };
    }
    $.ajax(url, { type: method,
                  data: data,
                  headers: header
                  // dan werkt de header niet dataType: "jsonp"
                }
          ).done(callbackDone).fail(callbackFail);
    //http_request.setRequestHeader("Content-Type", "text/xml; charset=utf-8")
}
function doBuild()
{
    var facid = $("#facid").val() || "UWVA";
    var pretty = $("#pretty:checked").val() == "on";
    var logging= $("#log:checked").val() == "on";
    var urlbase = $("#urlbase").val();
    var api = $("#api").val();

    var cust_data = getCustBase(facid);
    if (cust_data.url)
    {
        if (cust_data.ApiHost != "")
        {
            var url = urlbase + "/tas/api/" + api;
            url += "?fac_id="+facid;
            if (pretty)
                url += "&pretty=1";
            if (logging)
                url += "&logging=1";
            $("#urltest").html(url);
        }
        else
        {
            var apikey = $("#apikey").val();
            var scope = $("#scope").val();
            var format = $("[name=format]:checked").val();
            var url = urlbase + "/api2/" + api + "." + format;
            url += "?fac_id="+facid;
            if (scope)
                url += "&scope="+scope;
            if (pretty)
                url += "&pretty=1";
            if (logging)
                url += "&logging=1";
            $("#urltest").html(url + (pretty?"&":"?") + "apikey=" + apikey);
        }
    }
    else
    {
        var url = urlbase + "/api2/";
    }

    $("#url").val(url);
}

function doInit()
{
    $("#facid").change( change_facid );
    change_facid();
}

function process_api_list(data)
{
    $("#api").empty();
    var lastmodule = "";
    $.each( data.apis
          , function (index, value)
            {
                if (lastmodule != this.module)
                    $("#api").append("<optgroup label='" + this.modulecode + ": " + this.module + "'></option>");
                lastmodule = this.module;
                var apiname = this.id;
                $("#api").append("<option value="+ apiname +">" + apiname + "</option>");
            }
          );
}

function change_facid()
{
    var cust_data = getCustBase($("#facid").val());

    if (cust_data.url)
    {
        if (cust_data.ApiHost != "")
        {
            process_api_list(hosts[cust_data.ApiHost].data);
            $("#urlbase").val(cust_data.url);
        }
        else
        {
            var apikey = $("#apikey").val();
            $("#urlbase").val(cust_data.url);
            //jQuery.support.cors = true; // in IE niet al te moeilijk doen over cross-domain.
            var url = $("#urlbase").val() + "/api2/apis.json";
            $.ajax(url, { type: "GET",
                          //data: data,
                          headers: { "X-FACILITOR-API-Key": apikey,
                                     "X-CSRF-TOKEN": RVT_token
                                   }
                        // dan werkt de header niet dataType: "jsonp"
                        }
                  ).done(process_api_list).fail(callbackFail);
        }
    }
    else
    {
        process_api_list({}); // ongldige fac_id bij api_host
    }
}

function getCustBase(fac_id)
{
    var custid = fac_id.slice(fac_id.length-4).toUpperCase();
    var api_host = (fac_id.length > 4 ? fac_id.slice(0, -5) : "");

    var base = {};

    if (api_host)
    {
        var host_data = hosts[api_host];
        for (i=0; i<host_data.cust.length; i++)
        {
            if (host_data.cust[i].id == custid)
            {
                base = { ApiHost: api_host
                       , url: host_data.cust[i].adr
                       , key: host_data.cust[i].key
                       };
            }
        }
    }
    else
    {
        base = { ApiHost: ""
               , url: "http://" + custid.toLowerCase() + ".facws001.sg.nl" + tester_rooturl
               };
    }
    return base;
};

var hosts = { topdesk: { cust: [ { id: "TWYN"
                                 , usr: "FACILITOR-API"
                                 , adr: "https://myservicedesk-ont.twyn.nl"
                                 , key: "Basic uterwobxhistijd=="
                                 }
                               , { id: "STAM"
                                 , usr: "FACILITOR-API"
                                 , adr: "https://myservicedesk-ont.simac.nl"
                                 , key: "Basic RkFDSUxJVE9SLUFQSTpvYzdocS16YzJ2by1nZ3Bpdy1ldXh2aS1obm1pdA=="
                                 }
                               , { id: "UWVA"
                                 , usr: "FACILITOR-API"
                                 , adr: "https://myservicedesk-ont.uwva.nl"
                                 , key: "Basic lmnfglkdvngbd=="
                                 }
                               ]
                       , data: { apis: [ { modulecode: "MLD", module: "Incidenten", name: "Incidenten",       id: "incidents" }
                                       , { modulecode: "MLD", module: "Incidenten", name: "Soort melding",    id: "incidents/call_types" }
                                       , { modulecode: "MLD", module: "Incidenten", name: "Categorie",        id: "incidents/categories" }
                                       , { modulecode: "MLD", module: "Incidenten", name: "Subcategorie",     id: "incidents/subcategories" }
                                       , { modulecode: "MLD", module: "General",    name: "Personen",         id: "persons" }
                                       , { modulecode: "MLD", module: "Change",     name: "Alle templates",   id: "applicableChangeTemplates"}
                                       , { modulecode: "MLD", module: "Change",     name: "Toevoegen Change", id: "operatorChanges"}
                                       ]
                               }
                       }
            , zendesk: { cust: [ { id: "TWYN"
                                 , usr: "FACILITOR-API"
                                 , adr: "https://myzendesk-ont.twyn.nl"
                                 , key: "Basic uterwobxhistijd=="
                                 }
                               , { id: "UWVA"
                                 , usr: "FACILITOR-API"
                                 , adr: "https://myzendesk-ont.uwva.nl"
                                 , key: "Basic lmnfglkdvngbd=="
                                 }
                               ]
                       , data: { apis: [ { modulecode: "MLD", module: "Incidenten", name: "ZIncidenten",       id: "Zincidents" }
                                       , { modulecode: "MLD", module: "Incidenten", name: "ZSoort melding",    id: "Zincidents/call_types" }
                                       , { modulecode: "MLD", module: "Incidenten", name: "ZCategorie",        id: "Zincidents/categories" }
                                       , { modulecode: "MLD", module: "Incidenten", name: "ZSubcategorie",     id: "Zincidents/subcategories" }
                                       , { modulecode: "MLD", module: "General",    name: "ZPersonen",         id: "Zpersons" }
                                       , { modulecode: "MLD", module: "Change",     name: "ZAlle templates",   id: "ZapplicableChangeTemplates"}
                                       , { modulecode: "MLD", module: "Change",     name: "ZToevoegen Change", id: "ZoperatorChanges"}
                                       ]
                               }
                       }
            };
