﻿
(function($) {

    $.jsonAsmxService = function(path) {
        var url = path;

        this.call = function(fn, p, OK, target) {
            var pString;

            try {
                if (typeof (JSON) === 'object' && typeof (JSON.parse) === 'function') {
                    pString = JSON.stringify(p);
                } else {
                    if ($.toJSON == undefined) throw "Could not find the $.toJSON function. Search jquery.com to find this plugin."
                    pString = $.toJSON(p);
                }
            }
            catch (e) {
                alert(e);
                return;
            }
            var a = $.ajax({
                type: "POST",
                url: url + '/' + fn,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: pString,
                success: OK,
                error: $.jsonAsmxServiceFaild,
                target: target,
                async: OK != undefined
            });

            if (a.readyState == 4) {
                var ret;
                if (a.status != 200) {
                    $.debug(a.responseText);
                    return false;
                }

                if (typeof (JSON) === 'object' && typeof (JSON.parse) === 'function') {
                    ret = JSON.parse(a.responseText);
                } else {
                    ret = eval("(" + a.responseText + ")")
                }
                return ret.d;
            }

        }
    }

    $.debug = function(msg) {
        var bName = "debugWin";
        var win = $("#" + bName);

        if (!win.length) {
            win = $("<div />").attr("id", bName).appendTo("body");
            $(win).dialog({ "title": "Debug log" });
        }
        win.append('<div class="debug" >' + new Date().toLocaleTimeString() + ':' + msg + '</div>');
        win.dialog('open');

    }

})(jQuery)

jQuery.jsonAsmxServiceFaild = function(d) {
    var bName = "jsonAsmxServiceMsgBox";
    var msg = $("#" + bName);

    if (!msg.length) {
        msg = $("<div />").attr("id", bName).appendTo("body");
        $(msg).dialog({ "title": "Error log" });
    }

    var m;
    try {
        m = JSON.parse(d.responseText);
    }
    catch (e) { }

    if (m) {
        m = m.Message;
    } else {
        m = d.responseText;
    }

    msg.append("<h3>" + d.status + ' - ' + d.statusText + "</h3><div>" + m + "</div>");
    msg.dialog('open');
}


