/**
 * Tool for sending an AJAX request with a POST form. Be careful: the callback function called
 * "ServerResponseForPostForm" should be defined in your page.
 */

/* Declaration de l'objet HttpRequest global */
var objPostRequest = null;

/* Retourne la liste des éléments HTML composant un formulaire */
function getFormData(id) {
    var formEl = '';
    var LMR = '';
    var obF = document.getElementById(id);
    var elements = obF.elements;
    for (var i = 0; i < obF.length; i++) {
        /* LMR is for R20 report */
        if (elements[i].name === 'LMR') {
            if (elements[i].value == "")
                continue;
            if (LMR == '') {
                LMR += elements[i].name + '=' + escape(elements[i].value);
            } else {
                LMR += ";" + escape(elements[i].value);
            }
        } else if (elements[i].name + "" != "") {
            /* For check-boxes and radio button only take into account of checked values */
            if ((elements[i].type === 'radio') || (elements[i].type === 'checkbox')) {
                if (!elements[i].checked) {
                    continue;
                }
            }
            if (formEl != '') {
                formEl += "&";
            }
            formEl += elements[i].name + '=' + escape(elements[i].value);
        }
    }
    if (LMR != '') {
        formEl += "&" + LMR;
    }
    return formEl;
}

/* Méthode d'envoi via POST d'un formulaire */
function PostForm(url, form) {
    /* Lecture des données du formulaire */
    var data = getFormData(form);
    /* Détection du navigateur pour la création de l'objet XMLHttpRequest */
    if (window.XMLHttpRequest)
        objPostRequest = new XMLHttpRequest();
    else if (window.ActiveXObject)
        objPostRequest = new ActiveXObject("Microsoft.XMLHTTP");

    /* Envoi du formulaire en AJAX */
    objPostRequest.open('post', url, true);
    objPostRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    objPostRequest.setRequestHeader("Content-length", data.length);
    objPostRequest.onreadystatechange = ServerResponseForPostForm;
    objPostRequest.send(data);
}
