// An RPC service for the client side to communicate with the server side
// using JSON data.
(function() {
	jQuery.extend({
		jsonRpc: function( controller, action ) {
			var callback = undefined;
			var data = {};
			if (arguments.length < 2) {
				console.error("jsonRpc calls need a Controller name and an Action name.");
				return;
			} else if (arguments.length == 2) {
				data.parameters = "{}";
			} else {
				var variables = [];
				for (var pos = 2; pos < arguments.length; ++pos) {
					if (pos == arguments.length - 1 && jQuery.isFunction(arguments[pos])) {
						callback = arguments[pos];
					} else {
						variables.push(arguments[pos]);
					}
				}
				
				data.parameters = $.toJSON(variables);
				variables = undefined;
			}
			data.controller = controller;
			data.action = action;
			
			var xhr;
			var customCallback = function(response) {
				if (xhr.callback && jQuery.isFunction(xhr.callback)) {
					xhr.callback(response);
				}
			};
			
			xhr = jQuery.ajax({
				type: "POST",
				url: rainier.root + '/rainier.php?json=1',
				data: data,
				success: customCallback,
				dataType: "json"
			});
			
			xhr.callback = callback;
			xhr.addCallback = function(func) {
				xhr.callback = func;
			};
			
			return xhr;
		}
	});
})();
