function ajax()
{
	var httpRequest = false;
	var method = "GET";
	var url = null;
	var reposponseText = null;
    var postvars = null;

	var eventList = [];

	this.Initialize = function()
	{
		if (window.XMLHttpRequest) 
		{ 
			httpRequest = new XMLHttpRequest();

			if (httpRequest.overrideMimeType) 
			{
				httpRequest.overrideMimeType('text/html');
			}
		} 
		else if (window.ActiveXObject) 
		{ // IE
			try 
			{
				httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e) 
			{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}

		if (!httpRequest) 
		{
			return false;
		}
		httpRequest.onreadystatechange = this.StatusChange;
		httpRequest.open(method, url, true);
        if (method == "POST")
        {
            httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            httpRequest.setRequestHeader("Content-length", postvars.length);
            httpRequest.setRequestHeader("Connection", "close");
            httpRequest.send(postvars);
        }
        else   
        {
		    httpRequest.send(null);
        }
	};

	this.StatusChange = function()
	{
		this.statusText = httpRequest.StatusText;

		if (httpRequest.readyState == 1)
		{
			if (typeof eventList["OnLoading"] == "function")
			{
				eventList["OnLoading"].apply(this, new Array(this));
			}
		}
		else if (httpRequest.readyState == 2)
		{
			if (typeof eventList["OnLoaded"] == "function")
			{
				eventList["OnLoaded"].apply(this, new Array(this));
			}
		}
		else if (httpRequest.readyState == 4)
		{
			this.responseText = httpRequest.responseText;
			this.responseStatus = httpRequest.status;

			if (typeof eventList["OnSuccess"] == "function")
			{
				eventList["OnSuccess"].apply(this, new Array(this));
			}
		}
	}

	this.HandleArgs = function(args)
	{
		for (arg in args)
		{				
			if (arg == "url")
			{
				url = args[arg] + '&ajax=1';
			}
            else
            if (arg == "postvars")
            {
                method = "POST";
                postvars = args[arg];
            }
			else 
			if (typeof args[arg] == "function")
			{
				eventList[arg] = args[arg];	
			}
		}
	};
}

ajaxGET = function(arg)
{
	return ajaxRequest('GET', arg);
};

ajaxPOST = function(arg)
{
	return ajaxRequest('POST', arg);
};

ajaxRequest = function(requestType, arg)
{
	var request = new ajax();

	request.Method = requestType;
	request.HandleArgs(arg);
	return request.Initialize();
};

function encodeNode(node)
{
	if (!node.value) return false;
		var r=encodeURIComponent(node.getAttribute('name'))+'='+encodeURIComponent(node.value);
	node.value='';
	return r;
}

function GetFormQueryString(node)
{
	var form_fields = ['input', 'textarea', 'button', 'select'];
	var inputs = [];

	var table=document.getElementById(node).childNodes[0];
	for (var i in form_fields)
	{
		var ff = table.getElementsByTagName(form_fields[i]);
		inputs.push(ff);
	}
	var q='';
	for (i in inputs)
	{
		for(var l in inputs[i])
		{
			if (inputs[i][l].nodeName == 'INPUT')
			{
				//input
				if (!inputs[i][l].getAttribute('type') || inputs[i][l].getAttribute('type') == 'text')
				{
					//text
					var a=encodeNode(inputs[i][l]);
					if (a)
						q+=a+'&';
				}
				else
				if (inputs[i][l].getAttribute('type') == 'hidden')
				{
					//hidden
					var a=encodeNode(inputs[i][l]);
					if (a)
						q+=a+'&';
				}
				else
				if (inputs[i][l].getAttribute('type') == 'password')
				{
					//password
					var a=encodeNode(inputs[i][l]);
					if (a)
						q+=a+'&';
				}
				else
				if (inputs[i][l].getAttribute('type') == 'radio')
				{
					//radio
					if (inputs[i][l].checked)
					{
						var a=encodeNode(inputs[i][l]);
						if (a)
							q+=a+'&';
					}
				}
				else
				if (inputs[i][l].getAttribute('type') == 'checkbox')
				{
					if (inputs[i][l].checked)
					{
						var a=encodeNode(inputs[i][l]);
						if (a)
							q+=a+'&';
					}
				}
			}
			else
			if (inputs[i][l].nodeName == 'TEXTAREA')
			{
				var a=encodeNode(inputs[i][l]);
				if (a)
					q+=a+'&';
			}
			else
			if (inputs[i][l].nodeName == 'SELECT')
			{
				for (var x=0; x<inputs[i][l].childNodes.length; x++)
				{
					if(inputs[i][l].childNodes[x].selected)
					{
						var a=encodeURIComponent(inputs[i][l].getAttribute('name'))+'='+encodeURIComponent(inputs[i][l].childNodes[x].value);
						if (a)
							q+=a+'&';
					}
				}
			}
		}
	}
	return q.substr(0, q.length-1);
}


function SaveUserSettings(act, id)
{
	var q = GetFormQueryString('profile_edit');
	ajaxPOST(
	{
		url: "ajax.php?userid=<?=$userid?>&act="+act+"&save=1" + (id?"&id=" + id:''),
		postvars: q,
		OnSuccess: function(obj)
		{
			document.getElementById('profile_content').innerHTML = obj.responseText;
		}
	});
	
	return false;
}

function ShowMessage(id)
{
	var s = document.getElementById('msg'+id);
	if (!s) return true;
	if (s.style.display=='none')
	{
		s.style.display = '';
	}
	else
	{
		s.style.display = 'none';
	}
	return false;
}

function SwitchPanels(id)
{
	var elements = ['profile_inbox','profile_sentbox','profile_write', 'torrents_upped', 'torrents_seed', 'torrents_leech'];

	for (var i=0; i<elements.length; i++)
	{
		s=document.getElementById(elements[i]);
		if (!s) continue;
		s.style.display='none';
		var s = document.getElementById(elements[i]+'_s');
		s.style.fontWeight='';
	}
	var s = document.getElementById(id);
	s.style.display=''
	var s = document.getElementById(id+'_s');
	s.style.fontWeight='bold';
	return false;
}

function DelMessage(id,typ)
{
	ajaxGET({
		url: 'delmsg.php?id='+id+'&type='+typ,
		OnSuccess: function(obj)
		{
			if (obj.responseText == 'Success')
			{
				document.getElementById('msg'+id).style.display='none';
				document.getElementById('msgh'+id).style.display='none';
				return false;
			}
			return true;
		}
	});
	return false;
}

function SendMessage()
{
	var q = GetFormQueryString('sendmsg_form');
	ajaxPOST({
		url: 'sendmsg.php?',
		postvars: q,
		OnLoading: function(obj)
		{
			document.getElementById('sendmessage_button').disabled=true;
		},
		OnSuccess: function(obj)
		{
			if (obj.responseText == '')
			setTimeout(function(){
				var x = document.getElementById('sendmessage_button');
				x.disabled=false;
				x=x.parentNode.parentNode.parentNode;
				x.deleteRow(x.rows.length-1);
			},2500);
			else
				alert(obj.responseText);

		}
	});
	ajaxGET(
	{
		url: 'sendmsg.php?sent',
		OnSuccess: function(obj)
		{
			document.getElementById('profile_write').innerHTML = obj.responseText;
		}
	});
	return false;
}
function ReplyToMessage(id)
{
	SwitchPanels('profile_write');
	
	ajaxGET(
	{
		url: 'sendmsg.php?replyto='+id,
		OnSuccess: function(obj)
		{
			var x = document.getElementById('sendmessage_button').parentNode.parentNode.parentNode;
			x.deleteRow(0);
			x = x.insertRow(0);
			var r = obj.responseText;
			var username = r.substr(r.indexOf("username: ")+10, r.indexOf("\n\n")-10);
			r = r.substr(r.indexOf("\n\n")+1);
			x.innerHTML = '<td class="colhead" colspan="2">Wyslij wiadomosc do ' + username + '<input type="text" name="receiver" value="' + r.substr(r.indexOf("receiver: ")+10, r.indexOf("\n\n")-10) + '" /></td>';
			r = r.substr(r.indexOf("\n\n")+1);
			x.parentNode.rows[1].cells[1].firstChild.value = 'Re: '+ r.substr(r.indexOf("subject: ")+9, r.indexOf("\n\n")-9);
			r = r.substr(r.indexOf("msg: ")+5);
			x = x.parentNode.rows[2].cells[1].firstChild;
			x.value = '[quote=' + username + "]\n" + r + "[/quote]\n\n";
			x.setSelectionRange(x.value.length, x.value.length);
			x.focus();
		}
	});
	return false;
}

function check_avatar_size(elm, size)
{
	if (elm.clientWidth > size)
		elm.style.width = size+'px';
}

function RemoveFriend(id)
{
	ajaxGET(
	{
		url: 'friends.php?action=rmf&id='+id,
		OnSuccess: function(obj)
		{
			if (obj.responseText != '')
			{
				alert(obj.responseText);
				return;
			}
			var elm = document.getElementById('friend' + id);
			var elm2 = elm.parentNode;
			elm.parentNode.removeChild(elm);
			if (elm2.childNodes[1].nodeName != 'DIV')
			{
				elm = document.getElementById('friends');
				elm.parentNode.removeChild(elm);
			}
		}
	});
	return false;
}

function RemoveBlock(id)
{
	ajaxGET(
	{
		url: 'friends.php?action=rmb&id='+id,
		OnSuccess: function(obj)
		{
			if (obj.responseText != '')
			{
				alert(obj.responseText);
				return;
			}
			var elm = document.getElementById('block' + id);
			var elm2 = elm.parentNode;
			elm.parentNode.removeChild(elm);
			if (elm2.childNodes[1].nodeName != 'DIV')
			{
				elm = document.getElementById('blocks');
				elm.parentNode.removeChild(elm);
			}
			
		}
	});
	return false;
}
