/*
 * JSON RPC requester
 * 
 * (c) 2007-2008 Peter Cicman, Divio GmbH 
 */

var JsonRpcSettings = {
	'onRemoteError': function(msg) { 
		//console.error('json rpc error: ', msg); // #DEBUG 
	},
	'gateway': '/gw/'
};

var JsonRpc = Ajax.extend({
	_stop: false,
	
	initialize: function(options){
		var _options = options || {};
		var url = _options.url || JsonRpcSettings.gateway;
		this.parent(url, _options || {});
		this.setHeader('X-Request', 'X-JSON');
				
	},
	onComplete: function() {
		if (this._stop) return;
		if (this.options.update) $(this.options.update).empty().setHTML(this.response.content);
		if (!window.ie)
			this.evals();
		this.fireEvent('onComplete', [this.response.obj], 20);	
	},
	evals: function(process) {
		if (process || this.options.evalScripts || this.options.evalResponse) { 		
			this.response.text = this.response.content;
			this.evalScripts();	
		}
	},
	
	/**
	 * Creates remote call. 
	 * 
	 * @param {String} method Remote callable method, like qpointi.paring.views.test
	 * @param {Object} params Optional 
	 */
	rcall: function(method, params) {
		var prms = params || [];
		var data = Json.toString({id: 0, method: method, params: prms.constructor == Array ? prms : [prms]});
		this.request(data);
	},
	
	onSuccess: function(){
		if (this._stop) return;
		// handle erros first !
		var obj = Json.evaluate(this.transport.responseText);
		if($defined(obj.error)) {
			JsonRpcSettings.onRemoteError(obj.error);
			return;
		}
		this.response = {
			'content': $defined(obj.result.content) ? obj.result.content : obj.result,
			'obj': obj.result
		};
		this.fireEvent('onSuccess', this.response.obj);
		if (window.ie)
			this.evals();
		this.callChain();
	},
	
	stop: function(){
		this._stop = true;
	}
});
