var xmlreqs = new Array();

function Request(xmlhttp, callback, arg)
{
    this.xmlhttp = xmlhttp;
    this.callback = callback;
    this.arg = arg;
}

function new_xmlhttp()
{
    var request = false;
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = false;
            }
        }
    }

    if (!request)
        alert("Error initializing XMLHttpRequest!");

    return request;
}

function xmlhttp_statechange()
{
    if (typeof(window['xmlreqs']) == "undefined") return;
        
    for (var i=0; i < xmlreqs.length; i++) {
        if (xmlreqs[i].xmlhttp.readyState == 4) {
            try {
                if (xmlreqs[i].xmlhttp.status == 200 || xmlreqs[i].xmlhttp.status == 304) {
                    // 200 OK
                    var callback = xmlreqs[i].callback;
                    var arg = xmlreqs[i].arg;
                    var response = xmlreqs[i].xmlhttp.responseText;
        
                    xmlreqs.splice(i,1);
                    i--;

                    callback(response, arg);
                } else {
                    // error
                    //alert("returned status: "+xmlreqs[i].xmlhttp.status);
                    xmlreqs.splice(i,1);
                    i--;
                }
            } catch(e) {
                //alert("communication error"+" reqlen: "+xmlreqs.length);
                // communication error
                xmlreqs.splice(i,1);
                i--;
            }
        }
        if (xmlreqs.length <= 0) {
            //logo_static();
        }
    }
}

function async_GET(url, callback, arg)
{
    var xmlhttp = false;

    xmlhttp = new_xmlhttp();
    if (xmlhttp) {
        var req = new Request(xmlhttp, callback, arg);
        xmlreqs.push(req);

        xmlhttp.onreadystatechange = xmlhttp_statechange;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
//        logo_animate();
    }
}

function async_POST(url, data, callback, arg)
{
    var xmlhttp = false;

    xmlhttp = new_xmlhttp();
    if (xmlhttp) {
        var req = new Request(xmlhttp, callback, arg);
        xmlreqs.push(req);
        xmlhttp.onreadystatechange = xmlhttp_statechange;
        xmlhttp.open("POST",url,true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xmlhttp.send(data);
//        logo_animate();
    }
}
