/*
 * JSON RPC requester for jQuery
 * 
 * (c) 2009 Peter Cicman, Divio GmbH
 * 
 * 
 * Requires jquery.json-1.3.js from Brantley Harris.
 *  
 */

(function($) {	
	var gatewayURL = '/gw/';
	var requestCounter = 0;
		
	function request(method, params, callback) {
		var prms = params == undefined ? [] : ( params.constructor == Array ? params : [params] ); 
		var jsonData = $.toJSON({id: ++requestCounter, method: method, params: prms});
		
		$.ajax({
			url: gatewayURL,
			type: "POST",
			dataType: "json",
			data: jsonData,
			complete: function(res, status){
				if (status == "success" || status == "notmodified") {
					var response = $.secureEvalJSON(res.responseText);
					
					// check for response.error ...? (contatins error name)
					
					var result = {
						'content': (response.result.content || response.result),
						'obj': response.result
					}
					
					//if (response.etime) 
					//	console.info('RPC backend', response.etime);
					
					//console.log('res', result);
					callback(result.content.toString(), result.obj, status, res);
				} else {
					//console.error('RPC error');
					callback(null, null, status, res);
				}
				
			}
		});
	}
	
	
	/**
	 * Calls remote function, and pass response object to callback function. 
	 * Response object is json decoded object. Element content is replaced with 
	 * response.content.
	 * 
	 * @param {String} method Remote method, eg. rating.views.rate
	 * @param {Array/Object} params Arguments for remote method
	 * @param {Function} callback Callback function, receives object, status and
	 * 							  response object. Callback function is called in
	 * 							  both, successfull or non successfull case.
	 */
	$.fn.R = function(method, params, callback){
		// for elements...
		var self = this;
		
		request(method, params, function(content, obj, status, res){
			// place content into element
			if (status == "success" || status == "notmodified") {
				/* 
				self.html(selector ? // Create a dummy div to hold the results
				$("<div/>")	// inject the contents of the document in, removing the scripts
				// to avoid any 'Permission Denied' errors in IE
				.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))	// Locate the specified elements
				.find(selector) : // If not, just inject the full result
				res.responseText);
				*/
				
				// does this works properly under IE with <script tags ?
				self.html(content);
			}
			
			// apply obj to callbacks
			if (callback) {
				self.each(callback, [obj, status, res]);
			}
		});
	}
	
	
	/**
	 * Calls remote function, and pass response object to callback function. 
	 * Response object is json decoded object.
	 * 
	 * @param {String} method Remote method, eg. rating.views.rate
	 * @param {Array/Object} params Arguments for remote method
	 * @param {Function} callback Callback function, receives object, status and
	 * 							  response object. Callback function is called in
	 * 							  both, successfull or non successfull case.
	 */
	$.R = function(method, params, callback) {
		var self = this;
		
		request(method, params, function(content, obj, status, res){
			callback(obj, status, res);
		});
	}

})(jQuery);