var WebDemon = new (function ()
{

	var TIMEOUT = 150; // timeout in seconds, after which script will auto-reconnect
	var T = this;
	var onrecieve = null; // function is called on WebDemon.rcv(...);
	
	var $ = function(id){ return document.getElementById(id); };
	
	var next_timeout = null;
	var backend_src = null;
	
	T.reconnect = function()
	{
		$('webdemon_iframe').src = backend_src + '&' + Math.random();
		next_timeout = setTimeout(T.reconnect, TIMEOUT * 1000);
	}
	
	T.register = function(backend, onrcv_func)
	{
		if(!document.body)
		{
			throw "WebDemon.register() cannot be called directly from <head> or without <body> on the page";
		}
		
		if($('webdemon_iframe'))
		{
			throw "Only one WebDemon instance is supported";
		}

		onrecieve = onrcv_func;

		var el = document.createElement('IFRAME');
		
		var styles = { position: 'absolute', top: '0px', left: '0px', visibility: 'hidden' };
		for(var k in styles) el.style[k] = styles[k];
		
		backend_src = el.src = backend + (backend.indexOf('?') >= 0 ? '&' : '?') + 'InstanceId=0';
		el.width = 1;
		el.height = 1;
		el.id = 'webdemon_iframe';
		
		document.body.appendChild(el);
		//document.body.innerHTML = '<iframe id="webdemon_iframe" frameborder=0 vspace=0 hspace=0 width=1 height=1 scrolling=no src="'+backend_src+'"></iframe>';
		
		next_timeout = setTimeout(T.reconnect, TIMEOUT * 1000);
	};
	
	T.ping = function()
	{
		clearTimeout(next_timeout);
		next_timeout = setTimeout(T.reconnect, TIMEOUT * 1000);
	};
	
	T.rcv = function(iid /* instance id */, data)
	{
		if(!onrecieve)
		{
			throw "Recieve event registered, but is not available";
		}
		
		T.ping();
		
		onrecieve(data);
	};
	
	
})();