var http_request	= false;

function maf_encodeURI(uri)
{
	var plus = "%" + "+".charCodeAt(0).toString(16).toUpperCase();
	uri = encodeURI(uri);
	uri = uri.replace('+',plus);
	return uri;
}

function create_request()
{
	http_request = false;
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType)
		{
			http_request.overrideMimeType('text/xml');
		}
	}
	else if	(window.ActiveXObject)
	{
		try
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e2)
			{
			}
		}
	}
		
	if (!http_request)
	{
		alert("Can't do AJAX.");
		return false;
	}
	
	return true;
}

function xmlRead(xmldoc, tag)
{
	var a = xmldoc.getElementsByTagName(tag);
	var b;
	if (a.item(0) && a.item(0).childNodes.length > 0)
	{
		b = a.item(0).firstChild.data;
	}
	else
	{
		b="";
	}
	return b;
}

function maf_query(mode, parameters, fun)
{
	create_request();
	http_request.onreadystatechange = function() { fun(); };
	parameters = "ajax=" + mode + "&" + parameters;
	http_request.open("POST", url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);	
	
}

function prepare_ajax(aid, aaction)
{
	if (!create_request()) return;
	kod = "<input type=\"submit\" onclick=\""+aaction+"()\" value=\""+l_submit+"\" />";
	document.getElementById(aid).innerHTML = kod ;//+ "  " + maf_encodeURI(kod);
}
function sendajaxcomm()
{
	cid = document.getElementById("comm_id").value;
	ctext = maf_encodeURI(document.getElementById("comment").value);
	maf_query("submitcomment", "id="+cid+"&text="+ctext, getajaxcomm);
	document.getElementById("commentsadder").innerHTML=i_ajax_loader;
}

function getajaxcomm()
{
	try
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				var xmldoc = http_request.responseXML;
				var reply = xmlRead(xmldoc, "reply");

				if (reply == "OK")
				{
					var pagedata = xmlRead(xmldoc, "data");
					document.getElementById("commentsground").innerHTML += pagedata;
					document.getElementById("commentsadder").innerHTML="<b>Komentarz został wysłany.</b>";
					document.getElementById("commentsadder").style.background="#ddffdd";
					//document.getElementById("comments_count").innerHTML= parseInt(document.getElementById("comments_count").innerHTML) + 1;
				}
				else if (reply == "TOLONG")
				{	
					document.getElementById("commentsadder").innerHTML="<b>Zbyt duża liczba znaków.</b>";
					document.getElementById("commentsadder").style.background="#ff0000";
				}
				else if (reply == "TOSHORT")
				{	
					document.getElementById("commentsadder").innerHTML="<b>Zbyt mała liczba znaków.</b>";
					document.getElementById("commentsadder").style.background="#ff0000";
				}
			}
		}
	}
	catch (e)
	{
	}
}
