var _ajaxUniqueRequests = new Object;

function checkCoreLoaded()
{
	if( 'function' != typeof(debug) )
		alert("Missing core.js!");
}

/*
 *	Load data from server. Arguments:
 *		method		string				GET|POST|HEAD. Default is POST
 *		url			string				Base URL
 *		args		string|hash			Extra arguments either in "name=value&.." format or hash
 *		unique		string				Unique ID. Only one request with specified uid will be performed
 *										simultaneously. Other requests will be cancelled
 *		force		bool				Used only with "unique". Cancel previous unique request.
 *		onwait		func(req)			Waiting handler
 *		onerror		func(reason,req)	Error handler
 *		onready		func(req)			Success handler
 *
 *  @param		args	hash		Arguments
 *  @return		bool
 */
function  ajaxLoadUrl (args)
{
	var req = false;

	if ( 'undefined' != typeof( ajaxBaseUrl ) && args['url'].indexOf( '://' ) == '-1' )
		args['url'] = ajaxBaseUrl + args['url'];

	try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); }
	catch (e) { try { req = new XMLHttpRequest(); }
	catch (e) { req = false; }}}
	if( !req ) 				return debug("Cannot create XMLHttpRequest");
	if( !args['url'] )		return debug("Missing required argument: URL");

	try
	{
		args['method'] = args['method'] ? args['method'].toUpperCase() : 'POST';
		if (args['method'] != "POST")
		{
			req.open(args['method'], makeUrl(args['url'],args['args']), true);
			body = null;
		}
		else
		{
			req.open(args['method'], args['url'], true);
        	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			body = makeUrl('',args['args']);
		}
		var onWait		= args['onwait'];
		var onError		= args['onerror'];
		var onReady		= args['onready'];
		var unique		= ""+args['unique'];
		req.onreadystatechange = function()
		{
			var readyState, status, statusText;
			try
			{
				readyState	= req.readyState;
				status		= req.status;
				statusText	= req.statusText;
			}
			catch(err){};

			if (readyState != 4)
				return onWait ? onWait(req) : null;
			if( status != 200 )
				onError ? onError(statusText, req) : debug("There was a problem retrieving data:\n" + statusText);
			else
				onReady ? onReady(req) : null;
			if( unique )
				delete _ajaxUniqueRequests[unique];
		};
		if( 'unique' in args )
		{
			if( unique in _ajaxUniqueRequests )
				if( args['force'] )
					_ajaxUniqueRequests[unique].abort();
				else
					return false;
			_ajaxUniqueRequests[unique] = req;
		}
		req.send(body);
	}
	catch(e)
	{
		return debug(e);
	}
	return true;
}

/*
 *	Load XML document from server. Arguments see ajaxLoadUrl.
 *	Extra arguments:
 *		onready		func(xml,req)	Success handler
 *
 *  @param		args	hash		Arguments
 *  @return		void
 */
function  ajaxLoadXml (args)
{
	if( args['onready'] )
	{
		var process = args['onready'];
		var error	= args['onerror'] ? args['onerror'] : function(msg){debug("Error loading xml:" + msg)};
		args['onready'] = function(req)
		{
			if(req.responseXML === null)
				error("No XML data",req);
			else
				process(req.responseXML, req);
		}
	}
	ajaxLoadUrl(args);
}

/*
 *	Load Text document from server. Arguments see ajaxLoadUrl.
 *	Extra arguments:
 *		onready		func(text,req)	Success handler
 *
 *  @param		args	hash		Arguments
 *  @return		void
 */
function  ajaxLoadText (args)
{
	if( args['onready'] )
	{
		var process = args['onready'];
		var error	= args['onerror'] ? args['onerror'] : function(msg){debug("Error loading text:" + msg)};
		args['onready'] = function(req)
		{
			if(req.getResponseHeader("content-type").match(/text\/plain/) && req.responseText !== null) {
				process(req.responseText, req);
			} else {
				error("Server returned not a text document!",req);
			}
		}
	}
	ajaxLoadUrl(args);
}

if( "undefined" == typeof ajaxGenShowStatus )
{
	/*
	 *	Generate function to handle loading process ("onwait" handler)
	 *
	 *  @param		el		object		HTML element which will contain loading status
	 *  @return		function(req)
	 */
	ajaxGenShowStatus = function(el)
	{
		return function(req)
		{
			/*if(req.readyState == 1)
				el.innerHTML = "Sending request";
			else if(req.readyState == 2)
				el.innerHTML = "Request is sent";
			else if(req.readyState == 3)
				el.innerHTML = "Loading";
			else
				debug("Oops! readyState == 4!");*/
			el.innerHTML = '<img src="/img/indicator.gif" width="14" height="14" />';
		};
	}
}

/*
 *	Converts string "id\tvalue\n..." to <option> set.
 *
 *  @param		str		string		Source string
 *  @return		string
 */
function  ajaxLinesToOptions (str)
{
	return str.strip().split(/(\r?\n)/).map(function(v){
		var a = v.split(/\t/,2); return a.length == 1 ? '' : "<option value=\""+unescape(a[0])+"\">"+unescape(a[1])+"</option>";}).
		join("\n");
}

setOnLoadHandler('check_core_is_loaded', checkCoreLoaded);
