﻿var xmlHttp;

function MakeXmlHttpObject() {
    xmlHttp = null;

    try { // XmlHttpRequest para IE7+, Firefox,Opera, Safari e derivados.
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try { // IE6
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) { // IE5-
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    return xmlHttp;
}

// Estado 0 - Pedido não iniciado.
// Estado 1 - Pedido configurado.
// Estado 2 - Pedido enviado.
// Estado 3 - Pedido em processo.
// Estado 4 - Pedido completo e recebido.
function desvia(func, xmlResponse) {
    var state = xmlHttp.readyState;
    var response = "";

    if (state == 4) {
        response = xmlResponse? xmlHttp.responseXML: xmlHttp.responseText;
    }

    func.call("", state, response);
}

function requisita(pagina, paramPost, func, xmlResponse) {
    xmlHttp = MakeXmlHttpObject()

    if (!xmlHttp)
        return false; //O navegador não suporta AJAX

    if (!paramPost)
        paramPost = "";

    xmlHttp.open("POST", pagina, true);

    if (func) {
        xmlHttp.onreadystatechange = function() { desvia(func, xmlResponse); };
    }

    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.setRequestHeader('Content-length', paramPost.length);

    xmlHttp.send(paramPost);

    return true;
}
