/**
*	Juman Ajax Library
*	(c) Pavel Gudanets 2009
*/

/*
dependencies:
	browser()	(send_form)
	jd()		(_error_report)
*/

var JumanAjax = {

	// Tools
	
	debug: false,		// display error reports?

	get: function(elid)
	{
		return document.getElementById(elid);
	},

	set_document_title: function(title, add)
	{
		if (add)
		{
			if (document.title)
				document.title += ' -';
			document.title += ' ' + title;
		}
		else
		{
			document.title = title;
		}
	},

	/*
	*	@author: prototype.js
	*/
	is_json: function(str)
	{
		if (/^\s*$/.test(str)) return false;
		str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
		return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
	},

	js_loaded: {},
	get_js_loaded: function()
	{
		return JumanAjax.js_loaded;
	},

	// Private methods

	_createRequestObject: function()
	{
		if (window.XMLHttpRequest)
		{
			try { return new XMLHttpRequest(); } catch (e) {}
		}
		else if (window.ActiveXObject)
		{
			try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {}
			try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {}
		}
		return null;
	},

	_error_report: function(data)
	{
		if (JumanAjax.debug)
		for (i in data)
		{
			jd('<b>'+i+'</b>:');
			jd(data[i]);
			jd('<hr>');
		}
	},

	// Public methods

	// @param url of the server script
	// @param func_cb - callback js function
	// @param params - parameters to send; URL-encoding them
	// @param req_type - 'GET', 'POST' etc.
	request: function(url, func_cb, params, req_type)
	{
		try
		{
			var req = JumanAjax._createRequestObject();
			if (!req)
				return;

			var param_str = '';
			for (var i in params)
			{
				if (param_str)
					param_str += '&';
				param_str += i + '=' + encodeURIComponent( params[i] );
			}

			if (req_type == 'POST')
			{
				req.open('POST', url, true);
				req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			}
			else // GET
			{
				param_str = (url.indexOf('?') == -1 ? '?' : '&') + param_str;
				req.open('GET', url + param_str, true);
				param_str = null;
			}

			req.onreadystatechange = function() // must be after 'req.open' call in IE
			{
				try
				{
					if (req.readyState == 4) // Complete
					{
						if (req.status == 200 && typeof(func_cb) == 'function')
						{
							func_cb(req.responseText, req.responseXML);
						}
					}
				}
				catch (e) { JumanAjax._error_report({title:"AjaxError: onreadystatechange()", error:e}); }
			};

			req.send(param_str);
		}
		catch (e) { JumanAjax._error_report({title:"AjaxError: request()", error:e}); }
	},

	// @param url of the server script
	// @param elid is id of the DOM node
	// @param op - (in|pre|post) data from the server script
	// @param func_cb - callback js function(html_str); must return true, otherwise further data procession will be stopped
	// @param params = {param_name:param_value, ...}
	// @param req_type - 'GET', 'POST'
	load_html: function(url, elid, op, func_cb, params, req_type)
	{
		var JumanAjaxLoadHTMLFunc = function(str)
		{
			try
			{
				if (typeof(func_cb) == 'function')
					if (!func_cb(str))
						return;

				switch (op)
				{
					case 'pre':
						JumanAjax.get(elid).innerHTML = str + JumanAjax.get(elid).innerHTML;
					break;
					case 'post':
						JumanAjax.get(elid).innerHTML += str;
					break;
					//case 'in':
					default:
						JumanAjax.get(elid).innerHTML = str;
					break;
				}
			}
			catch (e) { JumanAjax._error_report({title:"AjaxError: JumanAjaxLoadHTMLFunc()", response:str, error:e}); }
		};

		JumanAjax.request(url, JumanAjaxLoadHTMLFunc, params, req_type);
	},

	/*
	*	@param func_cb - callback js function(is_ok)
	*	@param once - load only once (default: true);
	*/
	load_js: function(url, func_cb, once, charset)
	{
		var JumanAjaxLoadJSFunc = function(code)
		{
			try {
				var head = document.getElementsByTagName("head")[0];
				var script = document.createElement("script");
				script.src = url;
				script.type = 'text/javascript';
				if (charset)
					script.charset = charset;

				var wait = true;
				script.onload = script.onreadystatechange = function()
				{
					if ( wait && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") )
					{
						if (typeof once == 'undefined' || once)	// check if this js-file was loaded before
						{
							if (JumanAjax.js_loaded[url])
								return;
							else
								JumanAjax.js_loaded[url] = true;
						}

						wait = false;

						script.onload = script.onreadystatechange = null;	// handle memory leak in IE
						head.removeChild( script );
						
						if (typeof(func_cb) == 'function') func_cb(true);
					}
				};

				head.appendChild(script);

			} catch (e) { JumanAjax._error_report({title:"AjaxError: JumanAjaxLoadJSFunc()", response:code, error:e}); }
		}

		JumanAjax.request(url, JumanAjaxLoadJSFunc);
	},

	/*
	*	@param func_cb - callback js function(data) (mandatory argument)
	*	@param once - load only once (default: true);
	*/
	load_json: function(url, func_cb, params, req_type)
	{
		var JumanAjaxLoadJSONFunc = function(json)
		{
			try {
				if (JumanAjax.is_json(json))
				{
					eval('var data = ' + json + ';');
					func_cb(data);
					return;
				}
				JumanAjax._error_report({title:"AjaxError: JumanAjaxLoadJSONFunc()", response:json});
			} catch (e) { JumanAjax._error_report({title:"AjaxError: JumanAjaxLoadJSONFunc()", response:json, error:e});}
			func_cb(null);
		}

		JumanAjax.request(url, JumanAjaxLoadJSONFunc, params, req_type);
	},

	load_xml: function(url, func_cb, params, req_type)
	{
		var JumanAjaxLoadXMLFunc = function(text, xml)
		{
			func_cb(xml);
		}

		JumanAjax.request(url, JumanAjaxLoadXMLFunc, params, req_type);
	},


	/*
	*	@author Gustavs Gutmanis
	*
	*	@param url
	*	@param func_cb - callback js function
	*	@param form - DOM object (document.formname)
	*
	*	@example: <form onSubmit="javascript:return JumanAjax.send_form(url,func,this)" >
	*
	*	todo: radio field in ie6, file field
	*/
	send_form: function(url, func_cb, form)
	{
		try
		{
			var post_params = new Array();

			if (browser() == 'ie')
			{
				var els = form.all;
				for (var i in els)
				{
					if (els[i].type == 'text' || els[i].type == 'password' || els[i].type == 'textarea' || els[i].type == 'select-one' || els[i].type == 'checkbox' || els[i].type == 'hidden' || els[i].type == 'submit') //  || els[i].type == 'radio'
					{
						post_params[i] = els[i].value;
					}
				}
			}
			else
			{
				var els = form.elements;
				for (var i in els)
				{
					if (els[i].type == 'text' || els[i].type == 'password' || els[i].type == 'textarea' || els[i].type == 'select-one' || els[i].type == 'checkbox' || els[i].type == 'radio' || els[i].type == 'hidden' || els[i].type == 'submit')
					{
						post_params[els[i].name] = els[i].value;
					}
				}
			}
			JumanAjax.request(url, func_cb, post_params, 'POST');
		}
		catch (e) { JumanAjax._error_report({title:"AjaxError: send_form()", error:e}); }
		return false;
	}

};


