var data_form = {
    etes_vous: '',
    reclamation_deja_faite: '',
    date_reclamation: '',
    service_client: '',
    depot_plainte: '',
    quelle_personne: '',
    raison: '',
    civilite: '',
    nom: '',
    prenom: '',
    email: '',
    adresse: '',
    codepostal: '',
    ville: '',
    pays: '',
    tel: '',
    numero_compte: '',
    votre_agence: '',
    civilite2: '',
    nom2: '',
    prenom2: '',
    email2: '',
    adresse2: '',
    codepostal2: '',
    ville2: '',
    pays2: '',
    tel2: '',
    numero_compte2: '',
    votre_agence2: '',
    theme_principale: '',
    texte_raison: '',
    valeur: '',
    texte_estimation: '',
    reclamation_upload: '',
    reponse_upload: '',
    plainte_upload: '',
    pouvoir_upload: '',
    file_upload: '',
};
var reclamation_upload = new Array();
var reponse_upload = new Array();
var plainte_upload = new Array();
var pouvoir_upload = new Array();
var file_upload = new Array();
var formulaire = {
    fileNumber: 0,
    filesize: 3000 * 1024,
    filetypes: [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'image/gif',
        'image/jpeg',
        'image/png',
        'image/bmp'
    ],
    init: function (jQuery) {
        jQuery('.moi, .autre, .panel').hide();
        jQuery('.step1').show();
        jQuery('.inputFile').css('opacity', '0');
        jQuery('input[name="noJS"]').remove();
        jQuery('.button_validation').click(function (e) {
            if (jQuery(this).attr('value') == "TERMINER") {
                formulaire.reset_formulaire();
            }
            var panel = jQuery(this).parents('.panel');
            var step = /(step[\d]+)/i.exec(panel.attr('class'));
            if (!step)
                step = 1;
            else
                step = step[1];
            if (jQuery(this).attr('name') == "boutton_retour") {
                formulaire.etape_precedente(jQuery(this));
            } else if (jQuery(this).attr('name') == "boutton_retour2") {
                formulaire.etape_actuelle(jQuery(this));
            } else if (formulaire.traitement(step, e)) {
                formulaire.etape_suivante(jQuery(this));
            }
        });
        jQuery('.button_validation2').click(function (e) {
            formulaire.addField(this);
        });

        if (typeof File == 'undefined')
            jQuery('.fzise').hide();

        jQuery('input[type="text"]').blur(function () {
            if (jQuery(this)[0].value != "")
                jQuery(this).parents('td').find('.erreur').hide();
        });

        jQuery('.reload-cap').click(function () {
            jQuery('#sdsgiu').attr('src', '/captcha-image.php?' + new Date().getTime());
            return false;
        })

        jQuery('.cnil').show();
        jQuery('.step1 .contenu, .step1 .contenu .stop').not('.c1, .cValide').hide();
        jQuery('.step1 .contenu input:radio').prop('checked', false);

        jQuery('.step1 .c1 input:radio').on('change', function () {
            switch (jQuery(this).val()) {
                case 'particulier':
                    jQuery('.step1 .c1 .stop, .step1 .cValide input[name="boutton_validation"]').hide();
                    jQuery('.step1 .c2, .c2a').show();
                    if (jQuery('.step1 .c4 input:radio:checked').length)
                        jQuery('.step1 .cValide input[name="boutton_validation"]').show();
                    break;
                case 'professionnel':
                    jQuery('.step1 .contenu, .step1 .cValide input[name="boutton_validation"], .c2a').not('.c1, .c3, .c4, .cValide').hide();
                    jQuery('.step1 .c1 .stop').show();
                    break;
            }
        });

        jQuery('.step1 .c2 input[name="reclamation_deja_faite"]').on('change', function () {
            switch (jQuery(this).val()) {
                case 'oui':
                    jQuery('.step1 .c2 .stop-non, .step1 .c2 .stop-date-invalide, .step1 .c2 .stop-date-moins-2, .step1 .c2 .stop-date-plus-12, .step1 .c2 .date-ok').hide();
                    // jQuery('.step1 .c2').show();
                    jQuery('.step1 .c2a, .step1 .c2 .oui, .step1 .cValide').show();

                    var date = jQuery('.step1 .c2 input#date_reclamation').val();
                    if (date && /\d{4}-\d{2}-\d{2}/.test(date))
                        date_reclamation(date);
                    break;
                case 'non':
                    jQuery('.step1 .c2a, .step1 .c2 .oui, .step1 .c2 .stop-date-invalide, .step1 .c2 .stop-date-moins-2, .step1 .c2 .stop-date-plus-12, .step1 .c2 .date-ok, .step1 .cValide').not('.c2').hide();
                    jQuery('.step1 .c2 .stop-non').show();
                    break;
            }
        });

        function date_reclamation(date) {
            date = new Date(date);
            var month2 = new Date(),
                month12 = new Date();
            month2.setMonth(month2.getMonth() - 2);
            month12.setMonth(month12.getMonth() - 12);

            jQuery('.step1 .c2 .stop-non, .step1 .c2 .stop-date-invalide, .stop-date-moins-2, .step1 .c2 .stop-date-plus-12, .step1 .c2 .date-ok, .step1 .cValide input[name="boutton_validation"], .step1 .c2a').hide();
            if (month2 < date) {
                jQuery('.step1 .c2 .stop-date-moins-2').show();
            } else if (date < month12) {
                jQuery('.step1 .c2 .stop-date-plus-12').show();
            } else {
                jQuery('.step1 .c2 .date-ok, .step1 .c3, .step1 .c2a').show();
                if (jQuery('.step1 .c4 input:radio:checked').length)
                    jQuery('.step1 .cValide input[name="boutton_validation"]').show();
            }
        }

        jQuery('.step1 .c2 input#date_reclamation').on('change', function () {
            var date = jQuery(this).val();
            if (date && /\d{4}-\d{2}-\d{2}/.test(date)) {
                date_reclamation(date);
            } else {
                jQuery('.step1 .c2 .stop-date-invalide').show();
                jQuery('.step1 .c2 .stop-non, .step1 .c2 .stop-date-moins-2, .step1 .c2 .stop-date-plus-12, .step1 .c2 .date-ok, .step1 .cValide input[name="boutton_validation"], .step1 .c2a').hide();
            }
        });
        jQuery('.step1 .c3 input:radio').on('change', function () {
            switch (jQuery(this).val()) {
                case 'oui':
                    jQuery('.step1 .c3 .oui').show();
                    break;
                case 'non':
                    jQuery('.step1 .c3 .oui').hide();
                    jQuery('.step1 .c3 input:file').parent().removeAttr('style');
                    jQuery('.step1 .c3 input:file').val('');
                    jQuery('.step1 .c3 input.isFileOk').val('1');
                    jQuery('.step1 .c3 .fileSize').text('0');
                    jQuery('.step1 .c3 .fcrc32Hidden').val('');
                    break;
            }
            jQuery('.step1 .c4').show();
        });
        jQuery('.step1 .c4 input:radio').on('change', function () {
            switch (jQuery(this).val()) {
                case 'oui':
                    jQuery('.step1 .c4 .oui').show();
                    break;
                case 'non':
                    jQuery('.step1 .c4 .oui').hide();
                    jQuery('.step1 .c4 input:file').parent().removeAttr('style');
                    jQuery('.step1 .c4 input:file').val('');
                    jQuery('.step1 .c4 input.isFileOk').val('1');
                    jQuery('.step1 .c4 .fileSize').text('0');
                    jQuery('.step1 .c4 .fcrc32Hidden').val('');
                    break;
            }
            jQuery('.step1 .cValide input[name="boutton_validation"]').show();
        });

        jQuery('.step2 input[name="quelle_personne"]').click(function () {
            jQuery('.moi .autre').hide();
            jQuery('.step2 .bloque_complet').removeAttr('style');

            if (jQuery(this)[0].value == "Pour vous-même") {
                jQuery('input[name="pour_qui"]').val('');
                jQuery('.moi').show();
                jQuery('.autre').hide();
            } else {
                jQuery('input[name="pour_qui"]').val('1');
                jQuery('.moi').hide();
                jQuery('.autre').show();
            }

            jQuery('.pouvoir').hide();
            if (jQuery(this).data('pouvoir') != 0) {
                jQuery('.pouvoir1, .pouvoir2').hide();
                jQuery('.pouvoir, .pouvoir' + jQuery(this).data('pouvoir')).show();
            }
            jQuery('.erreur').hide();
        });

        jQuery('.step2 input[name="quelle_personne"]').click(function () {
            jQuery('.moi .autre').hide();
            jQuery('.step2 .bloque_complet').removeAttr('style');

            if (jQuery(this)[0].value == "Pour vous-même") {
                jQuery('input[name="pour_qui"]').val('');
                jQuery('.moi').show();
                jQuery('.autre').hide();
            } else if (jQuery(this)[0].value == "Association") {
                jQuery('input[name="pour_qui"]').val('1');
                jQuery('.moi, .noAssoc').hide();
                jQuery('.autre, .assoc').show();
            } else {
                jQuery('input[name="pour_qui"]').val('1');
                jQuery('.moi, .assoc').hide();
                jQuery('.autre, .noAssoc').show();
            }
            jQuery('.erreur').hide();
        });

        jQuery('.enregistrement').click(function () {
            data_form.reclamation_upload = reclamation_upload;
            data_form.reponse_upload = reponse_upload;
            data_form.plainte_upload = plainte_upload;
            data_form.pouvoir_upload = pouvoir_upload;
            data_form.file_upload = file_upload;
        });

        jQuery('textarea').each(function () {
            jQuery(this).focus(function () {
                if (jQuery(this).val() == 'Saisissez votre texte...')
                    jQuery(this).empty();
            })
        });

        jQuery('.erreur').click(function () {
            jQuery(this).hide();
        });

    },
    reset_formulaire: function () {
        location.reload();
    },
    inArray: function (search, array) {
        for (k in array) {
            if (array[k].toLowerCase() == search.toLowerCase())
                return k;
        }
        return false;
    },
    traitement: function (step, e) {
        jQuery('.erreur').hide();
        jQuery('.' + step + '.c1').show();
        jQuery('.' + step + '.c2').hide();

        switch (step) {
            case 'step1':
                data_form.etes_vous = jQuery('.' + step).find('input:radio[name="etes_vous"]:checked').val();
                data_form.reclamation_deja_faite = jQuery('.' + step).find('input:radio[name="reclamation_deja_faite"]:checked').val();
                data_form.service_client = jQuery('.' + step).find('input:radio[name="service_client"]:checked').val();
                data_form.depot_plainte = jQuery('.' + step).find('input:radio[name="depot_plainte"]:checked').val();

                if (!data_form.etes_vous) {
                    jQuery('.' + step).find('.c1 .erreur').show(500);
                    return false;
                }
                if (!data_form.reclamation_deja_faite) {
                    jQuery('.' + step).find('.c2 .erreur').show(500);
                    return false;
                } else if (data_form.reclamation_deja_faite == 'non') {
                    jQuery('input[name^="reclamation_upload["]').each(function () {
                        var c = jQuery(this);
                        var cp = c.parent();
                        if (c.val())
                            return false;
                        cp.find('.isFileOk').val('1');
                        cp.find('.fziseHidden').val('0');
                        cp.find('.fcrc32Hidden').val('');
                    });
                }
                if (!jQuery('input[name="reclamation_upload[0]"]').val()) {
                    jQuery('input[name="reclamation_upload[0]"]').parent().css({ 'border': '2px solid red' });
                    jQuery('input[name="reclamation_upload[0]"]').parent().find('.isFileOk').val('0');
                    alert("Pour continuer, veuillez joindre une copie de votre réclamation écrite avec la preuve de sa date d’envoi ou de réception.");
                    jQuery('input[name="reclamation_upload[0]"]').focus();
                    return false;
                }
                if (!data_form.service_client) {
                    jQuery('.' + step).find('.c3 .erreur').show(500);
                    return false;
                } else if (data_form.service_client == 'non') {
                    jQuery('input[name^="reponse_upload["]').each(function () {
                        var c = jQuery(this);
                        var cp = c.parent();
                        if (c.val())
                            return false;
                        cp.find('.isFileOk').val('1');
                        cp.find('.fziseHidden').val('0');
                        cp.find('.fcrc32Hidden').val('');
                    });
                }
                if (data_form.service_client == 'oui' && !jQuery('input[name="reponse_upload[0]"]').val()) {
                    jQuery('input[name="reponse_upload[0]"]').parent().css({ 'border': '2px solid red' });
                    jQuery('input[name="reponse_upload[0]"]').parent().find('.isFileOk').val('0');
                    alert("Pour continuer, veuillez joindre toutes les réponses reçues.");
                    jQuery('input[name="reponse_upload[0]"]').focus();
                    return false;
                }

                if (!data_form.depot_plainte) {
                    jQuery('.' + step).find('.c4 .erreur').show(500);
                    return false;
                } else if (data_form.depot_plainte == 'non') {
                    jQuery('input[name^="plainte_upload["]').each(function () {
                        var c = jQuery(this);
                        var cp = c.parent();
                        if (c.val())
                            return false;
                        cp.find('.isFileOk').val('1');
                        cp.find('.fziseHidden').val('0');
                        cp.find('.fcrc32Hidden').val('');
                    });
                }
                if (data_form.depot_plainte == 'oui' && !jQuery('input[name="plainte_upload[0]"]').val()) {
                    jQuery('input[name="plainte_upload[0]"]').parent().css({ 'border': '2px solid red' });
                    jQuery('input[name="plainte_upload[0]"]').parent().find('.isFileOk').val('0');
                    alert("Pour continuer, veuillez joindre la copie du procès verbal de dépôt de plainte.");
                    jQuery('input[name="plainte_upload[0]"]').focus();
                    return false;
                }

                var error = false,
                    isFileOk = jQuery('.' + step).find('.isFileOk');
                isFileOk.each(function () {
                    if (jQuery(this).val() != '1')
                        error = true;
                });

                if (error) {
                    alert("Les fichiers entourés de rouge dépassent la taille de fichier demandés ou ne sont pas dans un format autorisé.");
                    return false;
                }

                var date_reclam = false;
                var date = jQuery('.' + step + ' .c2 input#date_reclamation').val();
                if (date && /\d{4}-\d{2}-\d{2}/.test(date)) {
                    date = new Date(date);
                    var month2 = new Date(),
                        month12 = new Date();
                    month2.setMonth(month2.getMonth() - 2);
                    month12.setMonth(month12.getMonth() - 12);

                    if (month2 >= date && date >= month12) {
                        date_reclam = true;
                    }
                }

                if (!date_reclam || data_form.etes_vous != "particulier" || data_form.reclamation_deja_faite != "oui")
                    return false;

                break;
            case 'step2':
                var errors = new Array();
                var champs = jQuery('input[name="pour_qui"]').val();
                data_form.quelle_personne = jQuery('.' + step).find('input[name="quelle_personne"]:checked').val();
                data_form.civilite = jQuery('.' + step).find('input[name="civilite' + champs + '"]:checked').val();
                data_form.raison = jQuery('.' + step).find('input[name="raison"]').val();
                data_form.nom = jQuery('.' + step).find('input[name="nom' + champs + '"]').val();
                data_form.prenom = jQuery('.' + step).find('input[name="prenom' + champs + '"]').val();
                data_form.ville = jQuery('.' + step).find('input[name="ville' + champs + '"]').val();
                data_form.email = jQuery('.' + step).find('input[name="email' + champs + '"]').val();
                data_form.adresse = jQuery('.' + step).find('input[name="adresse' + champs + '"]').val();
                data_form.codepostal = jQuery('.' + step).find('input[name="codepostal' + champs + '"]').val();
                data_form.pays = jQuery('.' + step).find('input[name="pays' + champs + '"]').val();
                data_form.tel = jQuery('.' + step).find('input[name="tel' + champs + '"]').val();
                data_form.numero_compte = jQuery('.' + step).find('input[name="numero_compte' + champs + '"]').val();
                data_form.votre_agence = jQuery('.' + step).find('input[name="votre_agence' + champs + '"]').val();
                var cat = "Vous : ";

                if (!data_form.quelle_personne) {
                    errors.push("A quel titre intervenez-vous ?");
                    jQuery('.bloque_complet').css('border', '1px solid red');
                } else {
                    if (!data_form.raison && data_form.quelle_personne == "Association")
                        errors.push(cat + jQuery('.' + step).find('input[name="raison"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!data_form.nom && data_form.quelle_personne != "Association")
                        errors.push(cat + jQuery('.' + step).find('input[name="nom' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!data_form.prenom && data_form.quelle_personne != "Association")
                        errors.push(cat + jQuery('.' + step).find('input[name="prenom' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!data_form.adresse)
                        errors.push(cat + jQuery('.' + step).find('input[name="adresse' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!data_form.codepostal)
                        errors.push(cat + jQuery('.' + step).find('input[name="codepostal' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!data_form.ville)
                        errors.push(cat + jQuery('.' + step).find('input[name="ville' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!data_form.email || !/^([\w\.-]+@[\w\.-]+\.\w+)$/i.test(data_form.email))
                        errors.push(cat + jQuery('.' + step).find('input[name="email' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                    if (!jQuery('.autre').is(':visible')) {
                        if (!data_form.numero_compte)
                            errors.push(cat + jQuery('.' + step).find('input[name="numero_compte' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));
                    } else {
                        champs++;
                        data_form.civilite2 = jQuery('.' + step).find('input[name="civilite' + champs + '"]:checked').val();
                        data_form.nom2 = jQuery('.' + step).find('input[name="nom' + champs + '"]').val();
                        data_form.prenom2 = jQuery('.' + step).find('input[name="prenom' + champs + '"]').val();
                        data_form.ville2 = jQuery('.' + step).find('input[name="ville' + champs + '"]').val();
                        data_form.email2 = jQuery('.' + step).find('input[name="email' + champs + '"]').val();
                        data_form.adresse2 = jQuery('.' + step).find('input[name="adresse' + champs + '"]').val();
                        data_form.codepostal2 = jQuery('.' + step).find('input[name="codepostal' + champs + '"]').val();
                        data_form.pays2 = jQuery('.' + step).find('input[name="pays' + champs + '"]').val();
                        data_form.tel2 = jQuery('.' + step).find('input[name="tel' + champs + '"]').val();
                        data_form.numero_compte2 = jQuery('.' + step).find('input[name="numero_compte' + champs + '"]').val();
                        data_form.votre_agence2 = jQuery('.' + step).find('input[name="votre_agence' + champs + '"]').val();
                        var cat = "Pour qui vous intervenez : ";

                        if (!data_form.nom2 && data_form.quelle_personne != "Association")
                            errors.push(cat + jQuery('.' + step).find('input[name="nom' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        if (!data_form.prenom2 && data_form.quelle_personne != "Association")
                            errors.push(cat + jQuery('.' + step).find('input[name="prenom' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        if (!data_form.adresse2)
                            errors.push(cat + jQuery('.' + step).find('input[name="adresse' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        if (!data_form.codepostal2)
                            errors.push(cat + jQuery('.' + step).find('input[name="codepostal' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        if (!data_form.ville2)
                            errors.push(cat + jQuery('.' + step).find('input[name="ville' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        if (!data_form.email2 || !/^([\w\.-]+@[\w\.-]+\.\w+)$/i.test(data_form.email2))
                            errors.push(cat + jQuery('.' + step).find('input[name="email' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        if (!data_form.numero_compte2)
                            errors.push(cat + jQuery('.' + step).find('input[name="numero_compte' + champs + '"]').parents('label').text().replace(/\*\s*/i, ''));

                        var required_files = jQuery('.' + step).find('input[name="quelle_personne"][data-pouvoir="1"]:checked').length;
                        var required_files2 = jQuery('.' + step).find('input[name="quelle_personne"][data-pouvoir="2"]:checked').length;
                        if ((required_files > 0 || required_files2 > 0)) {
                            if (!jQuery('input[name="pouvoir_upload[0]"]').val()) {
                                jQuery('input[name="pouvoir_upload[0]"]').parent().css({ 'border': '2px solid red' });
                                jQuery('input[name="pouvoir_upload[0]"]').parent().find('.isFileOk').val('0');
                                alert("Pour continuer, veuillez joindre le mandat qui vous a été remis.");
                                jQuery('input[name="pouvoir_upload[0]"]').focus();
                                return false;
                            }
                        } else {
                            jQuery('input[name^="pouvoir_upload["]').each(function () {
                                var c = jQuery(this);
                                var cp = c.parent();
                                if (c.val())
                                    return false;
                                cp.find('.isFileOk').val('1');
                                cp.find('.fziseHidden').val('0');
                                cp.find('.fcrc32Hidden').val('');
                            });
                        }
                    }
                }

                if (errors.length > 0) {
                    var errorHTML = new Array();

                    for (var i in errors)
                        errorHTML.push('Valeur du champ "' + errors[i] + '" incorrecte.');

                    jQuery('.step2 .errors').html('<div tabindex="0" style="color: red; margin-bottom: 20px; font-size: 0.95em;">' + errorHTML.join('<br />') + '</div>');
                    jQuery('.step2 .errors div').focus();
                    return false;
                }

                break;
            case 'step3':
                data_form.theme_principale = jQuery('.' + step).find('option:selected').val();

                if (data_form.theme_principale == "0") {
                    jQuery('.' + step).find('.erreur1').show(500);
                    return false;
                }

                data_form.texte_raison = jQuery('.' + step).find('textarea').val();
                if (data_form.texte_raison == '' || !data_form.texte_raison || data_form.texte_raison == 'Saisissez votre texte...') {
                    jQuery('.' + step).find('.erreur2').show(500);
                    return false;
                }

                break;
            case 'step4':
                data_form.valeur = jQuery('.' + step).find('input[type="radio"]:checked').val();
                data_form.texte_estimation = jQuery('.' + step).find('textarea').val();

                break;
            case 'step5':
                var error = false,
                    isFileOk = jQuery('.step5').find('.isFileOk');
                isFileOk.each(function () {
                    if (jQuery(this).val() != '1')
                        error = true;
                });

                if (error) {
                    alert("Les fichiers entourés de rouge dépassent la taille de fichier demandés ou ne sont pas dans un format autorisé.");
                    return false;
                }

                break;
            case 'step6':
                if (e.target.name == 'save_bdd') {
                    if ((jQuery('input[name="dshghdsg[sdsgiu]"]').length && !jQuery('input[name="dshghdsg[sdsgiu]"]').val())) {
                        jQuery('.' + step).find('.erreur').show(500);
                        jQuery('.' + step).find('input[name="dshghdsg[sdsgiu]"]').focus();
                        return false;
                    }
                }

                // pre-submit callback
                function showRequest(formData, jqForm, options) {
                    jQuery('input[name="save_bdd"]:submit').attr('disabled', true);
                    formulaire.etape_suivante(jQuery('.panel.step6 .etape'));
                    jQuery.param(formData);
                    return true;
                }

                // post-submit callback
                function showResponse(responseText, statusText, xhr, $form) {
                    var r = responseText;

                    if (r.errorno > 0) {
                        jQuery('#sdsgiu').attr('src', '/captcha-image.php?' + new Date().getTime());
                        jQuery('input[name="dshghdsg[sdsgiu]"]').val('');
                        jQuery('input[name="save_bdd"]:submit').removeAttr('disabled');
                        jQuery('.panel').hide();
                        jQuery('.stepError').show();
                        jQuery('.stepError .champs_question').html(r.errormsg.join('<br>'));
                        jQuery('.stepError .cValide').hide();
                        if (r.errorno == 1) {
                            jQuery('.stepError .cValide').show();
                        }
                        if (r.errormsg.length < 2)
                            jQuery('.stepError .champs_question').append('<br><br><strong style="color: red">Suite à cette erreur, votre demande n\'a pas été enregistrée.</strong>');
                        else
                            jQuery('.stepError .champs_question').append('<br><br><strong style="color: red">Suite à ces erreurs, votre demande n\'a pas été enregistrée.</strong>');
                    } else {
                        formulaire.etape_suivante(jQuery('.panel.step7 .etape'));
                    }
                }

                var options = {
                    beforeSubmit: showRequest,
                    success: showResponse
                };
                jQuery('#commentForm').off('submit').submit(function () {
                    jQuery(this).ajaxSubmit(options);
                    return false;
                });

                break;
        }

        return true;
    },
    etape_suivante: function (element) {
        var panel = element.parents('.panel');
        var classList = panel.attr('class').split(/\s+/);
        jQuery('.' + classList).hide();
        /([0-9]+)/.exec(classList);
        var nb = RegExp.$1;
        var nouvelle_etape = parseInt(nb) + 1;

        jQuery('.step' + nouvelle_etape).show();
        jQuery('.step' + nouvelle_etape + ' .etape img').focus();
    },
    etape_precedente: function (element) {
        var panel = element.parents('.panel');
        if (panel.hasClass('stepError')) {
            panel.hide();
            var classList = panel.find('input[name="etape_retour"]').val();
            /([0-9]+)/.exec(classList);
            var nb = RegExp.$1;
            var nouvelle_etape = parseInt(nb);
        } else {
            var classList = panel.attr('class').split(/\s+/);
            jQuery('.' + classList).hide();
            /([0-9]+)/.exec(classList);
            var nb = RegExp.$1;
            var nouvelle_etape = Math.max(parseInt(nb) - 1, 1);
        }

        jQuery('.step' + nouvelle_etape).show();
        jQuery('.step' + nouvelle_etape + ' .etape img').focus();
        if (nouvelle_etape == '1')
            jQuery('.cnil').hide();
    },
    etape_actuelle: function (element) {
        var panel = element.parents('.panel');
        var classList = panel.attr('class').split(/\s+/);
        /([0-9]+)/.exec(classList);
        var nb = RegExp.$1;
        var nouvelle_etape = parseInt(nb);

        jQuery('.step' + nouvelle_etape + ' .c1').show();
        jQuery('.step' + nouvelle_etape + ' .c2').hide();
        jQuery('.step' + nouvelle_etape + ' .etape img').focus();
    },
    addField: function (elem) {
        this.fileNumber++;
        var lastfile = jQuery(elem).parents('.block_upload');

        if (lastfile.find('input:file[name^="reclamation_upload["]').length > 4)
            return false;
        else if (lastfile.find('input:file[name^="reponse_upload["]').length > 4)
            return false;
        else if (lastfile.find('input:file[name^="pouvoir_upload["]').length > 4)
            return false;
        else if (lastfile.find('input:file[name^="file_upload["]').length > 6)
            return false;

        button = "<button class='add button_validation2' onclick=\"formulaire.addField(this);\">Ajouter un fichier</button>";
        if (lastfile.find('input:file[name^="reclamation_upload["]').length > 3)
            button = "";
        else if (lastfile.find('input:file[name^="reponse_upload["]').length > 3)
            button = "";
        else if (lastfile.find('input:file[name^="pouvoir_upload["]').length > 3)
            button = "";
        else if (lastfile.find('input:file[name^="file_upload["]').length > 5)
            button = "";

        var fieldName = '';
        if (lastfile.find('input:file[name^="reclamation_upload["]').length)
            fieldName = "reclamation_upload";
        else if (lastfile.find('input:file[name^="reponse_upload["]').length)
            fieldName = "reponse_upload";
        else if (lastfile.find('input:file[name^="pouvoir_upload["]').length)
            fieldName = "pouvoir_upload";
        else if (lastfile.find('input:file[name^="file_upload["]').length)
            fieldName = "file_upload";

        lastfile.find('.add').remove();

        html = "<div class='pupload'><input type='file' name='" + fieldName + "[" + this.fileNumber + "]' onchange='formulaire.updateSize(this);'> <input class='isFileOk' type='hidden' value='1' name='isFileOk[" + this.fileNumber + "]'> <input class='fziseHidden' type='hidden' value='0' name='fzise[" + this.fileNumber + "]'> <input class='fcrc32Hidden' type='hidden' value='' name='fcrc32[" + this.fileNumber + "]'> <button class='re button_validation2' onclick=\"formulaire.removeField(this);\">Enlever ce fichier</button> " + button + " <div class='fzise'>Taille du fichier selectionné : <span class='fileSize'>0</span></div></div>";
        lastfile.append(html);
        return false;
    },
    removeField: function (elem) {
        var block_upload = jQuery(elem).parents('.block_upload');
        jQuery(elem).parents('div.pupload').remove();
        if (block_upload.find('.add').length == 0) {
            html = " <button class='add button_validation2' onclick=\"formulaire.addField(this);\">Ajouter un fichier</button></div>";
            jQuery(html).insertBefore(block_upload.find('> div').last().find('.fzise'));
        }
    },
    limiteur: function (texte, resultat) {
        maximum = 3000;
        champ = jQuery(texte);
        indic = jQuery(resultat);
        if (champ.val().length > maximum) {
            champ.val(champ.val().substring(0, maximum));
        } else {
            var i = (maximum - champ.val().length).toString();
            var pluriel = '';
            if (i > 1)
                pluriel = 's';
            var j = (j = i.length) > 3 ? j % 3 : 0;
            i = i.substr(0, j) + " " + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1 ");
            indic.html(i + ' caractère' + pluriel + ' restant' + pluriel);
        }
    },
    updateSize: function (elem) {
        if (typeof elem.files == 'undefined')
            return false;
        var nBytes = 0,
            error = false,
            oFiles = elem.files,
            nFiles = oFiles.length;
        jQuery(elem).parent().find('.fcrc32Hidden').val('');
        if (!nFiles && !jQuery(elem).is(':required')) {
            jQuery(elem).parent().removeAttr('style');
            jQuery(elem).parent().find('.isFileOk').val('1');
        } else if (!nFiles && jQuery(elem).is(':required')) {
            error = true;
            jQuery(elem).parent().css({ 'border': '2px solid red' });
            jQuery(elem).parent().find('.isFileOk').val('0');
        }
        for (var nFileId = 0; nFileId < nFiles; nFileId++) {
            jQuery(elem).parent().removeAttr('style');
            jQuery(elem).parent().find('.isFileOk').val('1');
            if (!formulaire.inArray(oFiles[nFileId].type, this.filetypes)) {
                error = true;
                jQuery(elem).parent().css({ 'border': '2px solid red' });
                jQuery(elem).parent().find('.isFileOk').val('0');
            }
            if (oFiles[nFileId].size > this.filesize) {
                error = true;
                jQuery(elem).parent().css({ 'border': '2px solid red' });
                jQuery(elem).parent().find('.isFileOk').val('0');
            }

            if (!error) {
                formulaire.fileHash(oFiles[nFileId], function (hash) {
                    var duplicated = false;
                    jQuery('.fcrc32Hidden').each(function () {
                        if (jQuery(this).val() == hash)
                            duplicated = true;
                    });

                    if (duplicated) {
                        alert('Vous avez déjà ajouté ce fichier dans la liste des fichiers joints au formulaire.');
                        jQuery(elem).val('');
                        jQuery(elem).parent().find('.fziseHidden').val('0');
                        jQuery(elem).parent().find('.fileSize').text('0');
                        return;
                    }

                    jQuery(elem).parent().find('.fcrc32Hidden').val(hash);
                });
            }

            nBytes += oFiles[nFileId].size;
        }
        var sOutput = nBytes + " bytes";
        // optional code for multiples approximation
        for (var aMultiples = ["Ko", "Mo", "Go"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
            sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple];
        }
        // end of optional code
        jQuery(elem).parent().find('.fziseHidden').val(nBytes);
        jQuery(elem).parent().find('.fileSize').text(sOutput);

        if (error)
            alert("Les fichiers entourés de rouge dépassent la taille de fichier demandés ou ne sont pas dans un format autorisé.");
    },
    fileHash(file, callback) {
        let reader = new FileReader();
        let start;
        reader.onerror = function (e) {
            console.error("fileHash", e.target.error);
        };
        reader.onload = function (e) {
            callback(CRC32.bstr(e.target.result));
        };
        reader.readAsBinaryString(file);
    }
}
