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

if (typeof Prototype != "undefined" )
	{
	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); 
		}
	

	_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;
				  }
			  }
		  });

	}
else if (typeof Sarissa != "undefined")
	{  
	var ajax = new Object;

	isRpcSupported = function()
		{
		return (Sarissa && Sarissa.IS_ENABLED_XMLHTTP);
		}

	asyncRpcCall = function(method)
		{
		if (!Sarissa.IS_ENABLED_XMLHTTP)
			return;

		var xmlhttp = new XMLHttpRequest();

		var callback;
		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]);
			}

		eval("ajax['" + method + "'] = new Object()");
		eval("ajax['" + method + "'].request = xmlhttp");
		eval("ajax['" + method + "'].callback = callback");

		if (callback)
			{
			code = "callback = function(){ var o = ajax['" + method + "'];";
			code += "if (o.request.readyState == 4) ";
			code += "o.callback(_evalIfJSON(o.request.responseText)) }";
			eval(code);
			xmlhttp.onreadystatechange = callback;
			}

		var envelope = new Object;
		envelope.method = method;
		envelope.args = args;
		
		xmlhttp.open("POST", ajaxServerURL, true);
		xmlhttp.send(JSON.stringify(envelope));
		}

	syncRpcCall = function(method)
		{
		if (!Sarissa.IS_ENABLED_XMLHTTP)
			return;
		
		var xmlhttp = new XMLHttpRequest();

		var callback;
		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]);
			}

		eval("ajax['" + method + "'] = new Object()");
		eval("ajax['" + method + "'].request = xmlhttp");
		eval("ajax['" + method + "'].callback = callback");

		if (callback)
			{
			code = "callback = function(){ var o = ajax['" + method + "'];";
			code += "if (o.request.readyState == 4) ";
			code += "o.callback(_evalIfJSON(o.request.responseText)) }";
			eval(code);
			xmlhttp.onreadystatechange = callback;
			}

		var envelope = new Object;
		envelope.method = method;
		envelope.args = args;

		xmlhttp.open("POST", ajaxServerURL, true);
		xmlhttp.send(JSON.stringify(envelope));
		}
	}

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");
	}

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;
}

