// XMLHttpRequest Factory
var xmlHttpObjects = new Array();

function getXmlHttpObjectIndex() {
    for (var i in xmlHttpObjects) {
        if(typeof(xmlHttpObjects[i]) != 'undefined') {
            if(xmlHttpObjects[i].readyState == 0 || xmlHttpObjects[i].readyState == 4) {
                xmlHttpObjects[i] = null;
                try { xmlHttpObjects[i] = new XMLHttpRequest(); }
                catch(e) { xmlHttpObjects[i] = new ActiveXObject("Microsoft.XMLHTTP"); }
                return i;
            }
        }
    }
    var newXmlHttpObject;
    try { newXmlHttpObject = new XMLHttpRequest(); }
    catch(e) { newXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP"); }
    xmlHttpObjects[xmlHttpObjects.length] = newXmlHttpObject;
    return xmlHttpObjects.length - 1;
}

function initSupercellRemote() {
    var xmlHttpIndex = getXmlHttpObjectIndex();
    xmlHttpObjects[xmlHttpIndex].onreadystatechange = function() {
        if(xmlHttpObjects[xmlHttpIndex].readyState == 4) {
            document.getElementById("scrAuthentication").innerHTML = xmlHttpObjects[xmlHttpIndex].responseText;
        }
    }
    
    xmlHttpObjects[xmlHttpIndex].open("GET", "supercell/supercellRemote.php", true);
    xmlHttpObjects[xmlHttpIndex].send(null);
}

function scrSubmitLogin() {
    var xmlHttpIndex = getXmlHttpObjectIndex();
    
    xmlHttpObjects[xmlHttpIndex].onreadystatechange = function() {
        if(xmlHttpObjects[xmlHttpIndex].readyState == 4) {
            window.location.reload();
        }
    }
    
    var scrAuthUsername = encodeURI(document.getElementById("scrAuthUsername").value);
    var scrAuthPassword = encodeURI(document.getElementById("scrAuthPassword").value);
    document.getElementById("scrAuthentication").innerHTML = '<div style="text-align: center; padding-top: 32px; padding-bottom: 32px;">Processing...</div>';
    xmlHttpObjects[xmlHttpIndex].open("GET", "supercell/supercellRemote.php?username=" + scrAuthUsername + "&password=" + scrAuthPassword, true);
    xmlHttpObjects[xmlHttpIndex].send(null);
}

function scrSubmitLogout() {
    var xmlHttpIndex = getXmlHttpObjectIndex();
    
    xmlHttpObjects[xmlHttpIndex].onreadystatechange = function() {
        if(xmlHttpObjects[xmlHttpIndex].readyState == 4) {
            window.location.reload();
        }
    }
    
    document.getElementById("scrAuthentication").innerHTML = '<div style="text-align: center; padding-top: 32px; padding-bottom: 32px;">Processing...</div>';
    xmlHttpObjects[xmlHttpIndex].open("GET", "supercell/supercellRemote.php?logout", true);
    xmlHttpObjects[xmlHttpIndex].send(null);
}

