/**
 * performs an asynchronous request to the given url via a POST, sending it
 * the given args (which can be null).  If the callback is non-null, it will
 * be passed the response text when the request has completed.  If sync is true,
 * the call will be synchronous. retry should not be given a value.
 */
function ajax(url, args, callback, sync, retry) {
    if (window.XMLHttpRequest)
	var req = new XMLHttpRequest();
    else
	var req = new ActiveXObject("Microsoft.XMLHTTP");
    req.open("POST", url, !sync);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    req.onreadystatechange = function() {
	if (req.readyState == 4) {
	    try {
		var st = req.status;
	    } catch (e) {
		return;
	    }
	    if (st == 200 || st == undefined) {
		var text = req.responseText;
		if (callback && text)
		    callback(text);
	    } else {
		var retry = retry || 0;
		if (retry >= 5) {
		    callback(undefined);
		} else {
		    setTimeout(function() {
			ajax(url, args, callback, retry + 1);
		    }, 10000);
		}
	    }
	}
    }
    var vars = "";
    if (args) {
	for (var a in args)
	    vars += a + "=" + encodeURIComponent(args[a]) + "&";
	vars = vars.substring(0, vars.length - 1);
    }
    req.send(vars);
}

/*
 * Creates a popup window.
 *
 * Any of the arguments to this function can be null or omitted.
 * If url is null, an empty popup will be created.
 * If no name is specified, a randomly generated name will be assigned.
 * If noreload is true, the window will be raised but not reloaded.
 */
function popup(url, width, height, features, name, noreload) {
    if (!url)
	url = "";
    var f = "";
    if (width)
	f += "width=" + width;
    if (height) {
	if (f.length > 0)
	    f += ",";
	f += "height=" + height;
    }
    if (features) {
	if (f.length > 0)
	    f += ",";
	f += features;
    }
    if (!name)
        name = "popup" + Math.round(Math.random() * 1000);
    var popup = window.open("", name, f);
    if (!popup.opener)
	popup.opener = self;
    try {
	if (!noreload || popup.location.href.indexOf(url) < 0)
	    popup.location = url;
    } catch (e) {
	// looking at the location can throw an exception
    }
    popup.focus();
    return popup;
}
function openChat(script) {
    if (script)
	ajax(script, null, null, true);
    popup("/ec/chat.jtp",700,500,"resizable=1","chat",true);
}
function checkInvite() {
    if (++inviteCount > 40) {
	clearInterval(inviteTimeout);
    } else {
	ajax("/peek/ajax/invitation.jtp", null, function(html) {
	    clearInterval(inviteTimeout);
	    $("#invitation").html(html);
	});
    }
}
