/*
 * Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you require will output into a single css file (app.css in this case)

// UTILISER LES FONT AWESOME POUR L'ICONOGRAPHIE
require('../../public/fontawesome/css/all.min.css');
// CSS DU KOHINOS
require('../css/app.css');
// THEME BOOTSTRAP / BOOTSWATCH + CONFIGURATION GLOBALE (COULEURS, FONTS...)
require('../css/global.scss');

// Need jQuery? Install it with "yarn add jquery", then uncomment to require it.
// require jQuery normally
const $ = require('jquery');

// create global $ and jQuery variables
global.$ = global.jQuery = $;

// JS is equivalent to  the normal "bootstrap" package
// no need to set this to a variable, just require it
// require('popper.js/dist/popper.js');
require('bootstrap');

require('../css/common.css');
// BOOTSTRAP plugins
require('bootstrap-slider')
require('bootstrap-slider/dist/css/bootstrap-slider.min.css')

// @TODO : make boostrap-datepicker works !!
// require('bootstrap-datepicker-webpack')
// require('bootstrap-datepicker-webpack/dist/css/bootstrap-datepicker3.min.css')
// require('../../public/bundles/sonatacore/vendor/moment/min/moment-with-locales.min.js');
// require('../../public/bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js');
// require('../../public/bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css');

// leaftlet : for openstreetmap
require('../leaflet/leaflet.js');
// for flash message notification
require('../js/flash-messages.js');

require('../js/geoloc.js');

require('select2/dist/js/select2.full');
require('select2/dist/js/i18n/fr');

$('#flash-messages').flashNotification('init');

var $collectionHolder;
// setup an "add a groupe presta (marché amap" link
var $addGroupeButton = $('<button type="button" class="btn btn-secondary add_groupe_link"><i class="fa fa-plus-circle" aria-hidden="true"></i> Ajouter AMAP / Marché</button>');
var $newLinkLi = $('<p class="row mx-2"></p>').append($addGroupeButton);
var $addGeolocButton = $('<button type="button" class="btn btn-secondary add_groupe_link"><i class="fa fa-plus-circle" aria-hidden="true"></i> Ajouter une adresse</button>');
var $newLinkLiGeoloc = $('<p class="row mx-2"></p>').append($addGeolocButton);

/* */
function addGroupeForm($collectionHolder, $newLinkLi) {
    // Get the data-prototype explained earlier
    var prototype = $collectionHolder.data('prototype');

    // get the new index
    var index = $collectionHolder.data('index');

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newForm = prototype.replace(/__name__/g, index);

    // increase the index with one for the next item
    $collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a groupe" link li
    var $newFormLi = $('<p class="row mx-2"></p>').append(newForm);
    $newLinkLi.before($newFormLi);

    // add a delete link to the new form
    addGroupeFormDeleteLink($newFormLi);
}

function addGroupeFormDeleteLink($tagFormLi) {
    var $removeFormButton = $('<button type="button" class="col-3 btn btn-warning">Supprimer</button>');
    $tagFormLi.append($removeFormButton);

    $removeFormButton.on('click', function(e) {
        // remove the li for the tag form
        $tagFormLi.remove();
    });
}


/* */
function addGroupeFormGeoloc($collectionHolderGeoloc, $newLinkLiGeoloc) {
    // Get the data-prototype explained earlier
    var prototypeGeoloc = $collectionHolderGeoloc.data('prototype');

    // get the new index
    var indexGeoloc = $collectionHolderGeoloc.find('.form-group').length;

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newFormGeoloc = prototypeGeoloc.replace(/__name__/g, indexGeoloc);

    // increase the index with one for the next item
    $collectionHolderGeoloc.data('index', indexGeoloc + 1);

    // Display the form in the page in an li, before the "Add a groupe" link li
    var $newFormLiGeoloc = $('<p></p>').append(newFormGeoloc);
    $newLinkLiGeoloc.before($newFormLiGeoloc);

    // add a delete link to the new form
    addGroupeFormDeleteLinkGeoloc($newFormLiGeoloc);
}

function addGroupeFormDeleteLinkGeoloc($tagFormLiGeoloc) {
    var $removeFormButtonGeoloc = $('<button type="button" class="btn btn-warning">Supprimer</button>');
    $tagFormLiGeoloc.append($removeFormButtonGeoloc);

    $removeFormButtonGeoloc.on('click', function(e) {
        // remove the li for the tag form
        $tagFormLiGeoloc.remove();
    });
}

function showConfirmTransactionModal(div, form, montant, don, destinataire = null) {
  // Get modal
  var modal = $('#confirmTransactionModal')

  // Get relevant confirmation message div
  var message = modal.find(div)

  // Set data in modal
  message.find('.montant_transaction').text(montant)
  if (parseFloat(don) > 0) {
    message.find('.montant_don').text(don)
  } else {
    message.find('.div_don').html('')
  }
  if (destinataire != null) {
    message.find('.nom_destinataire').text(destinataire)
  }

  // Show modal and relevant confirmation message
  modal.find(div).show()
  modal.modal('show')

  // Bind modal validation button with form submition
  $('#confirmTransactionModal #confirmTransactionButton').off()
  $('#confirmTransactionModal #confirmTransactionButton').on('click', function(e){
    $(this).attr('disabled', true)
    form.submit()
  });
}

$(function() {
	// Get the ul that holds the collection of groupes
	$collectionHolder = $('.groupeprestas');

  $('.select2').select2({
    language: 'fr',
    width: '100%',
  });
  $('.select2adh').select2({
    minimumInputLength: 3,
    language: 'fr',
    width: '100%',
    ajax: {
      delay: 350,
      cache: true,
      url: '/search/adherent',
      dataType: 'json'
    }
  });

	// add a delete link to all of the existing tag form li elements
    $collectionHolder.find('div.form-group').each(function() {
    	$(this).addClass('row mx-2');
        addGroupeFormDeleteLink($(this));
    });

	// add the "add a groupe" anchor and li to the groupes ul
	$collectionHolder.append($newLinkLi);

	// count the current form inputs we have (e.g. 2), use that as the new
	// index when inserting a new item (e.g. 2)
	$collectionHolder.data('index', $collectionHolder.find(':input').length);

	$addGroupeButton.on('click', function(e) {
	    // add a new groupe form (see next code block)
	    addGroupeForm($collectionHolder, $newLinkLi);
	});

	// Get the ul that holds the collection of groupes
	$collectionHolderGeoloc = $('.geolocs');

	// add a delete link to all of the existing tag form li elements
    $collectionHolderGeoloc.find('li').each(function() {
        addGroupeFormDeleteLinkGeoloc($(this));
    });

	// add the "add a groupe" anchor and li to the groupes ul
	$collectionHolderGeoloc.append($newLinkLiGeoloc);

	// count the current form inputs we have (e.g. 2), use that as the new
	// index when inserting a new item (e.g. 2)
	$collectionHolderGeoloc.data('index', $collectionHolderGeoloc.find(':input').length);

	$addGeolocButton.on('click', function(e) {
	    // add a new groupe form (see next code block)
	    addGroupeFormGeoloc($collectionHolderGeoloc, $newLinkLiGeoloc);
	});

	// BOOTSTRAP TOOLTIPS
	$('[data-toggle="tooltip"]').tooltip()

  $("input:text[name='formAchatMonnaieAdherent[don][montant]']").on('input', function() {
    let montant = 0;

    let montantSlider = parseFloat($('input.achatmonnaie-montant-slider').slider().val());
    if (!isNaN(montantSlider)) {
      montant = montantSlider;
    } else {
      montant = parseFloat($('input#formAchatMonnaieAdherent_montant').val());
    }

    let montantDon = parseFloat($("input:text[name='formAchatMonnaieAdherent[don][montant]']").val().replace(",", "."));
    if (isNaN(montantDon)) {
      montantDon = 0;
    }

    var valuetotal = montant + montantDon;
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  $("input:text[name='formAchatMonnaieAConfirmerAdherent[don][montant]']").change(function() {
    var valuetotal = parseFloat($('input.achatmonnaie-montant-slider').slider().val()) + parseFloat($("input:text[name='formAchatMonnaieAConfirmerAdherent[don][montant]']").val().replace(",", "."))
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  $("input:radio[name='formAchatMonnaieAdherent[montantradio]']").change(function() {
    var mySlider = $("input.achatmonnaie-montant-slider").slider();

    // Set slider value like radio when radio changes
  	mySlider.slider('setValue', this.value)

    $("span.achat_monnaie_montant_choisi").text(this.value + ' €')
    if ($("input:text[name='formAchatMonnaieAdherent[don][montant]']").length) {
      var valuetotal = parseFloat(this.value) + parseFloat($("input:text[name='formAchatMonnaieAdherent[don][montant]']").val().replace(",", "."))
    } else {
      var valuetotal = parseFloat(this.value)
    }
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  $("input:radio[name='formAchatMonnaieAConfirmerAdherent[montantradio]']").change(function() {
    var mySlider = $("input.achatmonnaie-montant-slider").slider();

    // Set slider value like radio when radio changes
    mySlider.slider('setValue', this.value)

    $("span.achat_monnaie_montant_choisi").text(this.value + ' €')
    if ($("input:text[name='formAchatMonnaieAConfirmerAdherent[don][montant]']").length) {
      var valuetotal = parseFloat(this.value) + parseFloat($("input:text[name='formAchatMonnaieAConfirmerAdherent[don][montant]']").val().replace(",", "."))
    } else {
      var valuetotal = parseFloat(this.value)
    }
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });

  $("form[name='formAchatMonnaieAdherent'] input.achatmonnaie-montant-slider").slider().on('change', function(event){
      var value = event.value.newValue;

      $("span.achat_monnaie_montant_choisi").text(value + ' €')
      if ($("input:text[name='formAchatMonnaieAdherent[don][montant]']").length) {
        var valuetotal = parseFloat(value) + parseFloat($("input:text[name='formAchatMonnaieAdherent[don][montant]']").val().replace(",", "."))
      } else {
        var valuetotal = parseFloat(value)
      }
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  
  $("form[name='formAchatMonnaieAConfirmerAdherent'] input.achatmonnaie-montant-slider").slider().on('change', function(event){
      var value = event.value.newValue;

      $("span.achat_monnaie_montant_choisi").text(value + ' €')
      if ($("input:text[name='formAchatMonnaieAConfirmerAdherent[don][montant]']").length) {
        var valuetotal = parseFloat(value) + parseFloat($("input:text[name='formAchatMonnaieAConfirmerAdherent[don][montant]']").val().replace(",", "."))
      } else {
        var valuetotal = parseFloat(value)
      }
      $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });

  $("input:text[name='formAchatMonnaiePrestataire[don][montant]']").change(function() {
    var valuetotal = parseFloat($('input.achatmonnaie-montant-slider').slider().val()) + parseFloat($("input:text[name='formAchatMonnaiePrestataire[don][montant]']").val().replace(",", "."))
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  $("input:text[name='formAchatMonnaieAConfirmerPrestataire[don][montant]']").change(function() {
    var valuetotal = parseFloat($('input.achatmonnaie-montant-slider').slider().val()) + parseFloat($("input:text[name='formAchatMonnaieAConfirmerPrestataire[don][montant]']").val().replace(",", "."))
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  $("input:radio[name='formAchatMonnaiePrestataire[montantradio]']").change(function() {
    var mySlider = $("input.achatmonnaie-montant-slider").slider();

    // Set slider value like radio when radio changes
    mySlider.slider('setValue', this.value)

    $("span.achat_monnaie_montant_choisi").text(this.value + ' €')
    if ($("input:text[name='formAchatMonnaiePrestataire[don][montant]']").length) {
      var valuetotal = parseFloat(this.value) + parseFloat($("input:text[name='formAchatMonnaiePrestataire[don][montant]']").val().replace(",", "."))
    } else {
      var valuetotal = parseFloat(this.value)
    }
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  $("input:radio[name='formAchatMonnaieAConfirmerPrestataire[montantradio]']").change(function() {
    var mySlider = $("input.achatmonnaie-montant-slider").slider();

    // Set slider value like radio when radio changes
    mySlider.slider('setValue', this.value)

    $("span.achat_monnaie_montant_choisi").text(this.value + ' €')
    if ($("input:text[name='formAchatMonnaieAConfirmerPrestataire[don][montant]']").length) {
      var valuetotal = parseFloat(this.value) + parseFloat($("input:text[name='formAchatMonnaieAConfirmerPrestataire[don][montant]']").val().replace(",", "."))
    } else {
      var valuetotal = parseFloat(this.value)
    }
    $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });

  $("form[name='formAchatMonnaiePrestataire'] input.achatmonnaie-montant-slider").slider().on('change', function(event){
      var value = event.value.newValue;

      $("span.achat_monnaie_montant_choisi").text(value + ' €')
      if ($("input:text[name='formAchatMonnaiePrestataire[don][montant]']").length) {
        var valuetotal = parseFloat(value) + parseFloat($("input:text[name='formAchatMonnaiePrestataire[don][montant]']").val().replace(",", "."))
      } else {
        var valuetotal = parseFloat(value)
      }
      $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });
  
  $("form[name='formAchatMonnaieAConfirmerPrestataire'] input.achatmonnaie-montant-slider").slider().on('change', function(event){
      var value = event.value.newValue;

      $("span.achat_monnaie_montant_choisi").text(value + ' €')
      if ($("input:text[name='formAchatMonnaieAConfirmerPrestataire[don][montant]']").length) {
        var valuetotal = parseFloat(value) + parseFloat($("input:text[name='formAchatMonnaieAConfirmerPrestataire[don][montant]']").val().replace(",", "."))
      } else {
        var valuetotal = parseFloat(value)
      }
      $("span.achat_monnaie_montant_total").text(valuetotal + ' €')
  });


  $('.transactionSubmit').on('click', function(e){
      // Stop form submition
      e.preventDefault();
      $(this).attr('disabled', true);

      var form = this.closest('form')
      if (form.checkValidity()) {
        // Get destinataire type : presta or adherent
        var destinataire_type = $('#' + form.name + '_destinataireType')[0].value
        if (destinataire_type == 'prestataire') {
          var div = '.confirmTransactionPrestataire'
        } else {
          var div = '.confirmTransactionAdherent'
        }

        // Get destinataire
        var destinataire_select = $('#' + form.name + '_destinataire')[0]
        var destinataire_name = destinataire_select.options[destinataire_select.selectedIndex].text

        // Get montant
        var montant_field = $('#' + form.name + '_montant')[0]
        var montant_value = montant_field.value

        // Get don montant
        var don_value = 0;
        if ($('#' + form.name + '_don_montant').length) {
          var don_field = $('#' + form.name + '_don_montant')[0]
          var don_value = don_field.value
        }

        showConfirmTransactionModal(div, form, montant_value, don_value, destinataire_name)
      } else {
        // Use symfony validation
        form.submit()
      }
  });

  $('.fluxSubmit').on('click', function(e){
      // Stop form submition
      e.preventDefault();
      $(this).attr('disabled', true);

      var form = this.closest('form')
      form.submit()
  });

  $('.cotisationMLCSubmit').on('click', function(e){
      // Stop form submition
      e.preventDefault();
      $(this).attr('disabled', true);

      var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'emlc'
      $('#' + form.name + '_don_moyen')[0].value = 'emlc'

      if (form.checkValidity()) {
        var div = '.confirmCotisation'

        // Get montant
        var montant_field = $('#' + form.name + '_montant')[0]
        var montant_value = montant_field.value
    
        // Get don montant
        var don_value = 0;
        if ($('#' + form.name + '_don_montant').length) {        
          var don_field = $('#' + form.name + '_don_montant')[0]
          var don_value = don_field.value
        }

        showConfirmTransactionModal(div, form, montant_value, don_value)
      } else {
        // Use symfony validation
        form.submit()
      }
  });
  $('.achatCBSubmit').on('click', function(e){
    var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'cb'
      if ($('#' + form.name + '_don_moyen').length) {
        $('#' + form.name + '_don_moyen')[0].value = 'cb'
      }
  });
  $('.achatHelloAssoSubmit').on('click', function(e){
      var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'helloasso'
      if ($('#' + form.name + '_don_moyen').length) {
        $('#' + form.name + '_don_moyen')[0].value = 'helloasso'
      }
  });
  $('.cotisationCBSubmit').on('click', function(e){
      var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'cb'
      if ($('#' + form.name + '_don_moyen').length) {
        $('#' + form.name + '_don_moyen')[0].value = 'cb'
      }
  });
  $('.cotisationHelloAssoSubmit').on('click', function(e){
      var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'helloasso'
      if ($('#' + form.name + '_don_moyen').length) {
        $('#' + form.name + '_don_moyen')[0].value = 'helloasso'
      }
  });

  $("input:radio[name='formAchatMonnaieAConfirmerAdherent[moyen]']").change(function() {
    if ($("#demande_achat_text_"+this.value).length) {
      $(".demande_achat_text").hide();
      $("#demande_achat_text_"+this.value).show();
    }
  });

  $("input:radio[name='formAchatMonnaieAConfirmerPrestataire[moyen]']").change(function() {
    if ($("#demande_achat_text_"+this.value).length) {
      $(".demande_achat_text").hide();
      $("#demande_achat_text_"+this.value).show();
    }
  });

  $(".paiementDate").toggle($('#formSolidoumeItem_isRecurrent').is(':checked'));
  $('#formSolidoumeItem_amount').slider();
  $('#formSolidoumeItem_isRecurrent').click(function() {
    $(".paiementDate").toggle(this.checked);
  });

  
  if ($("form[name='formEncaissement']").length > 0) {
    // Reset value on page loading (in case of second try)
    $("#formEncaissement_payment_code").val('');

    // Set payment summary on validation page
    let recap = `${$("#formEncaissement_adherent option:selected").text()}, montant : ${$("#formEncaissement_montant").val()} ${KOH_MLC_NAME_SMALL}`;
    $(".payment-recap").text(recap);

    // If conventionnement mode is active
    if ($(this).find("#formEncaissement_montantPanier").length > 0) {
      $("#formEncaissement_montant").prop("disabled",true);

      let maxAmount = 0;

      function disableMontant() {
        $("#formEncaissement_montant").val("");
        $("#formEncaissement_montant").prop("disabled", true);
        $(".presta-conventionnement-applied-text").hide();
      }

      /**
       * If basket amount is set and valid, enable emlc amount field & hide errors if needed.
       * Else display errors.
       */
      function checkMontantPanier() {
        let input = $("#formEncaissement_montantPanier");
        let val = input.val();
        if (val === '') {
          // reset
          $(".montant-panier-error").hide();
          input.removeClass('input-error');

          disableMontant();
        } else {
          let basketAmount = parseFloat(val);

          if (isNaN(basketAmount)) {
            // display error and reset the rest
            $(".montant-panier-error").show();
            input.addClass('input-error');

            disableMontant();
            return;
          }

          $(".montant-panier-error").hide();
          input.removeClass('input-error');

          // no error: enable amount field, set max emlc amount and display helper text
          $("#formEncaissement_montant").prop("disabled", false);
          $(".presta-conventionnement-applied-text").show();
          
          maxAmount = parseFloat(formEncaissementConventionnement) * basketAmount;
          $(".encaissment-emlc-max-amount").text(maxAmount);
        }

        checkMaxAmount();
      }

      checkMontantPanier();
      $("#formEncaissement_montantPanier").on("input", checkMontantPanier);

      /**
       * Check that emlc amount is valid depending on basket amount
       */
      function checkMaxAmount() {
        function reset() {
          $("#formEncaissement_montant").removeClass('input-error');
          $(".encaissment-emlc-max-amount-container").removeClass("text-error");
        }
        
        let val = $("#formEncaissement_montant").val();
        if (val === '') {
          reset();
        } else {
          let amount = parseFloat(val);
          
          if (!isNaN(amount) && amount > maxAmount) {
            $(this).addClass('input-error');
            $(".encaissment-emlc-max-amount-container").addClass("text-error");
          } else if (!isNaN(amount) && amount <= maxAmount) {
            reset();
          }
        }
      }

      checkMaxAmount();
      $("#formEncaissement_montant").on("input", checkMaxAmount);
    }
  }

  /**
   * On cashing payment, validation code screen, add digit to input when corresponding button clicked.
   */
  $(".payment-code-button").off("click");
  $(".payment-code-button").on("click", function() {
    // Get existing input
    let code = $("#formEncaissement_payment_code").val();

    // Add button value
    code += this.dataset.value;
    $("#formEncaissement_payment_code").val(code);

    // Visual payment code representation
    $("#code-visual").text("*".repeat(code.length));
  });

  $(".payment-code-correction-button").off("click");
  $(".payment-code-correction-button").on("click", function() {
    // Get existing input
    let code = $("#formEncaissement_payment_code").val();

    // Remove last char of code
    code = code.slice(0, -1);
    $("#formEncaissement_payment_code").val(code);
    $("#code-visual").text("*".repeat(code.length));
  });

  if ($("form[name='formEncaissement'] #code-digits-container").length > 0)  {
    document.addEventListener('keydown', function (e) {
      if (!isNaN(parseInt(e.key))) {
        $(`form[name='formEncaissement'] button.payment-code-button[data-value="${e.key}"]`)[0].click();
      } else if (e.key === "Backspace") {
        $("form[name='formEncaissement'] .payment-code-correction-button")[0].click();
      } else if (e.key === "Enter") {
        $("form[name='formEncaissement'] #formEncaissement_save")[0].click();
      }
    });
  }

  $("#formEncaisserCotisationAdherent_destinataire").on("change", function() {
    const cotisationMontants = JSON.parse($("#formEncaisserCotisationAdherent_cotisationMontants").val());
    let cotisationmontant = cotisationMontants[this.value];
    console.log(cotisationmontant);

    if (cotisationmontant === undefined) {
      $("#formEncaisserCotisationAdherent-montant-container").hide();
      $("#formEncaisserCotisationAdherent-no-cotisation-amount").hide();
      return;
    }

    if (cotisationmontant !== null) {
      $("#formEncaisserCotisationAdherent-montant-display").text(`${cotisationmontant} €`);
      $("#formEncaisserCotisationAdherent-montant-container").show();
      $("#formEncaisserCotisationAdherent-no-cotisation-amount").hide();

      $("#formEncaisserCotisationAdherent_save").prop("disabled",false);
    } else {
      // no cotisation profile
      $("#formEncaisserCotisationAdherent-montant-container").hide();
      $("#formEncaisserCotisationAdherent-no-cotisation-amount").show();

      $("#formEncaisserCotisationAdherent_save").prop("disabled",true);
    }
  });

  $("#show-login-password-icon").on("click", () => {
    let type = $("#login-password-container #password").prop("type");

    if (type === "password") {
      $("#login-password-container #password").prop("type", "input");
      $("#login-password-container #show-login-text").text("Masquer le mot de passe");
      $("#login-password-container #show-login-password-icon").removeClass("fa-eye").addClass("fa-eye-slash");
    } else {
      $("#login-password-container #password").prop("type", "password");
      $("#login-password-container #show-login-text").text("Afficher le mot de passe");
      $("#login-password-container #show-login-password-icon").removeClass("fa-eye-slash").addClass("fa-eye");
    }
  });

  /**
   * Display loader after validating Encaissement form
   */
  $("form[name='formEncaissement']").on("submit", () => {
    // non strict equality check
    if (formEncaissementValidation == true) {
      $("#formEncaissement_save").parent().append('<span class="spinner-border" role="status" aria-hidden="true"></span>');
      $("#formEncaissement_save").hide()
    }
  })

  $("#display-balance-button-no").on("click", () => {
    $("#display-balance-text-container").hide();
  })

  // $('.js-datepicker').datepicker({
  //     closeText: 'Fermer',
  //     prevText: '&#x3c;Préc',
  //     nextText: 'Suiv&#x3e;',
  //     currentText: 'Aujourd\'hui',
  //     monthNames: ['Janvier','Fevrier','Mars','Avril','Mai','Juin',
  //     'Juillet','Aout','Septembre','Octobre','Novembre','Decembre'],
  //     monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun',
  //     'Jul','Aou','Sep','Oct','Nov','Dec'],
  //     dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
  //     dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
  //     dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
  //     weekHeader: 'Sm',
  //     dateFormat: 'yy-mm-dd',
  //     format: 'yyyy-mm-dd',
  //     firstDay: 1,
  //     isRTL: false,
  //     showMonthAfterYear: false,
  //     yearSuffix: '',
  //     minDate: 0,
  //     maxDate: '+12M +0D',
  //     numberOfMonths: 2,
  //     showButtonPanel: true
  // });

    /*
     * Improve lisibility when reviewing prestataire questionnaire.
     */
    // Get all radio inputs of prestataire questionnaire forms when on review mode (disabled)
    var radioInputs = document.querySelectorAll(
        'form[name$="SelfEvalPrestaQuiz"] input[type="radio"]:disabled'
    );

    radioInputs.forEach(function(radioInput) {
        if (!radioInput.checked) {
            //get the colored icon
            icon = radioInput.labels[0].querySelector('i');
            var classList = Array.from(icon.classList);
            // Filter out classes starting with "text-"
            var textClasses = classList.filter(function(className) {
                return className.startsWith('text-');
            });
            // Remove all classes starting with "text-"
            textClasses.forEach(function(textClass) {
                icon.classList.remove(textClass);
            });
        }
    });

    // Reset hidden data on prestataire self evaluation quizz, for definitive form submition
    $('#formDistributorSelfEvalPrestaQuiz_submit_presta_quizz').val('1');

    /**
     * On prestataire self evaluation quizz, remove all required attributes in form on click on the temporary save button.
     * Set form hidden data to not definitively submit the form.
     */
    $("#formDistributorSelfEvalPrestaQuiz_temporary_save").on("click", (e) => {
      e.preventDefault();

      $('form[name="formDistributorSelfEvalPrestaQuiz"] input').removeAttr('required');
      $('#formDistributorSelfEvalPrestaQuiz_submit_presta_quizz').val('0');
      
      $('form[name="formDistributorSelfEvalPrestaQuiz"]').trigger("submit");
    });

    /**
     * Delete a PrestataireProductFamily node on icon click
     * @param {Event} e 
     */
    function deletePrestataireProductFamily(e) {
      e.preventDefault();
      $(this).closest('.presta-products-family')
          .fadeOut()
          .remove();
    }
    $(".presta-products-family-delete").on("click", deletePrestataireProductFamily);

    /**
     * Check if a product family is already selected on select change.
     */
    function onPrestataireProductFamilyChange() {
      let current_select_id = $(this).attr('id');
      let current_select_selected_option = $( `#${current_select_id} option:selected` ).text();

      let same_selected_option = false;

      $('.prestataire-product-families-select').each(function() {
        let select_id = $(this).attr('id');
        let select_selected_option = $( `#${select_id} option:selected` ).text();

        if (current_select_id !== select_id && current_select_selected_option === select_selected_option) {
          same_selected_option = true;
          return false;
        }
      });

      $('.presta-products-family-fields .presta-products-family-duplicate-warning').hide();
      $('.prestataire-product-families-products').attr('disabled', false);
      
      if (same_selected_option) {
        $(this).closest('.presta-products-family-fields').find('.presta-products-family-duplicate-warning').show();
        $(this).closest('.presta-products-family-fields').find('.prestataire-product-families-products').attr('disabled', true);
      }
    }
    $('.prestataire-product-families-select').on('change', onPrestataireProductFamilyChange);

    /**
     * Twig helper, add element to Collection in template based on collection prototype
     * @param {*} e 
     */
    function addFormToCollection(e) {
      const collectionHolder = document.querySelector('.' + e.currentTarget.dataset.collectionHolderClass);
    
      const item = document.createElement('div');
    
      item.innerHTML = collectionHolder
        .dataset
        .prototype
        .replace(
          /__name__/g,
          collectionHolder.dataset.index
        );
    
      collectionHolder.appendChild(item);
    
      collectionHolder.dataset.index++;

      $(".presta-products-family-delete").off("click", deletePrestataireProductFamily);
      $(".presta-products-family-delete").on("click", deletePrestataireProductFamily);

      $('.prestataire-product-families-select').off('change', onPrestataireProductFamilyChange);
      $('.prestataire-product-families-select').on('change', onPrestataireProductFamilyChange);
    };
    $("#add-prestataire-products-family").on("click", addFormToCollection);

    $("#tav-cotisation-payment-type").on("change", function() {
      $(".tav-cotisation-payment-form").hide();
      if (this.value === "instant-payment") {
        $("#tav-cotisation-instant-payment-container").show();
      } else if (this.value === "recurrent-payment") {
        $("#tav-cotisation-recurrent-payment-container").show();
      }
    });

    $("input:text[name='formAchatMonnaieAdherentRecurrent[don][montant]']").on('input', function() {
      let montant = 0;
      montant = parseFloat($('input#formAchatMonnaieAdherentRecurrent_montant').val());
  
      let montantDon = parseFloat($("input:text[name='formAchatMonnaieAdherentRecurrent[don][montant]']").val().replace(",", "."));
      if (isNaN(montantDon)) {
        montantDon = 0;
      }
  
      var valuetotal = montant + montantDon;
      $("span.achat_monnaie_premier_montant_total").text(valuetotal + ' €')
    });
});
