/**
 * @file
 * Add some needed functionality to the Advanced Search.
 */
(function($, Drupal, once) {
  'use strict';

  Drupal.behaviors.dropdown_filter_menu_utilities = {
    attach: function (context, settings) {
      //Use Ajax form
      once('send-searchform-onchange', '#views-exposed-form-search-results-page-1', context).forEach(selector => {
        const $input = $(selector);
        $input.change(function (e) {
          if (e.target.name === 's') {
            return;
          }
          $('#views-exposed-form-search-results-page-1 input[type="submit"]:not([name="op"])').click();
        });
      });

      once('send-searchform-onchange', '#views-exposed-form-pasala-search-results-page-1', context).forEach(selector => {
        const $input = $(selector);
        $input.change(function (e) {
          if (e.target.name === 's') {
            return;
          }
          $('#views-exposed-form-pasala-search-results-page-1 input[type="submit"]:not([name="op"])').click();
        });
      });

      //Mobile filter
      once('toggle-filter-button', '.menu-filter-button', context).forEach(selector => {
        const $input = $(selector);
        $input.click(function (e) {
          e.preventDefault();
          $('.menu-mobile-filter').fadeToggle();
        });
      });

      // Toggle Calendar
      once('toggle-calendar', '.input-date', context).forEach(selector => {
        const $input = $(selector);
        $input.click(function (e) {
          $('.icon-arrow-container').css('rotate','180deg');
          if ($(e.target).is('.open')) {
            $('.my-datepicker-search-form').addClass('d-none');
            $(this).removeClass('border-white');
            $('.input-date-text').removeClass('open');
          } else {
            $('.my-datepicker-search-form').removeClass('d-none');
            $(this).addClass('border-white');
            $('.input-date-text').addClass('open');
          }
        });
      });

      // Close Toggle Calendar
      function closeToggleCalendar(selector) {
        $(selector).click(function (e) {
          const $target = $(e.target);
          if (
            !$target.is('.input-date')
            && !$target.is("[class|='ui-datepicker']")
            && !$target.is(".input-date-text")
            )
          {
            $('.my-datepicker-search-form').addClass('d-none');
            $('.input-date-text').removeClass('open');
            $('.input-date').removeClass('border-white');
          }
        });
      }

      if (context.tagName == 'BODY') {
        closeToggleCalendar(context);
      } else {
        once('close-toggle', 'body', context).forEach(selector => {
          closeToggleCalendar(selector);
        });
      }

      // Calendar
      once('datepicker', '.my-datepicker-search-form', context).forEach(selector => {
        const $dateMaxField = $('input[data-drupal-selector="edit-fecha-final"]');
        const $dateMinField = $('input[data-drupal-selector="edit-fecha-inicio"]');
        const $datepicker = $(selector);
        $datepicker.datepicker({
          changeMonth: false,
          changeYear: false,
          minDate: 0,
          numberOfMonths: [1,1],
          yearRange: "c:c+3",
          monthNames: [
            Drupal.t('January',  { context: 'Long month name'}),
            Drupal.t('February', { context: 'Long month name'}),
            Drupal.t('March',  { context: 'Long month name'}),
            Drupal.t('April', { context: 'Long month name'}),
            Drupal.t('May', { context: 'Long month name'}),
            Drupal.t('June', { context: 'Long month name'}),
            Drupal.t('July', { context: 'Long month name'}),
            Drupal.t('August', { context: 'Long month name'}),
            Drupal.t('September', { context: 'Long month name'}),
            Drupal.t('October',  { context: 'Long month name'}),
            Drupal.t('November', { context: 'Long month name'}),
            Drupal.t('December',  { context: 'Long month name'}),
          ],
          dayNamesMin: [
            Drupal.t('Do'),
            Drupal.t('Lu'),
            Drupal.t('Ma'),
            Drupal.t('Mi'),
            Drupal.t('Ju'),
            Drupal.t('Vi'),
            Drupal.t('Sa')
          ],
          firstDay: 1,
          beforeShowDay: function(date) {
            let date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMinField.val());
            let date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMaxField.val());
            let $allSelected = $('.dp-highlight');
            let cssClass = '';

            if (date1 && date.getTime() == date1.getTime()) {
              cssClass += "dp-highlight first-selected";
              if (date2) {
                cssClass += " first-element";
              }
            }
            else if (date2 && date.getTime() == date2.getTime()) {
              cssClass += "dp-highlight last-selected";
            }
            else if (date1 && date2 && date.getTime() > date1.getTime() && date.getTime() < date2.getTime()) {
              cssClass += "dp-highlight";
            }
            let result = [true, cssClass];
            return result;
          },
          onSelect: function(dateText, inst) {
            let date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMinField.val());
            let date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $dateMaxField.val());
            let selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
            if (!$dateMaxField.val() && $dateMinField.val() == dateText) {
              $dateMaxField.val('');
              $dateMinField.val('');
            } else if (!date1 || date2) {
              $dateMinField.val(dateText);
              $dateMaxField.val('');
            }
            else if( selectedDate < date1 ) {
              $dateMaxField.val( $dateMinField.val() );
              $dateMinField.val( dateText );
            } else {
              $dateMaxField.val(dateText);
            }
            let $allSelected = $('.dp-highlight');
            $allSelected
              .removeClass('first-selected')
              .removeClass('last-selected');
            if ($allSelected.length > 0) {
              $allSelected.first().addClass('first-selected');
              $allSelected.last().addClass('last-selected');
              $('#views-exposed-form-search-results-page-1 input[type="submit"]:not([name="op"])').click();
              $('#views-exposed-form-pasala-search-results-page-1 input[type="submit"]:not([name="op"])').click();
            }
          }
        });
      });

      // Tabs close red buttons
      once('remove-filter-tab-btn', '.remove-filter-btn', context).forEach(selector => {
        const $closeBtn = $(selector);
        $closeBtn.click(function () {
          let selected_id = $(this).attr('id')
          switch (selected_id) {
            case 'fecha_inicio':
              $('.form-control[name="fecha_inicio"]').val('');
              $('.form-control[name="fecha_final"]').val('');
              $('.ui-datepicker .dp-highlight').removeClass('dp-highlight')
                .removeClass('first-selected')
                .removeClass('last-selected');
              break;
            case 'ciudades':
              $('select[data-drupal-selector="edit-ciudades"]').val(null).trigger('change');
              break;
            case 'categorias':
              $('select[data-drupal-selector="edit-categorias"]').val(null).trigger('change');
              break;
            case 's':
              $('#edit-s--2, #edit-s--3').val('').trigger('change');
              break;
            default:
              break;
          }
          $('#views-exposed-form-search-results-page-1 input[type="submit"]:not([name="op"])').click();
          $('#views-exposed-form-pasala-search-results-page-1 input[type="submit"]:not([name="op"])').click();
        });
      });
    }
  };

})(jQuery, Drupal, once);