var table = null;
$( document ).ready(function() {
    setCheckBoxClicker();
    $('.radioClicker').on('click', function() {
        $(this).find('input[type="radio"]').prop( "checked", true );
    });
    $('.popover-tooltip').popover({
        trigger:'hover',
    });
    //Gestion des inputs
    $('.js-form-input').formInput();
    $('.js-form-select').formSelect({
        textClass: 'form-select__text'
    });
    //Gestion des DatePickers
    $(function () {
        let $datepickers = $(".fake-form-control");
        if($datepickers.length>0){
            $datepickers.datepicker();
            $datepickers.blur(function () {  // Permet de garder le label de l'input en haut après avoir sélectionné la date
                let $block = $(this).parent();
                setTimeout( function () {
                    $block.addClass("active")
                },10);
            })
        }
    })
    // Gestion click dropdown
    // Gestion click dropdown
    $('.dropdown a').on('click', selectinBSSelect);
    $('.pass-visibility-toggle').on('click', function() {
        let $input = $(this).parent().find('input');
        if ($input.attr("type") === "password"){
            $(this).find('.fa').addClass('fa-eye-slash');
            $(this).find('.fa').removeClass('fa-eye');
            $input.attr("type","text");
        }else {
            $(this).find('.fa').addClass('fa-eye');
            $(this).find('.fa').removeClass('fa-eye-slash');
            $input.attr("type","password")
        }
    });
    let doJob = null;
    $('#showWhenScroll').mousedown(function () {
        if(!doJob){
            doJob = setInterval(job, 1);
        }
    });
    function job(){
        $("#openCuvesList").scrollTop(posY*2.5);
    }
    $('[data-target="#openCuvesList"]').on('click', function() {
        let openCuvesList = $('#openCuvesList');
        drawLoader($('body'));
        resetForm(openCuvesList.find('form'));
        let $container =  openCuvesList.find('.CuveEditInfoContainer');
        hideReferenceForm($container);
        validateCustomForm($container);
        validateInputs($container);
        setTimeout(function(){
            openCuvesList.find('fieldset').click();
            openCuvesList.find('input').first().focus();
            hideLoader($('body'));
        },700);
    });
    $(window).mouseup(function () {
        clearInterval(doJob);
        doJob = null;
    });
    let posY = 0;
    $(document).on( "mousemove", function( event ) {
        if(doJob){
            posY = event.pageY;
        }
    });
    setTimeout(function(){
        if(table){
            $(window).resize(function(){
                table.column(0).visible(!!table.$(":hidden").length);
            });
            table.on( 'draw', function () {
                table.column(0).visible(!!$(table.body()[0]).find('td:hidden').length);
            });
        }
    },10);
    $('[isColorPicker]').on('click', function () {
        $("div[style*='clear: both']").css({'z-index':'9999'});
    });
    selectedSearcheableJsValidatorFix();
    $('input[name=default_watch_type]').change(function() {
        let $editCuveCont = $(this).closest(".edit-cuve-fieldset");
        if(parseInt($(this).val()) === 1) {
            $editCuveCont.find('input[name=minLiter]').attr({name: 'maxLiter', dataform: 'maxLiter'});
            $editCuveCont.find('input[name=minLiterEmergency]').attr({name: 'maxLiterEmergency', dataform: 'maxLiterEmergency'});
        } else {
            $editCuveCont.find('input[name=maxLiter]').attr({name: 'minLiter', dataform: 'minLiter'});
            $editCuveCont.find('input[name=maxLiterEmergency]').attr({name: 'minLiterEmergency', dataform: 'minLiterEmergency'});
        }
    });
});
function selectInBoostrapSelect($select, idSelect) {
    let $res = $select.find('li').filter(function() {
        return $(this).attr('value') === idSelect;
    }).first();
    $select.find('button > span').first().html($res.find('a').html());
    $select.find("input:hidden").val($res.attr('value'));
}
function buildError(text) {
    return buildText(text, "alert-danger");
}
function buildWarning(text) {
    return buildText(text, "alert-warning");
}
function buildSuccess(text) {
    return buildText(text, "alert-success");
}
function buildText(text, htmlClass){
    return '
' + text + '
';
}
function appendError($element, text) {
    $element.prepend(buildError(text));
}
function appendWarning($element, text) {
    $element.prepend(buildWarning(text));
}
function appendSuccess($element, text) {
    $element.prepend(buildSuccess(text));
}
function appendMessage($element, text) {
    $element.prepend(buildText(text, "alert-info"));
}
function deleteAppendedMessages(){
    $('.js-generated').remove();
}
function subDays(date_fin, days) {
    let result = new Date(date_fin);
    result.setDate(result.getDate() - days);
    return result;
}
function emptyDataForm($fieldeset) {
    $fieldeset.find('input').val('');
}
function fillOptionDropdownComponent($dropdown, availableValues, selectedValues) {
    if(!selectedValues) {
        selectedValues = [];
    }
    $dropdown = $($dropdown);
    let $ul = $dropdown.find('ul');
    for(let key in availableValues) {
        $ul.append('' +
            '    ' +
            '        
=0 ? 'checked' : '') + '>
' + availableValues[key] + '
' +
            '     
 ')
    }
}
/**
 * Fill search dropdown
 *
 * @param {String} id
 * @param {Object} data
 * @param {Object=} container
 */
function fillSearchDropdown(id, data, container)
{
    if (container) {
        const input = container.find(id);
        const title = container.find(id + ' option:first-child').text();
        input.empty().append('' + title + ' ');
        return fillData(input, data);
    }
    const title = $(id + ' option:first-child')[0].innerText;
    const dropdown = $(id);
    dropdown.empty().append('' + title + ' ');
    return fillData(dropdown, data);
}
function fillData(input, data) {
    if (Array.isArray(data)) {
        for (let i =0; i < data.length; i++) {
            input.append('' + data[i][1].toUpperCase() + ' ')
        }
    } else {
        for (let key in data) {
            input.append('' + data[key].toUpperCase() + ' ');
        }
    }
    input.selectpicker('refresh');
    return true;
}
function preventObjectSorting(data)
{
    // From Object to Array (sortable)
    let result = [];
    for (let key in data) {
        result.push([key, data[key]]);
    }
    // Sort alphabetical order
    result.sort(function (a, b) {
        if (a[1] < b[1]) {
            return -1;
        }
        if (a[1] > b[1]) {
            return 1;
        }
        return 0;
    });
    return result;
}
function fillDropdownOption($dropdown, data) {
    $dropdown = $($dropdown);
    let $ul = $dropdown.find('ul');
    $ul.html('');
    for (let key in data) {
        $ul.append('' + data[key] + ' 
').html( data ).text();
        if($input){
            $input.val(text);
            $input.closest('.form-input').addClass('active');
        }
        if($label) {
            $label.html(text);
        }
        if($input && $input.is("textarea")) {
            $input.val(text);
        }
    } else {
        if($input) {
            if ($input.closest('.selectpicker').length){
                $input.val(data);
                $input.closest('.selectpicker').selectpicker('refresh');
                return;
            }
            if($input.closest('.dropdown').length) {
                let $dropdown = $input.closest('.dropdown');
                let $defaultText = $dropdown.find('[default_text]');
                $defaultText.text($defaultText.attr('default_text'));
                $dropdown.find('.input-tick').remove();
            }
            $input.val("");
            $input.closest('.form-input').removeClass('active');
        }
        if($label) {
            $label.html(variableEditCuves.nonRenseigne);
        }
    }
    if($input && $input.is("[iscolorpicker]")) {
        setTimeout(function() {
            if($input.val() !== '') {
                $input.focus().focusout();
            }
        }, 500);
    }
}
function resetForm($form, $arrayDontReset) {
    $form = $($form);
    $form.find('input').not($arrayDontReset).each(function() {
        handleDataInForm($(this), null, null);
    });
    $form.find('textarea').not($arrayDontReset).each(function() {
        handleDataInForm($(this), null, null);
    });
    $form.find('.input-tick').not($arrayDontReset).remove();
    deleteAppendedMessages();
}
function renderModalDatatable(text, labelArray) {
    return {
        details: {
            display: $.fn.dataTable.Responsive.display.modal( {
                header: function ( row ) {
                    let data = row.data();
                    if(labelArray){
                        for(let i = 0; i < labelArray.length; i++) {
                            text = text.replace('{' + i + '}',data[labelArray[i]]);
                        }
                    }
                    return text;
                }
            } ),
            renderer: myCustomRenderer
        },
    };
}
function myCustomRenderer( api, rowIdx, columns ) {
    let res = '';
    columns.shift();
    for (let key in columns) {
        res +=  '' + columns[key].title + '  : ' + columns[key].data + ' ';
    return res;
}
/**
 * Retrieve GET params in URI
 *
 * @param {string} name
 *
 * @returns {string|boolean}
 */
function getUriParam(name) {
    if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search)) {
        return decodeURIComponent(name[1]);
    }
    return false;
}
/////////////////////////////
//// JS input validation ////
/////////////////////////////
$(document).ready(function() {
    let timer;                  // Timer identifier
    const timerInterval = 1000; // Time in ms, 1 second here
    //When document is ready check pre-filled fields
    $('fieldset .dropdown:visible input[js-validator]').each(function() {
        if(!!$(this).val()){
            validateInput(this, false);
        }
    });
    $('.buttonComponentContainer').on('click', function() {
        checkBeforeSubmitSpecificForm($(this).closest('fieldset'));
    });
    $('.showEditView').on('click', function() {
        let that = this;
        setTimeout(function () {
            $(that).closest('widget').find('input[js-validator]:visible').each(function() {
                if(!!$(this).val()){
                    validateInput(this, false);
                }
            });
            $(that).closest('widget').find('fieldset .dropdown:visible input[js-validator]').each(function() {
                if(!!$(this).val()){
                    validateInput(this, false);
                }
            });
            $(that).closest('widget').find('fieldset .bootstrap-seach-select:visible input[js-validator]').each(function() {
                if(!!$(this).val()){
                    validateInput(this, false);
                }
            });
        },100)
    });
    $('.edit-pro-cuve, edit-pro-cuve-modal').on('show.bs.modal', function () {
        let that = this;
        setTimeout(function () {
            $(that).find('input[js-validator]:visible').each(function() {
                if(!!$(this).val()){
                    validateInput(this, false);
                }
            });
            $(that).find('fieldset .dropdown:visible input[js-validator]').each(function() {
                if(!!$(this).val()){
                    validateInput(this, false);
                }
            });
        },1000)
    });
    $('input[js-validator]:visible').each(function() {
        if($(this).is('[type=radio]') || $(this).is('[type=checkbox]')) {
            if($(this).is(':checked')){
                validateInput(this, true);
            }
        } else if(!!$(this).val().length){
            validateInput(this, true);
        }
    });
    // Check on keyup of input
    const inputsToValidate = $('input[js-validator]');
    inputsToValidate.keyup(function (e) {
        clearTimeout(timer);
        timer = setTimeout(function () {
            validateInput(e.target, false)
        }, timerInterval);
    });
    inputsToValidate.keydown(function () {
        clearTimeout(timer);
    });
    //Check on focusout of input
    inputsToValidate.focusout(function (e) {
        validateInput(e.target, true);
    });
    $('fieldset .bootstrap-seach-select input[js-validator]').change(function() {
        validateInput(this, false);
    });
    //If click on radio or checkbox, force focusout to trigger validation
    $('input[type=checkbox][js-validator], input[type=radio][js-validator]').on('click', function() {
        let that = this;
        setTimeout(function () {
            validateInput(that, true);
        },10);
    });
    $('.back-inscription').on('click', function () {
        setTimeout(function () {
            $('input[js-validator]:visible').each(function() {
                validateInput(this, true);
            });
            $('fieldset .dropdown:visible input[js-validator]').each(function() {
                validateInput(this, true);
            });
        },10);
    });
    //If click on a bootstrap dropdown, force focusout to trigger validation
    $('fieldset .dropdown a').on('click', function () {
        $(this).closest('div').find('input[js-validator]').focusout();
    });
    //If click on a bootstrap dropdown sreach input, force focusout to trigger validation
    $('fieldset .selectpicker').change(function () {
        $(this).closest('div').find('input[js-validator]').change();
    });
    //Allow validation for off becoming on
    $('[js-validator-off]').focusout(function () {
        if($(this).is('[js-validator]') && !$(this).is('[js-validator-off]')) {
            validateInput(this,true);
        }
    });
    //Check all field before submit
    $($('form') ).submit(function () {
        checkBeforeSubmitSpecificForm(this);
    });
    //Check all field before submit if button disabled
    $('button[type=submit]').parent().click(function() {
        checkBeforeSubmitSpecificForm($(this).closest('fieldset'));
    })
    $('button[name=add-contact]').parent().click(function() {
        checkBeforeSubmitSpecificForm($(this).closest('fieldset'));
    })
    $('fieldset span[data-target]').on('click', function() {
        $($($(this).attr('data-target')).find('input[js-validator]').get().reverse()).each(function() {
            validateInput(this,true);
        })
    })
});
function checkBeforeSubmitSpecificForm($form) {
    $form = $($form);
    $form.find('fieldset a').closest('div').find('input[js-validator]').each(function() {
        validateInput(this, true);
    });
    $form.find('.dropdown').closest('div').find('input[js-validator]').each(function() {
        validateInput(this, true);
    });
    $form.find('.bootstrap-seach-select').closest('div').find('input[js-validator]').each(function() {
        validateInput(this, true);
    });
    $($form.find("input[js-validator]:visible, fieldset a ").get().reverse()).each(function() {
        validateInput(this, true);
    });
    $form.find('.switch-tiny:visible > input[js-validator]').each(function() {
        validateInput(this, true);
    })
}
/**
 * Launch validation for all inputs
 */
function validateInputs(container)
{
    if (container) {
        container.find('input[js-validator]').each(function() {
            if(!!$(this).val()){
                validateInput(this, false);
            }
        });
    } else {
        $('input[js-validator]').each(function() {
            if(!!$(this).val()){
                validateInput(this, false);
            }
        });
    }
}
function validateInput(that, showErrorMessage, recursive) {
    if(!$(that).is('[js-validator]')){
        return;
    }
    if(typeof recursive === 'undefined') {
        recursive = true;
    }
    //Definition declaration
    let $this = $(that);
    let $fieldset = $this.closest('fieldset');
    let validate = false;
    let hasValidation = true;
    if(showErrorMessage){
        $this.val($this.val().trim());
    }
    let value = $this.val();
    let errorMessage = mesVariablesGlobales.validationVariables.genericInvalidInput;
    let divToShow;
    //Business rule
    switch ($this.attr('name')) {
        case 'limit_operator':
        case 'variation_operator':
        case 'alert_configuration_type':
        case 'limit_column_alert':
        case 'variation_column_alert':
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            divToShow = $('[name="alert-configuration-error"]');
            break;
        case 'odoo_partner_name':
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0 && $('[name="odoo_partner_id"]').val() !== '';
            divToShow = $('[name="alert-configuration-error"]');
            break
        case 'limit_value_alert':
        case 'variation_value_alert':
        case 'variation_time_alert':
        case 'leave_area_radius':
            validate = value > 0;
            if (value.length === 0){
                errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            }else {
                errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeNeg;
            }
            divToShow = $('[name="alert-configuration-error"]');
            break;
        case "date_operation_start":
            let date = moment(value);
            if(!date.isValid()) {
                date = moment(value, 'DD/MM/YYYY h:mm');
            }
            validate = date.isValid();
            errorMessage = "La date donnée est invalide"
            break;
        case "typeLiquide":
        case "id_role":
            validate = value.length > 0;
            break;
        case "liquide":
        case "taring_bottom":
        case "taring_top":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case "reference":
        case "localisation":
        case "density":
            validate = value.length > 0;
            break;
        case "LiquidCreation":
        case "ApiAccess":
        case "name":
        case "id_article":
        case "ref_cluster":
        case "domicile_device":
        case "client_device":
        case "cluster_type":
        case "animal_number":
        case "animal_type":
        case "SubsidiariesCreation":
        case "UserManagement":
        case "RoleManagement":
        case "contact":
        case "transport_mode":
        case "id_fd_loading_place":
        case 'title':
        case 'clef':
        case 'valeur':
        case 'column_name_dtd':
        case 'label':
        case 'icon':
        case 'color':
        case 'ref_quickbook':
        case 'fonction':
        case 'id_category':
        case 'is_default':
        case 'code_asset':
        case 'event_date':
        case 'advice_date':
        case "content_category" :
        case "maintenance_type_name" :
        case "operation_name" :
        case "contact_name" :
        case "operation_type" :
        case "default_level_permission" :
        case "form_type" :
            validate = value.length > 0;
            break;
        case "id_liquid":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case "quantity":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value > 0;
            break;
        case "date_delivery":
            let dateCharging = $fieldset.find('[name=date_charging]').val();
            if(dateCharging){
                errorMessage = "La date de livraison ne peut être inférieure à la date de chargement";
                validate = moment(value,'DD/MM/YYYY') >= moment(dateCharging,'DD/MM/YYYY');
            }else{
                validate = value.length > 0;
            }
            break;
        case "date_charging":
            let dateDelivery = $fieldset.find('[name=date_delivery]').val();
            if(dateDelivery){
                errorMessage = "La date de chargement ne peut être supérieure à la date de livraison";
                validate = moment(dateDelivery,'DD/MM/YYYY') >= moment(value,'DD/MM/YYYY');
            }else{
                validate = value.length > 0;
            }
            break;
        case "id_role_professionnel":
        case "id_professionnel":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case "desired_date_delivery":
        case "desired_date_delivery_Fin":
        case "longueur_abaque":
        case "largeur_abaque":
        case "type_alert":
        case "date_installation":
        case "date_debut":
        case "period":
        case "callback":
        case "mail_notification":
        case "date_fin":
        case "installation_date":
        case "maintainer_id":
        case "installer_id":
        case "fournisseur_id":
        case "ref_intervention":
        case "hauteur_utile":
        case "id_ref_category":
        case "account_level":
        case "map_marker":
            validate = value !== 'null';
            break;
        case "id_intervenant":
            validate = value !== 'null';
            break;
        case "siret":
            hasValidation = false;
            break;
        case "vtut":
            validate = value >= 0;
            break;
        case "vmut":
            validate = value >= 0;
            break;
        case "hauteur_min_non_vidangeable":
        case "fake_offset":
        case "waater_height":
        case "debit":
        case "position_capteur":
        case "asset_uid":
        case "facility_uid":
            validate = value !== 'null';
            break;
        case "invoicing_month_period":
        case "articles":
        case "payment_mode":
        case "prix":
            validate = !!value && value >= 0;
            break;
        case "function":
            validate = value.length < 250;
            break;
        case "price":
        case "total_qr_codes":
        case "total_models":
            validate = parseInt(value) >= 0;
            break;
        case "preference_invoicing_date":
        case "period_renew":
        case "odoo_partner_id":
        case "diam_surverse":
            validate = !!value;
            break;
        case "default_watch_type":
        case "watch_type":
            validate = [-1,0,1].indexOf(parseInt(value)) !== -1;
            break;
        case "equation_courbe":
            errorMessage = "Format d'équation non respecté. Attendu (sans les coeff): [x.xx^0, x.xx^1, x.xx^2, x.xx^3, x.xx^4, x.xx^5, x.xx^6] ";
            validate = RegExp("^\[-{0,1}[0-9]+(\.[0-9]+){0,1}\,-{0,1}[0-9]+(\\.[0-9]+){0,1}\,-{0,1}[0-9]+(\\.[0-9]+){0,1}\,-{0,1}[0-9]+(\\.[0-9]+){0,1}\,-{0,1}[0-9]+(\\.[0-9]+){0,1}\,-{0,1}[0-9]+(\\.[0-9]+){0,1}\,-{0,1}[0-9]+(\.[0-9]+){0,1}\\]$").test(value);//^\[(\d+(\.\d+)?,\s?){6}\d+(\.\d+)?\]$
            break;
        case "adresse_existante":
        case "rang_domicile":
            validate = !!value;
            break;
        case "type":
            let success = !!$('input[name=type]:checked').length;
            errorMessage = mesVariablesGlobales.validationVariables.cuveInvalidFormat;
            if(showErrorMessage) {
                renderErrorMessage($('.type-error'), success, errorMessage);
            }
            renderTicks($this, success, $fieldset);
            hasValidation = false;
            break;
        case "adresse-auto":
            setTimeout(function () {
                let success = true;
               if (!verifiedAddress) {
                    $this.closest(".autocomplete-container").find("input[name=adresse], input[name=ville], input[name=pays], input[name=coordonneesLatitude], input[name=coordonneesLongitude]").each(function() {
                        if(!$(this).val().length) {return success = false}
                    });
                }
                if(showErrorMessage) {
                    renderErrorMessage($this, success, mesVariablesGlobales.validationVariables.addressRules);
                }
                renderTicks($this, success, $fieldset);
            },200);
            hasValidation = false;
            break;
        case "largeur":
            divToShow = $('[name="asset-dimension"]');
            if (parseInt($fieldset.find('[name="type"]:checked').first().val()) === 0) {
                validate = $this.length > 0;
                errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
                break;
            }
            else {
                validate = $this.val() > 0;
                errorMessage = "La valeur ne peut être négative ou égale à zéro";
                break;
            }
        case "hauteur":
            errorMessage = "La hauteur doit être un entier";
            validate = !value.includes('.') && !value.includes(',');
            break;
        case "longueur":
            divToShow = $('[name="asset-dimension"]');
            if (parseInt($fieldset.find('[name="type"]:checked').first().val()) === 0) {
                validate = $this.length > 0;
                errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
                break;
            }
            else {
                validate = $this.val()>0;
                errorMessage = "La valeur ne peut être négative ou égale à zéro";
                break;
            }
        case "nb_entries":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "diametre":
            divToShow = $('[name="asset-dimension"]');
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "hauteurCone":
            divToShow = $('[name="asset-dimension"]');
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "diametreMinCone":
            divToShow = $('[name="asset-dimension"]');
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "largeurMinCone":
            divToShow = $('[name="asset-dimension"]');
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "surface":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "volume_total":
            divToShow = $('[name="asset-dimension"]');
            errorMessage = "La valeur ne peut être négative ou égale à zéro";
            validate = !isNaN(parseInt(value)) && value > 0 && !value.includes('.') && !value.includes(',');
            break;
        case "api_level":
        case "user_max":
        case "subsidiaries_max":
        case "devices_max":
        case "module_max":
        case "liquid_max":
        case "inactive_hours_threshold":
        case "offset":
        case "volumeTotal":
        case "token_duration":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeNeg;
            validate = !isNaN(parseInt(value))&& value >= 0;
            break;
        case "offset_bottom":
            validate = !isNaN(parseInt(value));
            break;
        case "CGV":
            errorMessage = mesVariablesGlobales.validationVariables.cocherCgv;
            validate = $this.is(":checked");
            break;
        case "code":
            errorMessage = mesVariablesGlobales.validationVariables.minActivationCodeLength;
            validate = value.length >= mesVariablesGlobales.validationVariables.caMinLength;
            break;
        case 'nom_distributeur':
        case 'company_name':
        case "old_password":
        case "role_name":
        case "nom":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case "marque":
        case "modele":
        case "type_vehicule":
        case "tor1_name":
        case "tor2_name":
        case "tor3_name":
        case "tor4_name":
        case "filename":
        case "filename_edit":
        case "immatriculation":
        case "id_liquide":
        case "id_domicile":
        case "id_ref_engins":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case "nom_cuve":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmptyOrTooLong;
            validate = value.length > 0 && value.length < "100";
            break;
        case "traductionSource":
        case "prenom":
        case "numero_professionnel":
        case "id_professionnels_referent":
        case "id_ref_associated_brand":
        case "id_ref_main_category":
        case "id_odoo_product_template":
        case "id_cuve":
        case "id_ref_reseau":
        case "zone_rcz":
        case "nb_releve_jour":
        case "sentinelle":
        case "version_hard":
        case "poids":
        case "dimension":
        case "description":
        case "sms_text":
        case "id_admin_referent":
        case "id_ref_verticale":
        case "cvc":
        case "holder":
        case "denomination_commerciale":
        case "reference_fabricant":
        case "part_concerned":
        case "comment":
        case "nom_adresse":
        case "langue":
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case "alerte_mail":
        case "mail_invitation":
            errorMessage = mesVariablesGlobales.validationVariables.emailInvalid;
            validate = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            break;
        case "email_envoi_alerte":
            errorMessage = mesVariablesGlobales.validationVariables.emailInvalid;
            validate = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            break;
        case "noreply_mail":
            errorMessage = mesVariablesGlobales.validationVariables.emailInvalid;
            validate = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            break;
        case "id_cuve_reference":
            validate = value.length > 0 && value !== "0";
            break;
        case "id_marque_reference":
            validate = value.length > 0 && value !== "0";
            break;
        case "mail_card":
        case "Mail":
        case "Email":
        case "email_client":
        case "contact_email":
            validate = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            errorMessage = mesVariablesGlobales.validationVariables.emailInvalid;
            break;
        case "mail":
        case "mail-to-update":
        case "mail2":
            isEmailForm = false;
            validate = checkEqualWithPeer($fieldset.find('input[name=mail]'), value, recursive, function(value) {
                return isEmailForm = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            });
            errorMessage = isEmailForm? mesVariablesGlobales.validationVariables.emailDifferent : mesVariablesGlobales.validationVariables.emailInvalid;
            break;
        case "email":
        case "mail_user":
            isEmailForm = false;
            validate = checkEqualWithPeer($fieldset.find('input[name=mail2]'), value, recursive, function(value) {
                return isEmailForm = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            });
            errorMessage = isEmailForm? mesVariablesGlobales.validationVariables.emailDifferent : mesVariablesGlobales.validationVariables.emailInvalid;
            break;
        case "mail_install":
            let isMailValid = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            if(!isMailValid){
                errorMessage = mesVariablesGlobales.validationVariables.emailInvalid;
                break;
            }
            $.ajax({
                url: '/' + getControllerName() + '/checkMailExist',
                type: 'GET',
                data: {
                    'mail': value,
                    'mail2': $fieldset.find('input[name=mail2_install]').val()
                },
                success : function (response) {
                    const data = response.data;
                    if (data.validation) {
                        isEmailForm = false;
                        validate = checkEqualWithPeer($fieldset.find('input[name=mail2]'), value, recursive, function(value) {
                            return isEmailForm = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
                        });
                        errorMessage = isEmailForm? mesVariablesGlobales.validationVariables.emailDifferent : mesVariablesGlobales.validationVariables.emailInvalid;
                        renderErrorMessage($this, validate, mesVariablesGlobales.validationVariables.emailDifferent, divToShow);
                        renderTicks($this, validate, $fieldset);
                    } else {
                        renderErrorMessage($this, false, 'Cet email existe déjà', divToShow);
                        renderTicks($this, false, $fieldset);
                    }
                }
            });
            hasValidation = false;
            break;
        case "mail2_install":
            isEmailForm = false;
            validate = checkEqualWithPeer($fieldset.find('input[name=mail_install]'), value, recursive, function(value) {
                return isEmailForm = RegExp(mesVariablesGlobales.validationVariables.emailRegex).test(String(value).toLowerCase());
            });
            errorMessage = isEmailForm? mesVariablesGlobales.validationVariables.emailDifferent : mesVariablesGlobales.validationVariables.emailInvalid;
            break;
        case "password":
            isSamePass = false;
            validate = checkEqualWithPeer($fieldset.find('input[name=confirmation_password]'), value, recursive, function(value) {
                return isSamePass = (value.length >= mesVariablesGlobales.validationVariables.passMinLength);
            });
            errorMessage = isSamePass? mesVariablesGlobales.validationVariables.mdpDifferent : mesVariablesGlobales.validationVariables.mdpTooShort;
            break;
        case "card_number":
            errorMessage = mesVariablesGlobales.validationVariables.cardInvalid;
            validate = RegExp(mesVariablesGlobales.validationVariables.cardNumberRegex).test(value.replace(/\s/g, ''));
            break;
        case "confirmation_password":
            isSamePass = false;
            validate = checkEqualWithPeer($fieldset.find('input[name=password]'), value, recursive, function(value) {
                return isSamePass = (value.length >= mesVariablesGlobales.validationVariables.passMinLength);
            });
            errorMessage = isSamePass? mesVariablesGlobales.validationVariables.mdpDifferent : mesVariablesGlobales.validationVariables.mdpTooShort;
            break;
        case "telephone":
        case "telephone_user":
        case "contact_phone":
            $.ajax({
                url: "/index/telVerif",
                type: 'GET',
                data:{
                    "langueInput": $fieldset.find('[name="verif_langue"]').val(),
                    "tel" : value,
                },
                success : function(reponse){
                    renderTicks($this, !!reponse.data, $fieldset)
                }
            })
            hasValidation = false;
            break;
        case "sms_from":
            let smsRegex = /^[a-z]{3,10}$/gm;
            errorMessage = '*  MINUSCULE SEULEMENT ! (pas de caractères speciaux / majuscules';
            validate = smsRegex.exec(value);
            break;
        case "code_activation":
            if (value.length <= 4){
                renderTicks($this, false, $fieldset);
                return;
            }
            $.ajax({
                url: '/' + getControllerName() + '/numDeviceOK',
                type: 'POST',
                data: {
                    'numDevice': value
                },
                success: function (response) {
                    if (response["installable"] !== undefined) {
                        renderTicks($this, !!response["installable"], $fieldset)
                    } else {
                        renderTicks($this, false, $fieldset)
                    }
                },
                error: function () {
                    renderTicks($this, false, $fieldset);
                }
            });
            hasValidation = false;
            break;
        case "id_cuve_maintenance" :
            validate = value > 0;
            break;
        case "config":
        case "form_inputs":
            let jsonValid = true;
            try {
                JSON.parse(value);
            } catch {
                jsonValid = false;
            }
            validate = jsonValid;
            break;
        case 'purchase_price':
            errorMessage = 'must be a float';
            validate = !isNaN(value);
            break ;
        case 'old_password_v2':
            errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
            validate = value.length > 0;
            break;
        case 'new_password_v2':
            const regex = /^\S*(?=\S{12,})(?=\S*[A-Z])(?=\S*\d)(?=\S*[\W])\S*$/;
            errorMessage = mesVariablesGlobales.validationVariables.newRulesPassword;
            validate = regex.test(value);
            break;
        case 'confirmation_password_v2':
            isSamePass = false;
            validate = checkEqualWithPeer($fieldset.find('input[name=new_password_v2]'), value, recursive, function(valueNewPassword) {
                return isSamePass = (valueNewPassword === value);
            });
            errorMessage = isSamePass ? mesVariablesGlobales.validationVariables.mdpDifferent : mesVariablesGlobales.validationVariables.mdpTooShort;
            break;
        default:
            if ($this.hasClass("default-validation")){
                errorMessage = mesVariablesGlobales.validationVariables.valueCannotBeEmpty;
                validate = value.length > 0;
                break;
            }
            hasValidation = false;
            break;
    }
    //Display handler
    if(hasValidation) {
        if(showErrorMessage) {
            renderErrorMessage($this, validate, errorMessage,divToShow);
        }
        renderTicks($this, validate, $fieldset);
    }
}
function showInputError($input, text,$div) {
    deleteAppendedMessages();
    $(buildError(text)).insertBefore($div ? $div : $input.parent());
}
function renderErrorMessage($this, validate, errorMessage,$div) {
    if(!$div){
        $div = $this.parent();
    }
    validate? $div.prev().filter('.js-generated').remove() : showInputError($this,errorMessage,$div);
}
function renderTicks($this, validate, $fieldset) {
    if(validate) {
        $this.parent().prev().filter('.js-generated').remove()
    }
    $this.parent().find('.input-tick').remove();
    let $toAdd = $('
');
    if(validate) {
        $toAdd.addClass('tick-ok fa fa-check color_success');
    } else {
        $toAdd.addClass('tick-ko fa fa-times color_danger');
    }
    if($this.is('[type=checkbox]')) {
        $toAdd.hide();
    }
    if($this.is('[type=radio]')) {
        $toAdd.hide();
        let name = $this.attr('name');
        let $allRadios = $fieldset.find('[name=' + name + ']');
        $allRadios.parent().find('.input-tick').remove();
        $allRadios.parent().append($toAdd.clone());
        $this.parent().find('.input-tick').remove();
    }
    if($this.is('.datepicker')) {
        $toAdd.css({'line-height':'34px'});
    }
    if($this.parent().is('.dropdown')){
        $toAdd.addClass('dropdown-tick');
    }
    if($this.parent().is('.bootstrap-seach-select')){
        $toAdd.css({'top': '-6px', 'right': '33px' ,'border': 'none', 'background-color': 'transparent'});
    }
    $this.parent().append($toAdd.clone());
    let nbFieldsToCheck = $fieldset.find('[js-validator]').length;
    let nbFieldsOk = $fieldset.find('[js-validator]').parent().find('.fa-check').length;
    if(nbFieldsToCheck !== nbFieldsOk) {
        if(!!$fieldset.find('[ButtonComponent][type=submit]').length) {
            disableBtn($fieldset.find('[ButtonComponent][type=submit]'));
        } else {
            $fieldset.find('button[type=submit]').attr("disabled", true);
            $fieldset.find('button[name=add-contact]').attr("disabled", true);
        }
    } else {
        if(!!$fieldset.find('[ButtonComponent][type=submit]').length) {
            enableBtn($fieldset.find('[ButtonComponent][type=submit]'));
        } else {
            $fieldset.find('button[type=submit]').attr("disabled", false);
            $fieldset.find('button[name=add-contact]').attr("disabled", false);
        }
    }
}
function checkEqualWithPeer($item, value, recursive, customcheck) {
    let validate = true;
    if(!!$item.length) {
        if(!!$item.val().length) {
            validate = value === $item.val();
            if(recursive) {
                validateInput($item.get(0), false, false);
            }
        }
    }
    return (customcheck(value) && validate);
}
function checkboxFactory(label, checked, disabled) {
    return '
';
}
function popoverFactory(title, text, icon) {
    if(!icon) {
        icon = 'fa-info-circle';
    }
    return '
').html(rawText).text();
}
function cTextHtml(rowText) {
    return `${(rowText || rowText === 0) ? rowText : ''}
`;
}
function fillEditForm(that, $selectedModal, data) {
    let $that = $(that);
    let $modal = $($selectedModal);
    resetForm($modal.find('form'));
    if(!data){
        data = $that.closest('table').DataTable().row($that.closest('tr')).data();
    }
    $modal.find('[dataform]').each(function () {
        handleDataInForm($(this),null,null);
    });
    if(data) {
        for(let element in data) {
            let input = null;
            if(!!$modal.find('[dataform=' + element + ']' ).length) {
                input = $modal.find('[dataform=' + element + ']' );
            } else {
                input =$modal.find('[dataform=' + camelize(element) + ']' );
            }
            handleDataInForm(input, null, data[element])
        }
    }
    if($modal.find('.autocomplete-container').length > 0) {
        handleDataInForm($modal.find('[name="adresse-auto"]'), null, cText(data.adresse + ", " + data.ville + ", " + data.pays));
    }
}
function buildForm(that) {
    let $that = $(that);
    let form = {};
    let $dataForm = $that.closest('form').find('[dataForm]');
    $dataForm.each(function(index) {
        let $element = $($dataForm[index]);
        let regex = /[a-zA-Z]+\[\]/gm;
            if (regex.exec($element.attr('dataForm'))) {
                if (typeof form[$element.attr('dataForm')] == "undefined") {
                    form[$element.attr('dataForm')] = [];
                }
                if ($element[0].type === 'checkbox') {
                    form[$element.attr('dataForm')].push($element[0].checked ? '1' : '0');
                }
        } else {
            if ($element[0].type === 'checkbox') {
                form[$element.attr('dataForm')] = $element[0].checked ? '1' : '0';
            }else{
                form[$element.attr('dataForm')] = $element.val();
            }
        }
    });
    return form;
}
/**
 * build new form data from html form
 *
 *
 * @param $form (JQuery form object)
 * @returns {FormData}
 */
function buildFormData($form){
    let formData = new FormData();
    let $dataForm = $form.closest('form').find('input[dataForm]');
    $dataForm.each(function (index,input) {
        let $element = $($dataForm[index]);
        if ($element[0].type === 'checkbox') {
            fillFormDataByCheckboxInput(formData,$element);
        }else if($element[0].type === 'file'){
            fillFormDataByFileInput(formData,$element,input);
        }else if(formData[$element.attr('dataForm')] !== "undefined") {
            fillFormDataByInput(formData,$element);
        }
    });
    return formData;
}
/**
 *
 * fill form data by checkbox input
 *
 * @param formData
 * @param $element
 */
function fillFormDataByCheckboxInput(formData,$element) {
    formData.append($element.attr('dataForm'),$element[0].checked ? '1' : '0');
}
/**
 *
 * fill form data by text/number/email/date input
 *
 * @param formData
 * @param $element
 */
function fillFormDataByInput(formData,$element) {
    formData.append($element.attr('dataForm'),$element.val());
}
/**
 *
 * fill form data by file input
 *
 * @param formData
 * @param $element
 * @param input
 */
function fillFormDataByFileInput(formData,$element,input) {
    if (input.files.length > 1){
        $.each(input.files,function(i, file){
            formData.append($element.attr('dataForm')+'['+i+']',file);
        })
    }else if(input.files.length === 1) {
        formData.append($element.attr('dataForm'),input.files[0]);
    }
}
function buildFieldset(that) {
    let $that = $(that);
    let filedset = {};
    let $dataForm = $that.find('[dataForm]');
    $dataForm.each(function(index) {
        let $element = $($dataForm[index]);
        let regex = /[a-zA-Z]+\[\]/gm;
        if (regex.exec($element.attr('dataForm'))) {
            if (typeof form[$element.attr('dataForm')] == "undefined") {
                filedset[$element.attr('dataForm')] = [];
            }
            else if ($element[0].type === 'checkbox') {
                filedset[$element.attr('dataForm')].push($element.is(':checked'));
            }
        } else {
            if ($element[0].type === 'checkbox') {
                filedset[$element.attr('dataForm')] = $element.is(':checked') ? 1 : 0;
            }else {
                filedset[$element.attr('dataForm')] = $element.val();
            }
        }
    });
    return filedset;
}
function badgeContactFactory(uid, lastname, firstname, isMobileActive, isMailActive, isDoNotDisturbActive, allowEdit){
    let prefixMobile = isMobileActive? 'active' : 'inactive';
    let prefixMail = isMailActive? 'active' : 'inactive';
    let prefixDND = isDoNotDisturbActive? 'active' : 'inactive';
    return '' +
        '';
}
let getUrlParameter = function getUrlParameter(sParam) {
    let sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
};
function makeModalResponsiveOnShow($modal) {
    $modal.on('show.bs.modal', function () {
        $(this).find('.modal-dialog').css({
            width: '95%',
            height:'95%',
            margin:  '1%',
            'overflow-y' : 'auto',
            padding: 0
        });
        $(this).find('.modal-content').css({
            height: 'auto',
            'min-height' : '100%',
        });
    });
}
function getCuveImageURL(typeCuve, isMobile) {
    typeCuve = parseInt(typeCuve);
    isMobile = parseInt(isMobile);
    let suffixe = isMobile? '_roue' : '';
    switch (typeCuve) {
        case 1:
            return "/view/img/cuve_parallelepipedique" + suffixe + ".png";
        case 2:
            return "/view/img/cuve_cylindrique" + suffixe + ".png";
        case 3:
            return "/view/img/cuve_debout" + suffixe + ".png";
        case 4:
            return "/view/img/cuves_spherique" + suffixe + ".png";
        case 5:
            return "/view/img/cuve_ibc_checkbox" + suffixe + ".png";
        default:
            return "/view/img/autre_checkbox.png";
    }
}
function getParams (url) {
    let params = {};
    let parser = document.createElement('a');
    parser.href = url;
    if(parser.href.indexOf('?') < 0 ) {
        return {};
    }
    let query = parser.search.substring(1);
    let vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split('=');
        params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
}
function resetInput($input) {
    handleDataInForm($input, null, null);
    resetValidation($input);
}
function resetValidation($input) {
    let $parent = $input.parent();
    $parent.find('.input-tick').remove();
    if($parent.prev().hasClass('alert-dismissible')) {
        $parent.prev().remove();
    }
}
function addSpinnerLoader($div) {
    $div.html('
');
}
/**
 * Give the used label class according to given date
 *
 * @param {string} date
 *
 * @returns {string}
 */
function getClassDateDelta (date) {
    // No date = no default
    if (date === undefined || date === null || date.length === 0) {
        return 'label-success';
    }
    const today = new Date();
    const dateTochange = new Date(date);
    const diffTime = Math.abs((today.getTime() - dateTochange.getTime())/1000);
    const diffDays = Math.trunc(diffTime / ( 60 * 60 * 24));
    if (diffDays <= 1) {
        return 'label-danger';
    }
    if (diffDays > 1 && diffDays <= 4) {
        return 'label-warning';
    }
    return 'label-success';
}
function getTextDateConnexion(data){
    if (data && data.length > 0) {
        return getTextDateDelta(data);
    }
    return 'Aucune connexion';
}
function getTextDateDelta(date) {
    if (date === undefined || date === null || date.length === 0) {
        return  mesVariablesGlobales.noDefault
    }
    const today = new Date();
    const dateTochange = new Date(date);
    const diffTime = Math.abs((today.getTime() - dateTochange.getTime())/1000);
    const diffDays = Math.trunc(diffTime / ( 60 * 60 * 24));
    if (diffDays > 4) {
        return mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}', diffDays).replace('{1}','s');
    }
    if (diffDays > 2) {
        return mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}', diffDays).replace('{1}','s');
    }
    if (diffDays >= 1) {
        return mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}', diffDays).replace('{1}','s');
    }
    const diffHeure = Math.trunc(diffTime / ( 60 * 60 ));
    if (diffHeure >= 1) {
        return mesVariablesGlobales.dateTrad.il_y_a_heures.replace('{0}', diffHeure).replace('{1}','s');
    }
    const diffMinute = Math.trunc(diffTime / ( 60 ));
    if (diffMinute >= 1) {
        return mesVariablesGlobales.dateTrad.il_y_a_minutes.replace('{0}', diffMinute).replace('{1}','s');
    }
    if (diffTime >= 1) {
        return mesVariablesGlobales.dateTrad.il_y_a_secondes.replace('{0}', Math.floor(diffTime)).replace('{1}','s');
    }
    return  mesVariablesGlobales.noEmission
}
function getDisplayDateDelta(date, chips_display = false, type = 'emission') {
    let text = '';
    if(date) {
        let today = new Date();
        let dateTochange = new Date(date);
        let classDiv ;
        const diffTime = Math.abs((today.getTime() - dateTochange.getTime())/1000);
        const diffDays = Math.trunc(diffTime / ( 60 * 60 * 24));
        const diffHeure = Math.trunc(diffTime / ( 60 * 60 ));
        const diffMinute = Math.trunc(diffTime / 60  );
        if(diffDays>4){ //jour
            text = mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}',diffDays).replace('{1}','s');
            classDiv = 'danger';
        }else if(diffDays>2) {
            text = mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}',diffDays).replace('{1}','s');
            classDiv = 'warning';
        }else if(diffDays>=1) {
            text = mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}',diffDays).replace('{1}',(diffDays <= 1 ? '' : 's'));
            classDiv = 'success';
        }else if(diffHeure>=1) {
            text = mesVariablesGlobales.dateTrad.il_y_a_heures.replace('{0}',diffHeure).replace('{1}',(diffHeure <= 1 ? '' : 's'));
            classDiv = 'success';
        }else if(diffMinute>=1) {
            text = mesVariablesGlobales.dateTrad.il_y_a_minutes.replace('{0}',diffMinute).replace('{1}','s');
            classDiv = 'success'
        }else {
            text = mesVariablesGlobales.dateTrad.il_y_a_secondes.replace('{0}',Math.trunc(diffTime)).replace('{1}','s');
            classDiv = 'success'
        }
        if(chips_display) {
            return `${text} `;
        }
        return `${text} `;
    }
    text = type === 'connexion' ? mesVariablesGlobales.noConnexion : mesVariablesGlobales.noEmission;
    if(chips_display) {
        return ` ${text}  `;
    }
    return `${text} `;
}
function getDisplayDateDeltaDevice(date){
        if(date) {
            let today = new Date();
            let dateTochange = new Date(date);
            let classDiv ;
            let text;
            const diffTime = Math.abs((today.getTime() - dateTochange.getTime())/1000);
            const diffDays = Math.trunc(diffTime / ( 60 * 60 * 24));
            const diffHeure = Math.trunc(diffTime / ( 60 * 60 ));
            const diffMinute = Math.trunc(diffTime / ( 60  ));
            if(diffDays>4){ //jour
                text = mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}',diffDays).replace('{1}','s');
                classDiv = 'label-danger';
            }else if(diffDays>2) {
                text = mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}',diffDays).replace('{1}','s');
                classDiv = 'label-warning';
            }else if(diffDays >=1 ) {
                text = mesVariablesGlobales.dateTrad.il_y_a_jours.replace('{0}',diffDays).replace('{1}','');
                classDiv = 'label-success';
            }else if(diffHeure >= 1) {
                text = mesVariablesGlobales.dateTrad.il_y_a_heures.replace('{0}',diffHeure).replace('{1}',(diffHeure <= 1 ? '' : 's'));
                classDiv = 'label-success';
            }else if(diffMinute >=1 ) {
                text = mesVariablesGlobales.dateTrad.il_y_a_minutes.replace('{0}',diffMinute).replace('{1}','s');
                classDiv = 'label-success'
            }else {
                text = mesVariablesGlobales.dateTrad.il_y_a_secondes.replace('{0}',Math.trunc(diffTime)).replace('{1}','s');
                classDiv = 'label-success'
            }
            $('[data-toggle="tooltip"]').tooltip();
            return ''+text+' ';
        }
        return '' + mesVariablesGlobales.noEmission + ' ';
    }
function debounce(callback, ms) {
    let timer = 0;
    return function () {
        let context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            callback.apply(context, args);
        }, ms || 0);
    }
}
function refreshDtColumnsDisplay(datatable, config) {
    let columns = datatable.settings().init().columns;
    datatable.columns().every(function(index) {
        if(columns && columns[index]) {
            let name = columns[index].name;
            if((name.indexOf('force_display') < 0 || !this.visible()) && config.column_to_show && Array.isArray(config.column_to_show) && config.column_to_show.indexOf(name) < 0) {
                this.visible(false);
            } else {
                this.visible(true);
            }
        }
    });
}
function setCheckBoxClicker() {
    const checkboxClicker = $('.checkboxClicker');
    checkboxClicker.unbind('click');
    checkboxClicker.on('click', function (e) {
        if(!$(e.target).is('input')){
            $(this).find('input').prop( "checked", !$(this).find('input').is(':checked') );
        }
    });
}
function getValuesOfSelectOptionDropdown($selectDropdown) {
    let value = {};
    $selectDropdown.find('input').each(function() {
        value[$(this).attr('name')] = $(this).is(':checked');
    });
    return value;
}
function getShownColumns(datatable) {
    let nameObj = {};
    let columns = datatable.settings().init().columns;
    datatable.columns().every(function(index) {
        if(columns && columns[index] && columns[index].visible !== false) {
            if(columns[index].name.indexOf('force_display') < 0 ) {
                nameObj[columns[index].name] = columns[index].title;
            }
        }
    });
    return nameObj;
}
//-------------------------------
//--- Datatable Button Factory---
//-------------------------------
function detailButtonFactory(path) {
    return '';
}
function fillFormInJSDomicile(form) {
    let $blockEditDomicile = $('#block-edit-domicile');
    $blockEditDomicile.data('id_domicile',form.idDomicile);
    $('#dissociate-edit-domicile').data('id_cuve',form.idCuve);
    $('#siret2-siren-infos-area').hide();
    $.ajax({
        url: '/' + getControllerName() + '/domicile',
        type: 'get',
        data: {
            id_domicile: form.idDomicile
        },
        success : function(resDomicile) {
            let $autocompleteHiddenFields = $blockEditDomicile.find('div[name=hidden-values]');
            let $inputAdresse = $blockEditDomicile.find('input[name=adresse-auto]');
            let $textAdresse = $blockEditDomicile.find('div[name=affichage-adresse]');
            let route = resDomicile.adresse.split(' ');
            route[0] = route[0].replace(resDomicile.numero,'');
            $blockEditDomicile.find('[name=name-domicile]').html(''+(resDomicile.isPrincipale === 1 ? mesVariablesGlobales.domicile_principal:mesVariablesGlobales.domicile_secondaire)+' ');
            $autocompleteHiddenFields.find('input[name=numero]').val(resDomicile.numero);
            $autocompleteHiddenFields.find('input[name=adresse]').val(route.join(' ').trim());
            $autocompleteHiddenFields.find('input[name=ville]').val(cText(resDomicile.ville));
            $autocompleteHiddenFields.find('input[name=pays]').val(cText(resDomicile.pays));
            $autocompleteHiddenFields.find('input[name=code_postal]').val(resDomicile.codePostal !== undefined ? resDomicile.codePostal : resDomicile.code_postal);
            $autocompleteHiddenFields.find('input[name=coordonneesLatitude]').val(resDomicile.coordonneesLatitude);
            $autocompleteHiddenFields.find('input[name=coordonneesLongitude]').val(resDomicile.coordonneesLongitude);
            handleDataInForm($blockEditDomicile.find('#siret2'),null,resDomicile.siret);
            handleDataInForm($blockEditDomicile.find('input[name="nom_adresse"]'),null,resDomicile.nom_adresse);
            handleDataInForm($blockEditDomicile.find('input[name="code_lieu"]'),null,resDomicile.code_lieu);
            handleDataInForm($blockEditDomicile.find('input[name="siret"]'),null,resDomicile.siret);
            handleDataInForm($blockEditDomicile.find('input[name="adresse2"]'),null,resDomicile.adresse2);
            handleDataInForm($blockEditDomicile.find('input[name="contact_last_name"]'),null,resDomicile.contactLastName);
            handleDataInForm($blockEditDomicile.find('input[name="contact_first_name"]'),null,resDomicile.contactFirstName);
            handleDataInForm($blockEditDomicile.find('input[name="contact_mail"]'),null,resDomicile.contactMail);
            handleDataInForm($blockEditDomicile.find('input[name="contact_phone"]'),null,resDomicile.contactPhone);
            let textArea = document.createElement('textarea');
            textArea.innerHTML = resDomicile.contactNote;
            let decodedString = textArea.value;
            textArea.remove();
            $('textarea[name="contact_note"]').val(decodedString);
            $blockEditDomicile.find('input[name="adresse2"]').trigger('change');
            handleDataInForm(null, $textAdresse, cText(resDomicile.adresse) + ", " + (resDomicile.codePostal !== undefined ? resDomicile.codePostal : resDomicile.code_postal)
                + ", " + cText(resDomicile.ville) + ", " + cText(resDomicile.pays) + " " + (resDomicile.adresse2 ? cText(resDomicile.adresse2) : '') + "  ");
            handleDataInForm($inputAdresse, null, $("
").html(cText(resDomicile.adresse) + " " + (resDomicile.codePostal !== undefined ? resDomicile.codePostal : resDomicile.code_postal)
                + " " + cText(resDomicile.ville) + " " + cText(resDomicile.pays)));
        },
        error : function(resultat, statut, erreur) {
        }
    });
}
function fillFormInJSSilo(form) {
    let $blockEditCuve = $('#block-edit-cuve');
    $blockEditCuve.find('form').data('id_cuve',form.idCuve);
    $.ajax({
        url: '/' + getControllerName() + '/cuve',
        type: 'get',
        data: {
            cuve_id: form.idCuve,
            pro: true
        },
        success : function(resCuve) {
            let $inputNomSilo = $blockEditCuve.find('input[name=nom_cuve]');
            let $textNomSilo = $blockEditCuve.find('u#old-nom-cuve');
            let $selectLocalisation = $('input[name=localisation]');
            let $selectWatchType = $('input[name=default_watch_type]');
            let $selectLiquide = $('input[name=typeLiquide]');
            let $inputOffset = $blockEditCuve.find('input[name=offset]');
            let $textOffset = $blockEditCuve.find('span#offset-value');
            let $selectNumeroPasDeVis = $blockEditCuve.find('input[name=numero_pas_de_vis]');
            let $inputHauteur = $blockEditCuve.find('input[name=hauteur]');
            let $inputLongueur = $blockEditCuve.find('input[name=longueur]');
            let $inputDiametre = $blockEditCuve.find('input[name=diametre]');
            let $inputLargeur = $blockEditCuve.find('input[name=largeur]');
            let $inputHauteurCone = $blockEditCuve.find('input[name=hauteurCone]');
            let $inputLargeurMinCone = $blockEditCuve.find('input[name=largeurMinCone]');
            let $inputDiametreMinCone = $blockEditCuve.find('input[name=diametreMinCone]');
            let $inputVolumeTotal = $blockEditCuve.find('input[name=volumeTotal]');
            let $inputTypeSilo = $blockEditCuve.find('input[name=type]');
            let $inputCodeAsset = $blockEditCuve.find('input[name=code_asset]');
            //Apply treatment
            handleDataInForm($inputNomSilo, $textNomSilo, resCuve.nomCuve);
            handleDataInForm($inputOffset, $textOffset, resCuve.offset / 10);
            handleDataInForm($inputHauteur, null, resCuve.hauteur);
            handleDataInForm($inputVolumeTotal, null, resCuve.volumeTotal);
            handleDataInForm($inputLongueur, null, resCuve.longueur);
            handleDataInForm($inputLargeur, null, resCuve.largeur);
            handleDataInForm($inputTypeSilo, null, resCuve.type);
            handleDataInForm($selectLiquide, null, resCuve.typeLiquide);
            handleDataInForm($selectLocalisation, null, resCuve.localisation);
            handleDataInForm($selectWatchType, null, resCuve.watchType);
            handleDataInForm($selectNumeroPasDeVis, null, resCuve.numeroPasDeVis);
            handleDataInForm($inputDiametre, null, resCuve.longueur);
            handleDataInForm($inputDiametreMinCone, null, resCuve.diametreMinCone);
            handleDataInForm($inputHauteurCone, null, resCuve.hauteurCone);
            handleDataInForm($inputLargeurMinCone, null, resCuve.largeurMinCone);
            handleDataInForm($inputCodeAsset, null, resCuve.codeAsset);
            //Puts the id on all forms
            $blockEditCuve.find('form').data('id_cuve', resCuve.idCuve);
            $blockEditCuve.find('form').val('id_cuve', resCuve.idCuve);
            $blockEditCuve.find('form').data('id_domicile', resCuve.idDomicile);
            typeSilo =  resCuve.type;
            switch (typeSilo) {
                case 10 :
                    showWithConePyr();
                    break;
                case 9 :
                    showWithConeConic();
                    break;
                case 8:
                    showWithoutConeConic();
                    break;
                case 7:
                    showWithoutConePyr();
                    break;
            }
            $blockEditCuve.find('input').each(function () {
                validateInput(this, true);
            });
        },
        error : function() {
            console.error("Error Silo");
        }
    });
}
function fillFormInJSCuve(form) {
    let $blockEditCuve = $('#block-edit-cuve');
    drawLoader($blockEditCuve);
    let $oldMarqueReference = $blockEditCuve.find('input[name=id_marque_reference]').val();
    resetForm($blockEditCuve);
    $blockEditCuve.find('form').data('id_cuve',form.idCuve);
    $.ajax({
        url: '/' + getControllerName() + '/cuve',
        type: 'get',
        data: {
            cuve_id: form.idCuve,
            pro: true
        },
        success : function(resCuve) {
            let $inputNomCuve = $blockEditCuve.find('input[name=nom_cuve]');
            let $textNomCuve = $blockEditCuve.find('u#old-nom-cuve');
            let $textWatchType = $blockEditCuve.find('#watch-type-title');
            let $selectLocalisation = $('input[name=localisation]');
            let $selectWatchType = $('input[name=default_watch_type]');
            let $textNomLocalisation = $blockEditCuve.find('span#nom-localisation-cuve');
            let $selectLiquide = $('input[name=typeLiquide]');
            let $textNomLiquide = $blockEditCuve.find('span#nom-liquide-utilise');
            let $inputOffset = $blockEditCuve.find('input[name=offset]');
            let $textOffset = $blockEditCuve.find('span#offset-value');
            let $inputOffsetBottom = $blockEditCuve.find('input[name=offset_bottom]');
            let $textOffsetBottom = $blockEditCuve.find('span#offset_bottom-value');
            let $selectNumeroPasDeVis = $blockEditCuve.find('input[name=numero_pas_de_vis]');
            let $textNumeroPasDeVis = $blockEditCuve.find('span#numero-pas-de-vis-value');
            let $inputHauteur = $blockEditCuve.find('input[name=hauteur]');
            let $inputLongueur = $blockEditCuve.find('input[name=longueur]');
            let $inputLargeur = $blockEditCuve.find('input[name=largeur]');
            let $inputIsMobile = $blockEditCuve.find('input[name=is_mobile]');
            let $inputVolumeTotal = $blockEditCuve.find('input[name=volumeTotal]');
            let $inputTypeCuve = $blockEditCuve.find('input[name=type]');
            let $selectMarqueReference = $blockEditCuve.find('input[name=id_marque_reference]');
            let $selectCuveReference = $blockEditCuve.find('input[name=id_cuve_reference]');
            let $inputContractNumber = $blockEditCuve.find('input[name=contract_number]');
            let $internalReference = $blockEditCuve.find('input[name=internal_reference]');
            let $vtut = $blockEditCuve.find('input[name=vtut]');
            let $vmut = $blockEditCuve.find('input[name=vmut]');
            $blockEditCuve.find('.media img').attr('src', getCuveImageURL(resCuve.typeCuve, resCuve.isMobile));
            let $containerReference = $blockEditCuve.find('.CuveEditInfoContainer');
            if (!resCuve.idMarqueReference) {
                hideReferenceForm($containerReference);
                validateCustomForm($containerReference);
                handleDataInForm($selectMarqueReference, null, null);
                handleDataInForm($selectCuveReference, null, null);
                handleDataInForm($blockEditCuve.find("input[name=known_brand]"),null,0);
                validateInputs($containerReference);
            } else if (resCuve.idMarqueReference) {
                showReferenceForm($containerReference);
                unvalidateCustomForm($containerReference);
                handleDataInForm($selectMarqueReference, null, resCuve.idMarqueReference);
                if ($oldMarqueReference !== resCuve.idMarqueReference) {
                    fillDropdownCuveReference($selectMarqueReference,$selectCuveReference,resCuve.idCuveReference);
                } else {
                    handleDataInForm($selectCuveReference, null, resCuve.idCuveReference);
                }
                handleDataInForm($blockEditCuve.find("input[name=known_brand]"),null,1);
                validateInputs($containerReference);
            }
            //Apply treatment
            handleDataInForm($inputNomCuve, $textNomCuve, resCuve.nomCuve);
            handleDataInForm($inputOffset, $textOffset, resCuve.offset / 10);
            handleDataInForm($inputOffsetBottom, $textOffsetBottom, resCuve.offset_bottom / 10);
            handleDataInForm($inputHauteur, null, resCuve.hauteur);
            handleDataInForm($inputVolumeTotal, null, resCuve.volumeTotal);
            handleDataInForm($inputLongueur, null, resCuve.longueur);
            handleDataInForm($inputLargeur, null, resCuve.largeur);
            handleDataInForm($inputTypeCuve, null, resCuve.type);
            handleDataInForm($inputIsMobile, null, resCuve.is_mobile);
            handleDataInForm($selectLiquide, null, resCuve.typeLiquide);
            handleDataInForm($selectLocalisation, null, resCuve.localisation);
            handleDataInForm($selectWatchType, null, resCuve.watchType);
            handleDataInForm($selectNumeroPasDeVis, null, resCuve.numeroPasDeVis);
            handleDataInForm($vtut, null, resCuve.volume_total_utile_pourcentage);
            handleDataInForm($vmut, null, resCuve.volume_minimal_utile_pourcentage);
            handleDataInForm($blockEditCuve.find('input[name=max_replenishment_threshold]'), null, resCuve.max_replenishment_threshold);
            handleDataInForm($blockEditCuve.find('input[name=min_replenishment_threshold]'), null, resCuve.min_replenishment_threshold);
            handleDataInForm($inputContractNumber, null, resCuve.contract_number);
            handleDataInForm($internalReference, null, resCuve.internal_reference);
            if  (typeof valueTable !== 'undefined'){
                valueTable.set('volumeTotal', parseInt(resCuve.volumeTotal));
                valueTable.set('hauteur', parseInt(resCuve.hauteur));
                valueTable.set('largeur', parseInt(resCuve.largeur));
                valueTable.set('longueur', parseInt(resCuve.longueur));
            }
            typeCuve = resCuve.type;
            if (resCuve.alertes !== null && (resCuve.alertes && resCuve.alertes.length !== 0)) {
                $('.seuilIntervention').css('display', 'block');
                if (resCuve.watchType === 1) {
                    if ($blockEditCuve.find('input[name=minLiter]').length) {
                        $blockEditCuve.find('input[name=minLiter]').attr({name: 'maxLiter', dataform: 'maxLiter'});
                        $blockEditCuve.find('input[name=minLiterEmergency]').attr({
                            name: 'maxLiterEmergency',
                            dataform: 'maxLiterEmergency'
                        });
                    }
                    let $inputPourcentIntervention = $blockEditCuve.find('input[name=maxLiter]');
                    let $inputPourcentUrgence = $blockEditCuve.find('input[name=maxLiterEmergency]');
                    handleDataInForm($inputPourcentIntervention, null, (resCuve.alertes.maxLiter !== null ? resCuve.alertes.maxLiter : 0));
                    handleDataInForm($inputPourcentUrgence, null, (resCuve.alertes.maxLiterEmergency !== null ? resCuve.alertes.maxLiterEmergency : 0));
                } else {
                    if ($blockEditCuve.find('input[name=maxLiter]').length) {
                        $blockEditCuve.find('input[name=maxLiter]').attr({name: 'minLiter', dataform: 'minLiter'});
                        $blockEditCuve.find('input[name=maxLiterEmergency]').attr({
                            name: 'minLiterEmergency',
                            dataform: 'minLiterEmergency'
                        });
                    }
                    let $inputPourcentIntervention = $blockEditCuve.find('input[name=minLiter]');
                    let $inputPourcentUrgence = $blockEditCuve.find('input[name=minLiterEmergency]');
                    handleDataInForm($inputPourcentIntervention, null, (resCuve.alertes.minLiter !== null ? resCuve.alertes.minLiter : 0));
                    handleDataInForm($inputPourcentUrgence, null, (resCuve.alertes.minLiterEmergency !== null ? resCuve.alertes.minLiterEmergency : 0));
                }
                let $inputJourIntervention = $blockEditCuve.find('input[name=minDay]');
                let $inputJourUrgence = $blockEditCuve.find('input[name=minDayEmergency]');
                handleDataInForm($inputJourIntervention, null, (resCuve.alertes.minDay !== null && resCuve.alertes.minDay !== 0 ? resCuve.alertes.minDay : 7));
                handleDataInForm($inputJourUrgence, null, (resCuve.alertes.minDayEmergency !== null && resCuve.alertes.minDayEmergency !== 0 ? resCuve.alertes.minDayEmergency : 7));
                selectInBoostrapSelect($selectLocalisation, resCuve.idLocalisation ? resCuve.idLocalisation : '');
                $textNomLocalisation.html(resCuve.textLocalisation ? resCuve.textLocalisation : '');
                selectInBoostrapSelect($selectLiquide, resCuve.idLiquide ? resCuve.idLiquide : '');
                $textNomLiquide.html(resCuve.textLiquide ? resCuve.textLiquide : '');
                selectInBoostrapSelect($selectNumeroPasDeVis, resCuve.numeroPasDeVis ? resCuve.numeroPasDeVis : '');
                $textNumeroPasDeVis.html(resCuve.numeroPasDeVis ? resCuve.numeroPasDeVis : '');
                selectInBoostrapSelect($selectWatchType, resCuve.watchType ? resCuve.watchType : '');
                let text = variableEditCuves.nonRenseigne;
                switch (parseInt(resCuve.watchType)) {
                    case -1:
                        text = variableEditCuves.watchDown;
                        break;
                    case 0:
                        text = variableEditCuves.watchBoth;
                        break;
                    case 1:
                        text = variableEditCuves.watchUp;
                        break;
                    default:
                        text = variableEditCuves.nonRenseigne;
                        break;
                }
                $textWatchType.html(text);
                //Puts the id on all forms
                $blockEditCuve.find('form').data('id_cuve', resCuve.idCuve);
                $blockEditCuve.find('form').data('id_domicile', resCuve.idDomicile);
                $blockEditCuve.find('#resume-forme-0').hide();
                $blockEditCuve.find('#resume-forme-1').hide();
                $blockEditCuve.find('#resume-forme-2').hide();
                $blockEditCuve.find('#resume-forme-3').hide();
                $blockEditCuve.find('#resume-forme-4').hide();
                switch (resCuve.type) {
                    case "0":
                        $blockEditCuve.find('#resume-forme-0').show();
                        break;
                    case "1":
                        $blockEditCuve.find('#cub-volume-total-value-resume').html(resCuve.volumeTotal ? resCuve.volumeTotal : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cub-hauteur-value-resume').html(resCuve.hauteurCuve ? resCuve.hauteurCuve : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cub-largeur-value-resume').html(resCuve.largeur ? resCuve.largeur : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cub-longueur-value-resume').html(resCuve.longueur ? resCuve.longueur : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#resume-forme-1').show();
                        break;
                    case "2":
                        $blockEditCuve.find('#cyl-hauteur-largeur-resume').html(resCuve.hauteurCuve ? resCuve.hauteurCuve : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cyl-volume-total-value-resume').html(resCuve.volumeTotal ? resCuve.volumeTotal : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cyl-longueur-resume').html(resCuve.longueur ? resCuve.longueur : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#resume-forme-2').show();
                        break;
                    case "3":
                        $blockEditCuve.find('#cyl-deb-hauteur-largeur-resume').html(resCuve.hauteurCuve ? resCuve.hauteurCuve : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cyl-deb-volume-total-value-resume').html(resCuve.volumeTotal ? resCuve.volumeTotal : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#cyl-deb-longueur-resume').html(resCuve.longueur ? resCuve.longueur : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#resume-forme-3').show();
                        break;
                    case "4":
                        $blockEditCuve.find('#sphere-volume-total-value-resume').html(resCuve.volumeTotal ? resCuve.volumeTotal : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#sphere-resume').html(resCuve.longueur ? resCuve.longueur : variableEditCuves.nonRenseigne);
                        $blockEditCuve.find('#resume-forme-4').show();
                        break;
                }
                $blockEditCuve.find('input').each(function () {
                    validateInput(this, true);
                });
            }
            hideLoader($blockEditCuve);
        },
        error : function() {
            hideLoader($blockEditCuve);
        }
    });
}
function sendFormAsAjaxDomicile(callback, error) {
    let $blockEditDomicile = $('#block-edit-domicile');
    $blockEditDomicile.unbind();
    $blockEditDomicile.submit(function(e) {
        e.preventDefault();
        let $form = $(e.target);
        let formdata = $form.serializeArray();
        let data = {};
        $(formdata).each(function (index, obj) {
            data[obj.name] = obj.value;
        });
        data.id_domicile = $form.data('id_domicile');
        $.ajax({
            url: '/' + getControllerName() + '/editDomicile',
            type: 'PUT',
            data: data,
            success: function (code_html, statut) {
                callback(code_html, statut);
            },
            error: function (resultat, statut, erreur) {
                error(resultat, statut, erreur)
            }
        });
    });
}
function dissociateDomicileAjax(callback, error) {
    let $dissociateEditDomicile = $('#dissociate-edit-domicile');
    $dissociateEditDomicile.unbind();
    $dissociateEditDomicile.submit(function(e) {
        e.preventDefault();
        let $form = $(e.target);
        let formdata = $form.serializeArray();
        let data = {};
        $(formdata).each(function (index, obj) {
            data[obj.name] = obj.value;
        });
        data.id_cuve = $form.data('id_cuve');
        $.ajax({
            url: '/' + getControllerName() + '/dissociateDomicile',
            type: 'PUT',
            data: data,
            success: function (code_html, statut) {
                callback(code_html, statut);
            },
            error: function (resultat, statut, erreur) {
                error(resultat, statut, erreur)
            }
        });
    });
}
function buttonValidateFactory(target, perso, tooltip = '') {
    if(typeof perso === 'undefined') {
        perso = true;
    }
    let tooltipHtml = ``
    if (tooltip !== '') {
        tooltipHtml = `data-toggle="tooltip" data-placement="bottom" title="${tooltip}"`
    }
    return `
';
}
function buttonDeleteFactory(target, perso) {
    if(perso === undefined) {
        perso = true;
    }
    return '
';
}
function durationCountdownFactory(endDate, overText) {
    let years, month, days;
    years = month = days = 0;
    let classe = 'danger';
    let text = '';
    if (endDate) {
        endDate = endDate.replace(/-/g, '/')//Thanks IE ... haha
        let duration = moment.duration(moment(new Date(endDate).getTime()).diff(new Date().getTime()));
        years = duration.years();
        month = duration.months();
        days = duration.days();
    }
    if (years > 0) {
        classe = 'label-color-success';
        text = years + ' ' + "an(s)";
    }
    if (month > 0) {
        classe = month > 1 ? 'label-color-success' : 'label-color-warning';
        text += ' ' + month + ' ' + "mois";
    }
    if (days > 0 && month === 0 && years === 0) {
        classe = 'label-color-warning';
        text += ' ' + days + ' ' + "jour(s)";
    }
    if (days < 0 && month === 0 && years === 0) {
        classe = 'label-color-danger';
        text = overText
    } else {
        text += ' ' + days + ' '  + "jour(s)" + ' ' + "Restant";
    }
    return '' + text + ' ';
}
function editDomicileDt(data, table) {
    $('.editCuveBtn').click();
    $('.infoCuveBtn').hide();
    fillFormInJSDomicile({
        idDomicile: data.idDomicile !== undefined ? data.idDomicile : data.id_domicile,
        idCuve: data.idCuve !== undefined ? data.idCuve : data.id_cuve
    });
    sendFormAsAjaxDomicile(function(resDomicile) {
        deleteAppendedMessages();
        let message = '';
        if(resDomicile.data === 0) {
            message = localVariables.success_message;
        }
        appendSuccess($('.cuveDomContainer'), message);
        table.draw();
        $('#edit-pro-domicile').modal("hide");
    }, function (resultat) {
        deleteAppendedMessages();
        appendError($('.cuveDomContainer'), JSON.parse(resultat.responseText).message);
        table.draw();
        $('#edit-pro-domicile').modal("hide");
    });
    dissociateDomicileAjax(function(resDomicile) {
        deleteAppendedMessages();
        let message = '';
        if(resDomicile.data === 0) {
            message = localVariables.success_message;
        }
        appendSuccess($('.cuveDomContainer'), message);
        table.draw();
        $('#edit-pro-domicile').modal("hide");
    });
}
String.prototype.removeWord = function(searchWord){
    let str = this;
    let n = str.search(searchWord);
    while(str.search(searchWord) > -1){
        n = str.search(searchWord);
        str = str.substring(0, n) + str.substring(n + this.length, str.length);
    }
    return ''+str;
};
function showCellHighlight(tableNoRes,idTable){
    $('#'+idTable+' tbody')
        .on( 'mouseenter', 'td', function () {
            if($(this)[0]['colSpan'] !== 10 && tableNoRes.order().length > 0) {
                let colOrder = tableNoRes.order()[0][0];
                let rowId = tableNoRes.cell(this).index().row;
                $( tableNoRes.cells().nodes())
                    .removeClass('highlight-col')
                    .removeClass('highlight-row');
                $(tableNoRes.column(colOrder).nodes()).addClass('highlight-col');
                $(tableNoRes.row(rowId).nodes()).find('td').addClass('highlight-row');
            }
        })
        .on('mouseleave','td',function () {
            if($(this)[0]['colSpan'] !== 10) {
                if(tableNoRes) {
                    $(tableNoRes.cells().nodes())
                        .removeClass('highlight-col')
                        .removeClass('highlight-row');
                }
            }
        });
}
function selectedSearcheableJsValidatorFix() {
    $('.selectpicker').change(function () {
        let $this = $(this);
        $this.parent().find('input').val($this.val());
    });
}
function launchToast($container, message, type, icon) {
    if (type === undefined) {
        type = 'alert-success';
    }
    if (icon === undefined) {
        icon = 'fa-exclamation-triangle';
    }
    $('.toast').remove();
    $container.append(
        '' +
        '    
' +
        '   
' + message + '
' +
        '
' + text + ' ';
    }
    return '' + mesVariablesGlobales.aucuneDateRenseignee + ' ';
}
function dateToDayTextShow(date){
    if(date) {
        let today = new Date();
        let dateToChange = new Date(date);
        let text;
        const diffTime = (dateToChange.getTime() - today.getTime()) / 1000;
        const diffDays = diffTime / (60 * 60 * 24);
        if(diffDays < 0){
            if (diffDays < -30 ){
                text = mesVariablesGlobales.dateTrad.passe_depuis_mois.replace('{0}',Math.abs(Math.trunc(diffDays / 30)));
            }else if(diffDays > -1){
                text =  mesVariablesGlobales.dateTrad.yesterday;
            }else {
                text = mesVariablesGlobales.dateTrad.passe_depuis_jours.replace('{0}',Math.abs(Math.trunc(diffDays)));
            }
        }else if(diffDays < 7){
            if(diffDays < 1){
                text =  mesVariablesGlobales.dateTrad.today;
            }else{
                text = mesVariablesGlobales.dateTrad.dans_prochains_jours.replace('{0}',Math.trunc(diffDays));
            }
        }else {
            if (diffDays > 365){
                text = mesVariablesGlobales.dateTrad.dans_prochains_ans.replace('{0}',Math.trunc(diffDays / 365));
            }
            if (diffDays > 30 ){
                text = mesVariablesGlobales.dateTrad.dans_prochains_mois.replace('{0}',Math.trunc(diffDays / 30));
            }else {
                text = mesVariablesGlobales.dateTrad.dans_prochains_jours.replace('{0}',Math.trunc(diffDays));
            }
        }
        return ''+text+' ';
    }
    return '' + mesVariablesGlobales.aucuneDateRenseignee + ' ';
}
function getLabelPaymentMode(idPaymentMode) {
    switch (parseInt(idPaymentMode)) {
        case 1 :
            return 'Virement';
        case 2 :
            return 'Prélèvement SEPA';
        case 3 :
            return 'Carte bancaire';
        case 4 :
            return 'Chèque';
        default :
            return 'Inconnu';
    }
}
function getLabelContractPeriod(idContractPeriod) {
    switch (parseInt(idContractPeriod)) {
        case 1 :
            return 'Mensuelle';
        case 3 :
            return 'Trimestrielle';
        case 6 :
            return 'Semestrielle';
        case 12 :
            return 'Annuelle';
        default :
            return 'Inconnu';
    }
}
function showAlert(selectorAlert, typeAlert, message, timeout) {
    $(selectorAlert).append('' + message + '
');
    $('html, body').animate({ scrollTop: $(selectorAlert).offset().top }, 'slow');
    setTimeout(function () {
        $(selectorAlert).empty();
    }, timeout);
}
function parseInitials(lastName, firstName) {
    if (!!lastName && !!firstName) {
        return firstName[0] + lastName[0];
    }
    if (!lastName && !!firstName) {
        return firstName[0] + firstName[1];
    }
    if (!!lastName && !firstName) {
        return lastName[0] + lastName[1];
    }
    return 'AA';
}
function generateDatatableRoundedProfile(idUser, email = '', lastName, firstName, initial, badgeColor, small = true, width, redirection_url = '/adminUser/UserDetail/') {
    if (email === null || email === '') {
        return '';
    }
    const rounded_profile = generateRoundedProfile(email, initial, badgeColor, small, width);
    const name = (lastName || firstName) ? `${lastName} ${firstName}` : email.substring(0, email.indexOf("@"));
    const redirection = idUser ? `${name} ` : `${name} `;
    if(name.length === 0) {
        return '';
    }
    return `
        
            ${rounded_profile}
            ${redirection}
        
`;
}
function generateRoundedProfile(email, initial, badgeColor, small = true, width, tooltip = '') {
    let initials;
    let color;
    let tooltipProperty;
    if(badgeColor) {
        color = lightOrDark(badgeColor);
    }
    if(initial) {
        initials = initial;
    } else {
        initials = email.substring(0, 1);
    }
    if(initials.length === 0) {
        return '';
    }
    let fontSize = 5;
    if(small) {
        fontSize -= 1;
    }
    if(initials.length >= 3) {
        fontSize -= 1;
    }
    fontSize = '.' + fontSize + 'em';
    if (tooltip !== '') {
        tooltipProperty = ` data-toggle="tooltip" data-placement="top" title="${tooltip}" `;
    }
    return '' +
        ``;
}
function getColorFromInitials(text) {
    const number = text.split('')
        .map(char => char.charCodeAt(0))
        .join('');
    return 'hsl(' + (parseInt(number) % 255) + ', 50%, 50%)';
}
function getImageURLAssetGenericModule(typeCuve) {
    let src = "";
    switch (parseInt(typeCuve)) {
        case 0:
            src = "/view/img/autre_checkbox.png";
            break;
        case 1:
            src =  "/view/img/cuve-parallelepipedique_checkbox.png";
            break;
        case 2:
            src =  "/view/img/cuve_cylindrique1_checkbox.png";
            break;
        case 3:
            src =  "/view/img/cuve_debout_checkbox.png";
            break;
        case 4:
            src =  "/view/img/cuves_spherique_checkbox.png";
            break;
        case 5:
            src =  "/view/img/cuve_ibc_checkbox.png";
            break;
    }
    return src;
}
function showReferenceForm($container) {
    $container.find('div.manual-dimensions').slideUp();
    $container.find('div.cuves-marques-references').slideDown();
}
function hideReferenceForm($container) {
    $container.find('div.manual-dimensions').slideDown();
    $container.find('div.cuves-marques-references').slideUp();
}
function validateCustomForm($container) {
    $container.find('[dataform=volumeTotal]').attr('js-validator', true).removeAttr('js-validator-off');
    $container.find('[dataform=hauteur]').attr('js-validator', true).removeAttr('js-validator-off');
    $container.find('[dataform=largeur]').attr('js-validator', true).removeAttr('js-validator-off');
    $container.find('[dataform=longueur]').attr('js-validator', true).removeAttr('js-validator-off');
    $container.find('[name=type]').attr('js-validator', true).removeAttr('js-validator-off');
    $container.find('[dataform=id_marque_reference]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=id_cuve_reference]').attr('js-validator-off', true).removeAttr('js-validator');
}
/**
 * initialize input from DOM
 * @param $form
 * @param inputName
 */
function initializeInputGeneric($form,inputName) {
    let $input = $form.find("[name="+inputName+"]");
    let $parent = $input.parent();
    $input.bind("DOMSubtreeModified", function () {
        if ($input.is(":disabled") !== $(this).is(":disabled")) {
            $(this).val($(this).is(":disabled") ? "" : $(this).attr("value"));
        }
    }).change(function () {
        $(this).attr("value", $(this).val());
    }).on('focus', function () {
        $parent.addClass("focus");
    }).on('blur', function () {
        $parent.removeClass("focus");
        activateControl($input);
    }).focusout(function (e) {
        validateInput(e.target, true);
    }).keyup(function (e) {
        let timer = setTimeout(function () {
            validateInput(e.target, false)
        }, 500);
    });
    if ($input.val()){
        $input.parent().addClass("active");
        validateInput($input, false)
    }
    if ($input.hasClass("datepicker")){
        $input.datetimepicker({
            locale: "fr",
            format: 'YYYY-MM-DD H:m'
        });
    }
}
/**
 *
 * @param $input
 */
function activateControl($input) {
    let value = $input.val();
    if (value == null || value === '') {
        $input.parent().removeClass("active");
    } else {
        $input.parent().addClass("active");
    }
}
function unvalidateCustomForm($container) {
    $container.find('[dataform=volumeTotal]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=hauteur]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=largeur]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=longueur]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[name=type]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=id_marque_reference]').attr('js-validator', true).removeAttr('js-validator-off');
    $container.find('[dataform=id_cuve_reference]').attr('js-validator', true).removeAttr('js-validator-off');
}
function validateCustomFormReference($container) {
    $container.find('[dataform=id_marque_reference]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=id_cuve_reference]').attr('js-validator-off', true).removeAttr('js-validator');
}
function unvalidateCustomFormReference($container) {
    $container.find('[dataform=hauteur]').attr('js-validator-off', true).removeAttr('js-validator').val(1);
    $container.find('[dataform=largeur]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[dataform=longueur]').attr('js-validator-off', true).removeAttr('js-validator');
    $container.find('[name=type]').attr('js-validator-off', true).removeAttr('js-validator');
}
function fillDropdownCuveReference($marqueReference, $cuveReference = null, idCuveReference =null)
{
    let selectedId = $marqueReference.val();
    let $container = $marqueReference.closest('.CuveEditInfoContainer');
    $.ajax({
        url: '/index/cuvesByMarque',
        type: 'POST',
        data: {
            id_marque_reference: selectedId
        },
        success: function (response) {
            if (response.error === false && response.status === 200) {
                let $cuvesDropDown = $container.find('div.cuves-dropdown');
                if (!$cuvesDropDown.is(':visible')) {
                    $cuvesDropDown.show();
                }
                fillSearchDropdown('#id_cuve_reference', response.data, $container);
                $container.find('#id_cuve_reference').attr('js-validator-off', true).removeAttr('js-validator');
                $('.cuves-dropdown > div > div > .input-tick').remove();
                if ($cuveReference && idCuveReference){
                    handleDataInForm($cuveReference, null, idCuveReference);
                }
                validateInputs();
            }
            if (response.error !== false || response.status !== 200) {
                console.error(response.message);
            }
        }
    });
}
/**
 * Show country flag for client language
 *
 * @param {string} country
 *
 * @returns {string}
 */
function getCountryFlagFromLanguage(country){
    switch (country.toLowerCase()){
        case 'fr' :
            return ' tree
function createTreeText(obj, firstLevel = true) { // standalone recursive function
    let li = '';
    let ul;
    if (firstLevel && (typeof obj !== 'object' || obj === null)){
        if (obj === null) {
            return "null";
        }
        if (typeof obj === 'function') {
            // Do not do anything, bug caused by AlertesTableComponent that adds an "insert" key
            return 'null';
        }
        return obj;
    }
    if (typeof obj === 'object' ) {
        //for (let key in Object.keys(obj)) {
        for (let key in obj) {
            if (typeof obj[key] === 'object'){
                li += ' ' + key + createTreeText(obj[key], false) + ' ';
            } else if (typeof obj[key] === 'function'){
                // Do not do anything, bug caused by AlertesTableComponent that adds an "insert" key
            } else {
                li += '' + key + ' : ' + obj[key] + ' ';
            }
        }
    } else if (typeof obj === 'function'){
        // Do not do anything, bug caused by AlertesTableComponent that adds an "insert" key
    } else {
        li += '' + obj + ' ';
    }
    if (li) {
        ul = ''
    }
    return ul || '';
}
function idRoleAdminAsText(idRole) {
    switch (idRole) {
        case 0:
            return 'Master'
            break
        case 1:
            return 'Développeur Soft'
            break
        case 2:
            return 'Développeur Hard'
            break
        case 3:
            return 'Commercial'
            break
        case 4:
            return 'Production'
            break
        case 5:
            return 'Stagiaire'
            break
        case 6:
            return 'Installateur'
            break
        default:
            return 'Unknown'
            break
    }
}