/* this object is used to communicate with server without reloading page */
/* $Revision: 1.41 $ */

var rpc={

	q: [],

/* 
	public int send(data, [callback], [url], [html], [getmethod])

		send request to server

	parameters:
		data - url string like "param1=data1&param2=data2" or object like {param1:data1,param2:data2}
		callback - function that will be called when response arrive (optional parameter)
		url  - url to which make request. by default - root of site (optional parameter)
		html - boolean flag that specifies return page html or not (optional parameter)
		getmethod - by default request method is post but you can set this flag to use GET method (optional parameter)
*/
	send: function(d,c,u,h,m){
		var t, n = rpc.q.length, o = rpc.x.o(), a=d?d:'';

		rpc.q[n] = {request:d,conn:o,callback:c,response:{}};

		u=u?u:window.location.href.replace(/(.*):\/\/([^\/]+)(.*)/ig,'$1://$2/')+'';


		if(typeof(a)=='object')
		{
			a='';
			for(t in d)
			{
				a+=(a?'&':'')+t+'='+encodeURIComponent(d[t]);
			}
		}
		a += '&__device=rpc';
		a += h?'&__html=1':'';


		if(m){
			o.open('GET',u+'?'+a, true);
			o.send(null);
		}else{
			o.open('POST',u,true);
			try{o.setRequestHeader('Content-Type','application/x-www-form-urlencoded')}catch(e){};
			o.send(a);
		}

		rpc.p(n);

		return n;
	},


	// try to terminate request (by id)
	abort: function(id){
		try{rpc.q[id].conn.abort();rpc.q[id].conn=null}catch(e){}
		rpc.q[id]=null
	},


	// create new XmlHttpRequest object
	x: {
		o: function()
		{
			var r=null
			try{
				r=new XMLHttpRequest()
			}catch(e){
				var i,s='.XMLHTTP',t='MSXML2'+s,m=[t+'.6.0',t+'.5.0',t+'.4.0',t+'.3.0',t,'Microsoft'+s];
				for(i in m)
				{
					try{
						r=new ActiveXObject(m[i]);if(r){break}
					}catch(e){}
				}
			}
			return r
		}
	},


	// polling thread
	p: function(id){

		if(rpc.q[id]!=null)
		{
			if(rpc.q[id].conn.readyState==4)
			{
				rpc.q[id].response.text = rpc.q[id].conn.responseText;
				rpc.q[id].response.xml = rpc.q[id].conn.responseXML;

				// try evaluate response data into js and store it in response object
				var o={};
				try {
					eval('o='+rpc.q[id].response.text);
				}catch(e){}
				rpc.q[id].response.js = o;


				if(rpc.q[id].callback)
				{
					rpc.q[id].callback(rpc.q[id].response);
				}

				rpc.q[id].conn=null;
				rpc.q[id]=null;
			}else{
				setTimeout('rpc.p('+id+')', 50);
			}
		}
	}
};