(function($){

$.jsonRpc = $.jsonRpc || function(options) {
    options.type = options.type || 'GET';
    var ajaxOptions = {
        contentType: 'application/json',
        dataType:  options.type == 'GET' ? 'jsonp' : 'json',
        processData: options.type == 'GET'
    };

    var data = {
        version: options.version || '1.0',
        method: options.method || 'system.listMethods',
        params: options.params || [],
        id: options.id || 'jsonrpc',
        jsonrpc: options.version || '1.0'
    };
    $.each(data, function(i){ delete options[i] });

    function send() {
        options.data = JSON.stringify(data);
        if (options.type == 'GET') options.data = {json: options.data};
        $.ajax($.extend(ajaxOptions, options));
    }
    
    if (typeof JSON == 'undefined') {
        $.getScript('http://www.json.org/json2.js', function(){ send() });
    } else {
        send();
    }
    return $;
};

})(jQuery);

var callback = function(cb, data, status) {
    if (typeof data.result == 'object') {
        if ('html' in data.result)
            for (tag in data.result.html)
                $(tag).html(data.result.html[tag])
        if ('alert' in data.result)
            alert(data.result.alert)
        if ('eval' in data.result)
            eval(data.result.eval)
    }
    if (typeof cb == 'function')
        cb(data, status)
}

window.rpc = function(method, params, cb, ecb){
    var url = '/json/'
    jQuery.jsonRpc({
        url: url, 
        type: 'POST', 
        method: method, 
        params: params,
        success: function(data, st){callback(cb, data, st)},
        error: ecb
        })
}

