(function () {
    // todo. make this atomic
    var request_counter = 1;

    $(document).ajaxSend(function (e, xhr, options) {
        options.requestid = request_counter++;
        var log = window.log;
        options.log = function (category, message) { if (log && log.debug) log.debug(category, message); };
        var msg = "(" + options.requestid + ") ";

        msg = msg + "Sending ";
        msg = msg + options.type;
        msg = msg + " to " + options.url;
        if (options.data) {
            var dataText;
            if (typeof (options.data) == "string") dataText = options.data;
            else dataText = JSON.stringify(options.data);

            msg = msg + " (data: " + util.htmlEncode(dataText) + ")";
        }
        msg = msg + "...";
        if (options.log) options.log("ajax", msg);
    });

    $(document).ajaxError(function (e, xhr, options, error) {
        var msg = options.requestid ? ("(" + options.requestid + ") ") : "";

        msg = msg + "Error ";
        msg = msg + xhr.status + " (" + xhr.statustext + ")";
        if (error) msg = msg + ": " + error;
        msg = msg + " (data: " + util.htmlEncode(xhr.responseText) + ")";
        if (options.log) options.log("ajax", msg);
    });

    $(document).ajaxSuccess(function (e, xhr, options) {
        var msg = options.requestid ? ("(" + options.requestid + ") ") : "";

        msg = msg + "Success ";
        msg = msg + xhr.status + " (" + xhr.statustext + ")";
        msg = msg + " (data: " + util.htmlEncode(xhr.responseText) + ")";
        if (options.log) options.log("ajax", msg);
    });
})();

