var ajaxServerURL = "/tools/ajaxrpc.php";

asyncRpcCall = function(method)
  {
  var callback;
  var args = new Array();
  for (var i = 1; i < arguments.length; i++)
	{
	  var a = arguments[i];
	  if (typeof a == 'function')
		callback = a;
	  else
		args.push(arguments[i]);
	}
  return _rpcCall(true, method, args, callback,false); 
  }
	
syncRpcCall = function(method)
  {
  var callback;
  var args = new Array();
  for (var i = 1; i < arguments.length; i++)
	{
	  var a = arguments[i];
	  if (typeof a == 'function')
		callback = a;
	  else
		args.push(arguments[i]);
	}

  return _rpcCall(false, method, args, callback,false); 
  }

queuedRpcCall = function(method)
  {
  var callback;
  var args = new Array();
  for (var i = 1; i < arguments.length; i++)
	{
	  var a = arguments[i];
	  if (typeof a == 'function')
		callback = a;
	  else
		args.push(arguments[i]);
	}

  return _rpcCall(true, method, args, callback,true); 
  }
	
function reloadingRpcCall(method)
	{
	url = ajaxServerURL + "?";

	var i;
	var args = new Array();

	for (i = 1; i < arguments.length; i++)
		{
		a = arguments[i];
		if (typeof a == 'function')
			callback = a;
		else
			args.push(arguments[i]);
		}

	var envelope = new Object;
	envelope.method = method;
	envelope.args = args;
	envelope.returnto = document.location.href;
	url += escape(JSON.stringify(envelope));
	window.open(url, "_self");
	}


if (typeof jQuery != "undefined")
  {
	_rpcCall = function(async, method, args, callback, queue)
		{
		var i;

		// Note: always queueing, "onlyLatestOfClass" not supported

		var envelope = new Object;
		envelope.method = method;
		envelope.args = args;
		envelope = JSON.stringify(envelope);

		var successWrapper = null;

		if (callback)
		    {
			successWrapper = function(data, textStatus, xmlHttpRequest)
				{
				data = _evalIfJSON(data);
				callback(data);
				}
			}

		function showFailureMessage(xmlHttpRequest, textStatus, errorThrown)
		    {			 		
			  alert('Ett anrop misslyckades. Kanske din koppling till Internet är bruten?');
			}

		$.ajax({
			url: ajaxServerURL,
			data: envelope,
			success: successWrapper,
			dataType: "text",
			type: "POST",
			error: showFailureMessage
			});
		}

	function _evalIfJSON(text)
		{
		  // trim whitespace
		  //
		  text = text.replace(/^\s*|\s*$/g, "");
		  
		  // eval if it looks like JSON
		  //
		  if (text.substr(0,1) == "{" || text.substr(0,1) == "[" || text == "null" || text == "true" || text == "false" )
			eval("text = "+ text );

		  return text;
		};
  }

if (typeof Prototype != "undefined" )
	{
	_rpcCall = function(async, method, args, callback, queue)
		{
		var i;

		var envelope = new Object;
		envelope.method = method;
		envelope.args = args;
		envelope = JSON.stringify(envelope);

		var successWrapper = null;
		if (callback)
		    {
			successWrapper = function(callback, request, jsonHeader)
				{
				var text = request.responseText;
				text = _evalIfJSON(text);
				callback(text, jsonHeader);
				}.bind(this,callback);
			}

		var olocMethod = (queue ? null : method);	
		var timeout = (queue ? null : 15000);

		var request = new Ajax.Request(
			ajaxServerURL,
			{
			    onlyLatestOfClass: olocMethod,
				asynchronous: async,
		  		method: "post",
				timeout: timeout,
		  		postBody: envelope,
		  		onSuccess: successWrapper,
				onFailure: function() { alert("Ett anrop till webbservern misslyckades"); }
			}
		);

		}


	function callInProgress (xmlhttp)
	  {
		switch (xmlhttp.readyState) {
		case 1: case 2: case 3:
		  return true;
		  break;
		  // Case 4 and 0
		default:
		  return false;
		  break;
		}
	  }

	function showFailureMessage()
	  {
		alert('Ett anrop misslyckades. Kanske din koppling till Internet är bruten?');
	  }

	// Register global responders that will occur on all AJAX requests
	Ajax.currentRequests = {};

	Ajax.Responders.register(
		{
		onCreate: function(request)
		  {
		  if (request.options.timeout)
		      {
				  request['timeoutId'] = window.setTimeout(function()
					{
						// If we have hit the timeout and the AJAX request is active,
						// abort it and let the user know
						if (callInProgress(request.transport))
						{
							request.transport.abort();
							showFailureMessage();

							// Run the onFailure method if we set one up when creating the AJAX object
							//
							if (request.options['onFailure'])
							{
								request.options['onFailure'](request.transport, request.json);
							}
						}
					}, request.options.timeout * 60); /* timeout in milliseconds */
			  }

			if (request.options.onlyLatestOfClass && Ajax.currentRequests[request.options.onlyLatestOfClass])
				{
				  // if a request of this class is already in progress,
				  // attempt to abort it before launching this new request
				  try { Ajax.currentRequests[request.options.onlyLatestOfClass].transport.abort(); } catch(e) {}

				  // keep note of this request object so we can cancel it if superceded
				  Ajax.currentRequests[request.options.onlyLatestOfClass] = request;
				}
		  },
		onComplete: function(request)
			  {
				// Clear the timeout, the request completed ok
				window.clearTimeout(request['timeoutId']);

				if (request.options.onlyLatestOfClass)
				  {
					// remove the request from our cache once completed so it can be garbage collected
					Ajax.currentRequests[request.options.onlyLatestOfClass] = null;
				  }
			  }
		  });

	function _evalIfJSON(text)
	{
		// trim whitespace
		//
		text = text.replace(/^\s*|\s*$/g, "");
		
		// eval if it looks like JSON
		//
		if (text.substr(0,1) == "{" || text.substr(0,1) == "[" || text == "null" || text == "true" || text == "false" )
			eval("text = "+ text );

		return text;
	}
}


