// Copyright 2009 Sleepless Software Inc.  All Rights Reserved 

/*function comet_default_err_func(a)
{
	var msg = "\nERROR: "+a.explanation+"\n";
	//alert(a.explanation+"\n{"+a.code+"}\n"+a.result+"\n");
	alert(msg);
}*/

function comet(url, okfunc, errfunc, data, async)
{
	if(!errfunc || (!errfunc instanceof Function))
	{
		if(typeof comet_err === "function")
			comet_err(a);
		else	
			errfunc = function(a) { alert("\nERROR: "+a.explanation+"\n"); };
	}

	if(!async)
		async = true;

	var request = null;
	try {
		if(typeof ActiveXObject != "undefined")
			request = new ActiveXObject("Microsoft.XMLHTTP");	// ie
		else
		if(window.XMLHttpRequest)
			request = new XMLHttpRequest();		// firefox
		else
			alert("comet error 1");
	} catch(exc) { alert("comet error 2"); }

	request.onreadystatechange = function()
		{
			if(request.readyState != 4)
				return;
			var c = parseInt(request.status);
			var t = request.responseText;
			var a = { ok: false, code: c, explanation: 'Communication error', result: t };
			if(c == 200)
			{
				a.code = 1;
				a.explanation = 'Unknown error';
				var m = t.match(/^[ \n]*(\d+) ([^\n]+)\n([^\f]*)/);	// definition of "kludge"
				if(m)
				{
					a.code = parseInt(m[1]);
					a.explanation = m[2];
					a.result = m[3];
					a.ok = (a.code == 0);
				}
				else
				{
					a.explanation = t.substr(0, 50)+" ...";
				}
			}
			if(a.ok)
			{
				if(okfunc && okfunc instanceof Function)
					okfunc(a);
				else
				if(typeof comet_ok === "function")
					comet_ok(a);
			}
			else
			{
				errfunc(a);
			}
			request.onreadystatechange = function() {}
		};

	if(data == undefined)
		data = null;

	request.open(data ? "POST" : "GET", url, async);

	if(data)
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	request.send(data ? data : null);
}

function comet_marshal(list, sep)
{
	if(!sep)
		sep = ";";
	var amp = "";
	var args = "";
	iter(list.split(sep), function (e, i) {
		if(e)
		{
			args += amp+e+"="+escape(elem(e).value);
			amp = "&";
		}
	});
	return args;
}

function cc(cmd)
{
	comet("comet?cmd="+escape(cmd));
}


