/*  $Id$
 *  
 *  This file is part of the Jamiedia Toolkit.
 *  Copyright 2007/2008, Jamiedia Ltd., http://www.jamiedia.co.uk
 *  
 *  This file may not be used or (re)distributed for any other
 *  purposes than a commercial deployment by Jamiedia of a system
 *  based on the Jamiedia Toolkit. No modifications may be made to
 *  this file by anyone, except for individuals working for Jamiedia Ltd.
 *
 *  File description: Provides JSON-RPC implementation. Requires jQuery and jQuery JSON plugin to be loaded first!
 *
 */ 

Jamiedia.RPC = function(options) {
	this.init(options);
}

Jamiedia.RPC.prototype = {
	id: 0,
	url: null,
	onSuccess: function(data) {},
	onError: function(error) {
		alert('Error '+error.code+': '+error.message);
	},
	onTransportError: function(message) {
		alert('Error: '+message);
	},
	init: function(options) {
		if (!options)
			return false;
	
		if (options.url)
			this.url = options.url;
		else
			return false;
			
		if (options.successCallback)
			this.onSuccess = options.successCallback;
			
		if (options.errorCallback)
			this.onError = options.errorCallback;
			
		if (options.onTransportError)
			this.onTransportError = onTransportError;
	},
	invoke: function(method, params, successCallback, errorCallback) {
		var _this = this;

		var data = { 
			jsonrpc: '2.0',
			method: method,
			id: ++this.id
		};

		if (!(typeof(params) == 'undefined' || params == null))
			data.params = params;
		
		jQuery.ajax({
			url: _this.url,
			dataType: 'json',
			type: 'POST',
			data: jQuery.toJSON(data),
			success: function(json) {
				if (typeof(json.result) == 'undefined' && typeof(json.error) != 'undefined') {
					// JSON-RPC error
					if (typeof(errorCallback) == 'function')
						errorCallback(json.error);
					else
						_this.onError(json.error)
				}
				else if (typeof(json.result) != 'undefined' && typeof(json.error) == 'undefined') {
					// JSON-RPC success
					if (typeof(successCallback) == 'function')
						successCallback(json.result);
					else
						_this.onSuccess(json.result);
				}
				else
					_this.onTransportError('Server returned non-valid JSON-RPC message.');
			},
			error: function(requestObject, textStatus, errorThrown) {
				_this.onTransportError(textStatus);
			},
			processData: false,
			contentType: 'application/json'
		});
	}
};