



//Формат ответа: json
//По умолчанию в ответе разбираются следующие параметры:
//error, success, response
//Соответственно ожидается ответ в виде `var error = "текст ошибки"; var success = "текст успеха"; var response = "текст респонса";`
//При этом важно чтобы в переменных не было переносов строк, для этого нужно заменять \n|\r на \\n|\\r


function mss_ajax_init()
{
	mss_ajax_load_photo_initialize();
}



function mss_ajax(options)
{
	var defaults = 
	{
		method: "POST",
		url: "",
		type: "json",		// тип ответа, json или html
		datasource: null,	// id элемента, если указан, берутся все input-select-textarea в нем и их значения добавляются в params
		params: null,		// дополнительные параметры
		callback: "",
		timeout: 10000,		// максимальное ожидание ответа
		target: "",		// id элемента, если указан, он очищается и в нем отображается "загрузка", а потом то что пришло с ответом, после этого делается callback
		escapedata: 1,		// делать escape() всем посылаемым параметрам
		printstatus_mode: 1,	// 0 - скрывать, 1 - обычный, 2 - короткий;
		statuscontainer: "",	// если указан и hideprintstatus=0, в нем отображается "loading...";
		debug: 0		// alert-ить посылаемый запрос перед отправкой
	}
	
	for (var i in options)
		defaults[i] = options[i];
	options = defaults;


	var 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;
	}


	var print_status = function(newstatus,status_text) 
	{ 
		if (options.hideprintstatus > 0) return null;

		var obj = null;

		if (options.statuscontainer.length > 0)
		{
			obj = document.getElementById(options.statuscontainer);
		}
		else if (options.target.length > 0)
		{
			obj = document.getElementById(options.target);
		}

		if ((typeof obj == "object") && (obj != null))
		{
			if (options.printstatus_mode == 1)
				obj.innerHTML = "<div class='mss_ajax_status_container'><div class='mss_ajax_status'><div class='" + newstatus + "'>" + newstatus.toUpperCase() + ": " + status_text + "</div></div></div>";
			else if (options.printstatus_mode == 2)
				obj.innerHTML = "<span class='mss_ajax_status_short'><span class='"+newstatus+"'></span></span>";
		}
		return null;
	}


	var req_fn = function(obj)
	{       
		var query = "";                

		if (typeof obj != "object") return query;

		if (obj.name.length>0 && obj.value.lenght>0)
		{
			if ((this.type == "checkbox" || this.type == "radio") && this.checked == false) { }
			else query += (query?"&":"") + this.name + "=" + (options.escapedata>0?escape(this.value):this.value);
		}

		for (var i = 0; i < obj.children.length; i++)
		{
			var tmp_query = req_fn(obj.children.item(i));
			if (tmp_query.length > 0)
				query += (query?"&":"") + tmp_query;
		}

		return query;
	}




	var query = "";

	if (options.datasource != null)
	{
		var obj = document.getElementById(options.datasource.length);
		if (typeof obj == "object")
		{
			query += (query?"&":"") + req_fn(obj);
		}
	}

	if (options.params != null)
	{                         
		if (typeof options.params == "string")
		{
			query += (query?"&":"") + (options.escapedata?escape(options.params):options.params);
		}
		else if (typeof options.params == "object")
		{
			for (var i in options.params)
			{
				if (i.length > 0)
				{
					query += (query?"&":"") + escape(i) + "=" + escape(options.params[i]);
				}
			}
		}
	}




	var req = createRequestObject();
	if (!req) return print_status("error","Can't define XMLHttpRequest");


	var req_abort = function()
	{
		req.abort();
		print_status("error","time out limit");
	}
	if (options.timeout > 0) var timeout = setTimeout(req_abort,options.timeout);


	req.onreadystatechange = function()
	{
		var tmp = null;
		var error = null;
		var success = null;
		var response = null;

		if (req.readyState == 0) tmp = "Not initialized";
		if (req.readyState == 1) tmp = "Start loading";
		if (req.readyState == 2) tmp = "Loaded";
		if (req.readyState == 3) tmp = "Processed";
		if (req.readyState == 4) tmp = "Completed";

		print_status("loading",tmp);

		if (req.readyState == 4)
		{
			if (req.status == 200) 
			{
				if (options.type == "json")
					eval(req.responseText);
			}
			else error = "can't receive data";

			if (error != null) print_status("error",error);
			else if (success != null) print_status("success",success);
			else if (response != null || options.type == "html") 
			{
				if (options.target.length > 0)
				{
					var obj = document.getElementById(options.target);
					if (typeof obj == "object")
					{
						obj.innerHTML = (options.type=="html"?req.responseText:response);
					}
				}
			}
			else print_status("error","empty data");

			clearTimeout(timeout);

			if ((success || response) && options.callback) options.callback(req.responseText);
		}
	}


	print_status("loading","please wait");
	if (options.debug) alert(query);


	if (options.method == "GET")
	{
		req.open(options.method,options.url + "?" + query,true);
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		req.send(null);
	}
	if (options.method == "POST")
	{
		req.open(options.method,options.url,true);
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		req.send(query);
	}
}

		