// detect the browser
// http://www.javascriptkit.com/javatutors/objdetect3.shtml
var isOpera    = (window.opera);
var isIE6plus  = (!isOpera  && document.compatMode && document.all);
var isIE7      = (!isOpera  && document.documentElement && ('undefined' != (typeof document.documentElement.style.maxHeight)));
var isIE6      = (isIE6plus && !isIE7);
var isFF1plus  = (!isOpera  && window.getComputedStyle);
var isFF15plus = (!isOpera  && Array.every);
var isFF2plus  = (!isOpera  && window.Iterator);
var isFF       = (isFF1plus || isFF15plus || isFF2plus);

function redirect(href)
{
	if (isIE6) window.open(href, '_self'); else window.location.replace(href);
}

// converts an ajax request to a json result
function request_to_result(request)
{
	var result =
	(	// if valid and non-empty
		(	request && request.responseText &&
			(response = request.responseText) &&
			('' != response)
		) ?
		// return the evaluated json object
		eval('(' + response + ')') :
		// otherwise, return an unknown error object
		{ "failed": true, "message": "Unknown error." }
	);
	return result;
}

// loads the requested file, with the given parameters, into the given destination,
// displaying errors in the second destination given
function ajax_load(filename, parameters, destination, json)
{
	var std_destination = (destination ? (destination.standard ? destination.standard : destination) : false);
	var err_destination = (destination ? (destination.error ? destination.error : destination) : false);
	var expect_json = ((json && json.expect) ? true : false);
	var json_on_error = ((json && json.on_error) ? json.on_error : false);
	var json_on_success = ((json && json.on_success) ? json.on_success : false);

	var done = false;
	var failed = false;

	new Ajax.Request(filename,
	{
		method: 'get',
		parameters: parameters,
		onFailure: function(request)
		{
			if (done) return; failed = true;
			if (err_destination) err_destination.innerHTML = 'An error occurred: ' + request.statusText;
		},
		onComplete: function(request)
		{
			if (failed) return; done = true;

			if (expect_json)
			{
				result = request_to_result(request);

				if (result.failed)
				{
					failed = true;
					alert("Input error!\n" + result.message);
					if (json_on_error) json_on_error(result);
					return;
				}

				if (json_on_success) json_on_success(result);
			}
			else
			{
				if (std_destination) std_destination.innerHTML = request.responseText;
			}
		}
	});
}
