function DisplayTable() {
    var tableContent = '';
    // Browse each report
    var reportCount = reportArray.length;

    for (var i = 0; i < reportCount; i++) {
        var currentReport = reportArray[i];

        // Display columns of the current report
        tableContent += '<tr>\n';
        tableContent += '    <td class="reportTable"><strong>' + reportArray[i]['report_code'] + '</strong></td>\n';
        tableContent += '    <td class="reportTable">' + reportArray[i]['planif_name'] + '</td>\n';
        tableContent += '    <td class="reportTable">' + reportArray[i]['period'] + '</td>\n';
        tableContent += '    <td class="reportTable">' + reportArray[i]['date_maj'] + '</td>\n';
        tableContent += '    <td class="reportTable">' + reportArray[i]['user_responsable'] + '</td>\n';
        tableContent += '    <td class="reportTable">' + reportArray[i]['date_start'] + '</td>\n';
        // begin columns containing the buttons
        // ->infos (magnifying glass)
        tableContent += '    <td class="reportTable">';
        tableContent += '        <img src="ihm/bt-search.png" onclick="parent.Dialog(\'Crit&egrave;res\',\'<IFRAME src=/kurt-web/frames/scheduling_criteria.jsp?reportId='
            + currentReport['id']
            + ' width=350 height=220 frameBorder=0></IFRAME>\')" title="Afficher les crit&egrave;res" style="cursor:pointer;width:16px;height:16px;"/>\n';
        tableContent += '    </td>\n';

        // ->update planification page
        tableContent += '    <td class="reportTable">';
        tableContent += '        <img src="ihm/update.png"   onclick="updateSchedulingReport(\'' + currentReport['id']
            + "','" + reportArray[i]['report_code'] + '\');"  style="cursor:pointer;width:16px;height:16px;"/>\n';
        tableContent += '    </td>\n';

        // ->delete current planification
        tableContent += '    <td class="reportTable">';
        tableContent += '        <img src="ihm/delete.png" onclick="parent.Dialog(\'Suppression\',\'<IFRAME src=/kurt-web/frames/scheduling_delete.jsp?activeReportCode='
            + activeReportCode
            + '&reportId='
            + currentReport['id']
            + '&planif_name='
            + encodeURIComponent(currentReport['planif_name'])
            + ' width=550 height=80  frameBorder=0></IFRAME>\')" title="Supprimer une planification" style="cursor:pointer;width:16px;height:16px;"/>\n';
        tableContent += '    </td>\n';

        tableContent += '</tr>';
    }

    document.write(tableContent);
}

/* Redirect to page */
function GoSchedulingPage(i, j) {
    document.location.href = '/kurt-web/schedulingReader?page=' + i + "&reportCode=" + j;
}

/* build select active or not active report */
function displaySelectActivateDesactivateReport() {
    if ('TOUS' === activeReportCode) {
        document.getElementById('authorizedLabel').style.visibility = "hidden";
        document.getElementById('authorizedTd').style.visibility = "hidden";
    } else {
        document.getElementById('authorizedLabel').style.visibility = "visible";
        document.getElementById('authorizedTd').style.visibility = "visible";
        var selectContentIsActiveReport = '<select id="selectEnableDisable" style="width:80px;" >';

        if (isReportAuthorized === "OUI") {
            selectContentIsActiveReport += '<option selected="selected" value="TRUE">OUI</option>';
            selectContentIsActiveReport += '<option value="FALSE">NON</option>';
        } else {
            selectContentIsActiveReport += '<option  value="TRUE">OUI</option>';
            selectContentIsActiveReport += '<option selected="selected" value="FALSE">NON</option>';
        }
        selectContentIsActiveReport += '</select>';
        document.write(selectContentIsActiveReport);
    }
}

/* Redirect to page 1 */
function getReport(i) {
    document.location.href = '/kurt-web/schedulingReader?reportCode=' + i;
}

/* get current value on select */
function getSelectedValue(idElem) {
    var e = document.getElementById(idElem);
    var strUser = e.options[e.selectedIndex].value;
    return strUser;
}

/* persistence on select activate or enabled scheduling report */
function saveAction() {
    var curReportCode = "reportCode=" + activeReportCode;
    var valueOfSelect = "reportAuthorized=" + getSelectedValue("selectEnableDisable");
    var data = curReportCode + "&" + valueOfSelect;

    // Detection du navigateur pour la creation 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', "/kurt-web/activateDeactivate", true);
    objPostRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    objPostRequest.send(data);
    objPostRequest.onreadystatechange = ServerResponseForSaveActionConfirmation;
}

/* Popup after click button save to enabled or disabled report */
function ServerResponseForSaveActionConfirmation() {
    if (objPostRequest.readyState === 4) {
        if (objPostRequest.status === 200) {
            var queryResponse = JSON.parse(objPostRequest.responseText);
            if (queryResponse.status === "success") {
                parent.Dialog("Confirmation", queryResponse.success);
            } else {
                parent.Dialog("Erreur", queryResponse.error);
            }
        }
    }
}

/* */
function refreshSchedulingPage(i) {
    parent.hideDialog();
    top.frames['subFrame'].location.href = '/kurt-web/schedulingReader?reportCode=' + i;
}

/* Hidden or show button new when user select value "TOUS" */
function showHideButtonNewPlanification() {
    var selectBox = document.getElementById("selectReportType");
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;
    getReport(selectedValue);
}

function updateSchedulingReport(id, reportCode) {
    return callSchedulingReport("update", id, reportCode);
}

function newSchedulingReport() {
    return callSchedulingReport("create", "", "");
}

function callSchedulingReport(status, id, reportCode) {

    var reportCodeActive = "";
    // reportCode = reportCode.replace("R", "");
    reportCodeActive = activeReportCode.replace("R", "");
    if (status === "create") {
        var theReportCode = activeReportCode;
        document.location.href = '/kurt-web/frames/scheduling_new.jsp?activeSchedulingList=' + reportCodeActive
            + '&reportCode=' + theReportCode;
    } else {
        document.location.href = '/kurt-web/frames/scheduling_update.jsp?activeSchedulingList=' + reportCodeActive
            + '&id=' + id + '&reportCode=' + reportCode;
    }
}

function getSubPeriod(name, id, isActive) {
    // Detection du navigateur pour la creation de l'objet XMLHttpRequest
    if (window.XMLHttpRequest) {
        objPostRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        objPostRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var concat = "&";
    var subPeriodData = 'subPeriod=' + encodeURIComponent(name);
    var isUpdate = 'isUpdate=' + encodeURIComponent(isActive);
    var idData = 'id=' + encodeURIComponent(id);

    // Envoi du formulaire en AJAX
    objPostRequest.open('post', "/kurt-web/getScheduling", true);
    objPostRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    objPostRequest.send(subPeriodData + concat + isUpdate + concat + idData);
    objPostRequest.onreadystatechange = ServerResponseForGetSubPeriod;
}

function createDiv(content) {

    var container = document.createElement('div');
    container.id = "div_temp";
    container.innerHTML = content;

    return container;
}

// div_container_sub_period
function ServerResponseForGetSubPeriod() {
    if (objPostRequest.readyState == 4) {
        if (objPostRequest.status == 200) {
            var queryResponse = JSON.parse(objPostRequest.responseText);

            var containerSubPeriod = document.getElementById("div_container_subPeriod");
            containerSubPeriod.innerHTML = "";

            if (queryResponse.status == "success") {
                containerSubPeriod.innerHTML = queryResponse.content;
                initPicker('datepicker_planification', 'container_planification');
            } else {
                containerSubPeriod.innerHTML = "Oh oh ......"; // FIXME
            }
        } else if (objPostRequest.status === 500) {
            document.getElementById("div_container_subPeriod").innerHTML = "Erreur interne du serveur d&eacute;tect&eacute;e. ";

        } else {
            document.getElementById("div_container_subPeriod").innerHTML = "La connexion avec le site semble interrompue.";

        }

    }
}

// Methode d'envoi via POST d'un formulaire
function deleteCommand(schedulingReportId) {
    // active progress bar
    showProgressBarOnDelete();
    // Detection du navigateur pour la creation de l'objet XMLHttpRequest
    if (window.XMLHttpRequest)
        objPostRequest = new XMLHttpRequest();
    else if (window.ActiveXObject)
        objPostRequest = new ActiveXObject("Microsoft.XMLHTTP");
    var data = 'scheduling_report_id=' + encodeURIComponent(schedulingReportId);
    // Envoi du formulaire en AJAX
    objPostRequest.open('post', "/kurt-web/scheduling/delete", true);
    objPostRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    objPostRequest.send(data);
    objPostRequest.onreadystatechange = ServerResponseForDeleteCommand;
}

/* Callback on delete */
function ServerResponseForDeleteCommand() {
    if (objPostRequest.readyState == 4) {
        if (objPostRequest.status == 200) {
            var queryResponse = JSON.parse(objPostRequest.responseText);
            document.getElementById("div_message").innerHTML = "";
            if (queryResponse.status == "success") {
                document.getElementById("div_message").innerHTML = queryResponse.success;
            } else {
                document.getElementById("div_message").innerHTML = queryResponse.failed;
            }
            // add button to close popup
            document.getElementById("div_buttons").innerHTML = "";
            document.getElementById("div_buttons").innerHTML = addButtonClose();
        } else {
            document.getElementById("div_message").innerHTML = "Erreur interne du serveur d&eacute;tect&eacute;e. ";
            document.getElementById("div_buttons").innerHTML = "";
            document.getElementById("div_buttons").innerHTML = addButtonClose();
        }
    }
}

/* Use on delete */
function showProgressBarOnDelete() {
    document.getElementById("div_message").innerHTML = progressBar();
    document.getElementById("div_buttons").innerHTML = "";
}

/* Build a progress bar */
function progressBar() {
    return "<i>Traitement en cours...</i>" + "<br/>"
        + "<img src=\"/kurt-web/ihm/progress.gif\" vspace=\"6\" width=\"129\" height=\"20\">";
}

/* build a close button */
function addButtonClose() {
    return "<button class=\"formButton\" onclick=\"refreshSchedulingPage('" + activeReportCode + "')\">Fermer</button>";
}

/* */
function sendSchedulingReport(targetUrl, optionalParameters) {
    /* call check of current report and call check of scheduling */

    var isFormOK = checkForm();
    var isSchedulingOK = checkParamScheduling();
    if (isFormOK && isSchedulingOK) {
        // PostForm(targetUrl,"reportSchedulingForm");
        /* Display loading bar and hide buttons */
        document.getElementById("loading").style.display = '';
        document.getElementById("div_buttons").style.display = 'none';
        postScheduling(targetUrl, "reportSchedulingForm", optionalParameters);
    }

}

function postScheduling(url, form, optionalParameters) {
    /* Lecure des donnees du formulaire */
    var data = getFormData(form);
    data += optionalParameters;
    /* Detection du navigateur pour la creation 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); // Unsafe!
    objPostRequest.onreadystatechange = serverResponseForPostScheduling;
    objPostRequest.send(data);
}

function serverResponseForPostScheduling() {
    if (objPostRequest.readyState == 4) {
        if (objPostRequest.status == 200) {
            var queryResponse = JSON.parse(objPostRequest.responseText);
            if (queryResponse.status == "success") {
                parent.Dialog("Confirmation", queryResponse.success);
            } else {
                parent.Dialog("Erreur", queryResponse.error);
            }
        } else if (objPostRequest.status == 500) {
            parent.Dialog("Erreur", "Erreur interne du serveur d&eacute;tect&eacute;e.");
        } else {
            parent.Dialog("Erreur", "La connexion avec le site semble interrompue.");
        }
        // Display buttons and hide loading bar
        document.getElementById("loading").style.display = 'none';
        document.getElementById("div_buttons").style.display = '';
    }
}

/* check input button text of radio_all_month_day */
function checkIsValidDay() {
    return isValidDay("dayInMonthValue");
}

/* check input in field day in month */
function isValidDay(inputText) {
    var element = document.getElementById(inputText);
    var isGood = true;
    if (isNaN(element.value) || element.value == "" || element.value < 1 || element.value > 31) {
        isGood = false;
    }
    return isGood;
}

/* Check fields of planification */
function checkParamScheduling() {
    var maxCharacter = 40;
    if (!checkMaxLenghtOnInputText("scheduling_name", maxCharacter)) {
        parent.Dialog("Erreur", "Le champ Nom ne peut pas contenir plus de " + maxCharacter + " caract&egrave;res.");
        return false;
    }
    if (!checkInputAlphanumeric("scheduling_name")) {
        parent.Dialog("Erreur", "Le champ Nom ne peut contenir que des caract&egrave;res alphanum&eacute;riques.");
        return false;
    }
    /* Filed may not be empty */
    if (isEmptyFieldMaybeMandatory("scheduling_name", false)) {
        document.getElementById("scheduling_name").focus();
        parent.Dialog("Erreur", "Saisir un nom pour la planification.");
        return false;
    }
    if (!checkInputRadioDayOfMonth()) {
        document.getElementById("scheduling_name").focus();
        parent
            .Dialog("Erreur",
                "Vous avez choisi une planification par mois, le champ ne doit pas etre vide ou comporter un jour entre 1 et 31.");
        return false;
    }
    if (!checkInputRadioByDate()) {
        document.getElementById("scheduling_name").focus();
        parent.Dialog("Erreur", "Vous avez choisi une planification par date, le champ ne doit pas etre vide.");
        return false;
    }
    return true;
}

/* Check by month */
function checkInputRadioDayOfMonth() {
    var returnValue = true;
    if ((document.getElementById('div_period_monthly').checked) && (document.getElementById('dayInMonthValue').checked)) { // A
        // day
        // in
        // month
        // is
        // selected
        // --> field day in month may not be empty and between 1-31 day of month
        returnValue = checkIsValidDay();
    }
    return returnValue;
}

/* Check by date */
function checkInputRadioByDate() {
    var returnValue = true;
    // radio date
    if (document.getElementById('div_period_date').checked) {
        if (document.getElementById('datepicker_planification').value === "") {
            returnValue = false;
        }
    }
    return returnValue;
}

/* Check max length on input text */
function checkMaxLenghtOnInputText(idOfInput, max) {
    var element = document.getElementById(idOfInput);
    var returnValue = true;
    if (element.value.length > max) {
        returnValue = false;
    }
    return returnValue;
}

/* Regex Authorized -> alaphanumeric[a-zA-Z0-9_], -, éèçà, whitespace and start min:0 to max:40 car */
function checkInputAlphanumeric(idOfInput) {
    var text = document.getElementById(idOfInput).value;
    // var check = new RegExp("^([a-zA-Z0-9_-\\s]{0,40})$", "g");
    var check = /^([\w- éèçà]{0,40})$/;
    return check.test(text);
}
