<script>
//------------------------------------------------------------------------------
// Filter scripts
//------------------------------------------------------------------------------
$(document).ready(function(){
  $('.flt-price').each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
  });
  var divList = $(".filter-container");
  divList.sort(function(a, b){
    return $(a).data("index") - $(b).data("index")
  });
  $("#all-filters-container").html(divList);
});
var flt_settings = {
  toggle: ".toggle-flt-sidebar",
  exit_selector: ".slider-exit",
  animation_duration: "0.5s",
  place: "right",
  animation_curve: "cubic-bezier(0.54, 0.01, 0.57, 1.03)",
  body_slide: true,
  no_scroll: false,
  auto_close: false
};
$('#filter-slider').sliiide(flt_settings);

//region General operations
// Open filter section
$('#all-filters-container').on('click', '.flt-header > .flt-selector', function(){
  var target = $(this).parent('.flt-header').data("target");
  var element = $("#" + target);
  if (element.is(':visible')) {
    $(this).parent('.flt-header').find('.opener').css('background-position', '0px');
    element.slideUp();
  } else {
    $(this).parent('.flt-header').find('.opener').css('background-position', '-26px');
    element.show("slow");
  }
});
function toggleFilters(how) {
  $('.flt-cdtitl').prop("disabled", how);
  $('.flt-cdlinm').prop("disabled", how);
  $('.flt-cdserm').prop("disabled", how);
  $('.flt-generic').prop("disabled", how);
  $('.flt-price').prop("disabled", how);
}
// Reset all filters
$('#reset-all-filters').click(function(){
  $('.flt-cdtitl').each(function(){
    $(this).prop('checked', false);
  });
  $('.flt-cdlinm').each(function(){
    $(this).prop('checked', false);
  });
  $('.flt-cdserm').each(function(){
    $(this).prop('checked', false);
  });
  $('.flt-generic').each(function(){
    $(this).prop('checked', false);
  });
  $('.flt-price').each(function(){
    $(this).val('');
  });
  apply_filters();
});
// Apply filters and load models
function apply_filters() {
  toggleFilters(true);
  $("body").removeClass("loading-done");
  {% if router.getActionName() == "collection" %}
  var url = "{{ url('catalog/loadFiltersCollection') }}";
  {% elseif router.getActionName() == "fabric" %}
  var url = "{{ url('catalog/loadFiltersFabric') }}";
  {% elseif router.getActionName() == "sales" %}
  var url = "{{ url('catalog/loadFiltersSales') }}";
  {% elseif router.getActionName() == "selection" %}
  var url = "{{ url('catalog/loadFiltersSelection/' ~ cdspsl) }}";
  {% elseif router.getActionName() == "tag" %}
  var url = "{{ url('catalog/loadFiltersTag') }}";
  {% else %}
  var url = "{{ url('catalog/setFilters') }}";
  {% endif %}

  var selectedFilters = [];
  $('.filter-container').each(function(){
    var name    = $(this).data('name');
    if (name == 'structure') {
      selectedFilters.push({ 'name': 'titlin', 'context': 'LM', 'type': 0, 'custom': 0, 'filter': get_titlin_filter() });
      selectedFilters.push({ 'name': 'linmod', 'context': 'AN', 'type': 0, 'custom': 0, 'filter': get_linmod_filter() });
      selectedFilters.push({ 'name': 'sermod', 'context': 'AN', 'type': 0, 'custom': 0, 'filter': get_sermod_filter() });
    } else if (name == 'prezzo') {
      var filter = {
        'min': $("#pric-min").val() > 0 ? $("#pric-min").val() : -1,
        'max': $("#pric-max").val() > 0 ? $("#pric-max").val() : -1,
      };
      selectedFilters.push({ 'name': 'prezzo', 'context': 'LS', 'type': 0, 'custom': 0, 'filter': filter });
    } else if (name == 'tipcla') {
      var filter = get_tipcla_filter(name);
      selectedFilters.push({ 'name': 'tipcla', 'context': 'TC', 'type': 2, 'custom': 0, 'filter': filter });
    } else {
      var context = $(this).data('context');
      var type    = $(this).data('type');
      var custom  = $(this).data('custom');
      var filter  = get_filter(name);
      selectedFilters.push({ name, context, type, custom, filter });
    }
  });

  $.ajax({
    type: "POST",
    url: url,
    dataType: "json",
    data: {
      filters: selectedFilters,
      tag: "{{ tag is defined ? tag : '' }}"
    }
  }).done(function(data) {
    {% if router.getActionName() in ['collection', 'fabric', 'sales', 'selection', 'tag'] %}
    $("#visual-mode").html(data);
    setLazy();
    $("body").addClass("loading-done");
    toggleFilters(false);
    {% elseif router.getActionName() == 'fabricDetail' %}
    if (data == "OK") {
      window.location = "{{ url('catalog/fabricDetail/' ~ fabric.cdpers) }}";
    }
    {% elseif router.getActionName() == 'list' %}
    if (data == "OK") {
      window.location = "{{ url('catalog/list') }}";
    }
    {% else %}
      window.location.reload();
    {% endif %}
  }).error(function(x, t, m) {
		printAjaxError(x, t, m);
    toggleFilters(false);
  });
}
//endregion

//region Structure filter
function get_sermod_filter() {
  var sermod = [];
  $('#flt-structure').find('.flt-cdserm:checked').each(function(){
    var curr_cdlinm = $(this).data('cdlinm');
    var curr_cdserm = $(this).data('cdserm');
    sermod.push([ curr_cdlinm, curr_cdserm  ]);
  });
  return sermod;
}
function get_linmod_filter() {
  var linmod = [];
  $('#flt-structure').find('.flt-cdlinm:checked').each(function(){
    var curr_cdlinm = $(this).data('cdlinm');
    linmod.push(curr_cdlinm);
  });
  return linmod;
}
function get_titlin_filter() {
  var titlin = [];
  $('#flt-structure').find('.flt-cdtitl:checked').each(function(){
    var curr_cdtitl = $(this).data('cdtitl');
    titlin.push(curr_cdtitl);
  });
  return titlin;
}
$('#remove-flt-structure').click(function(){
  $('.flt-cdtitl').each(function(){
    $(this).prop('checked', false);
  });
  $('.flt-cdlinm').each(function(){
    $(this).prop('checked', false);
  });
  $('.flt-cdserm').each(function(){
    $(this).prop('checked', false);
  });
  apply_filters();
});
$('#all-filters-container').on('click', '.flt-cdtitl', function(){
  var checked = $(this).prop('checked');
  $(this).closest('li').find('.flt-cdlinm').each(function(){
    $(this).prop('checked', checked);
    $(this).closest('li').find('.flt-cdserm').each(function(){
      $(this).prop('checked', checked);
    });
  });
  apply_filters();
});
$('#all-filters-container').on('click', '.flt-cdlinm', function(){
  var checked = $(this).prop('checked');
  if (checked) {
    // check brand
    $(this).closest('ul.flt-linmod').parent('li').find('.flt-cdtitl').prop('checked', true);
  } else {
    // uncheck brand if siblings are unchecked
    if ($(this).closest('ul.flt-linmod').parent('li').find('.flt-cdlinm:checked').length == 0)
      $(this).closest('ul.flt-linmod').parent('li').find('.flt-cdtitl').prop('checked', false);
  }

  // check/uncheck series
  $(this).closest('li').find('.flt-cdserm').each(function(){
    $(this).prop('checked', checked);
  });

  apply_filters();
});
$('#all-filters-container').on('click', '.flt-cdserm', function(){
  var checked = $(this).prop('checked');
  if (checked) {
    // check line
    $(this).closest('ul.flt-sermod').parent('li').find('.flt-cdlinm').prop('checked', true);
    // check brand
    $(this).closest('ul.flt-linmod').parent('li').find('.flt-cdtitl').prop('checked', true);
  } else {
    // uncheck line if siblings are unchecked
    if ($(this).closest('ul.flt-sermod').parent('li').find('.flt-cdserm:checked').length == 0)
      $(this).closest('ul.flt-sermod').parent('li').find('.flt-cdlinm').prop('checked', false);

    // uncheck brand if siblings are unchecked
    if ($(this).closest('ul.flt-linmod').parent('li').find('.flt-cdlinm:checked').length == 0)
      $(this).closest('ul.flt-linmod').parent('li').find('.flt-cdtitl').prop('checked', false);
  }

  apply_filters();
});
function hideFilters(input_text, liFlt) {
  var showFilter = false;

  $(liFlt).find('li > div > label').each(function() {
    if ($(input_text).val().trim() == '') {
      showFilter = true;
    } else {
      showFilter = false;
      content = $(this).html();

      if( content.toLowerCase().indexOf($(input_text).val().toLowerCase()) > -1 || $(input_text).val().trim() == ''){
        showFilter = true;
      }
    }

    if (showFilter) {
      $(this).closest('li').find('label').css('color','#606060');
    } else {
      $(this).closest('li').find('label').css('color','#eee');
    }
  });
}
$('#flt-structure-text').on('input', function() {
  hideFilters(this, $("#flt-structure"));
});
//endregion

//region Generic filter
function get_filter(field) {
  var result = [];
  $('#flt-' + field).find('.flt-generic:checked').each(function(){
    var curr_result = $(this).data('code');
    result.push(curr_result);
  });
  return result;
}
function get_tipcla_filter(field) {
  var result = [];
  $('#flt-' + field).find('.flt-generic:checked').each(function(){
    let code1 = $(this).data('code1');
    let code2 = $(this).data('code2');
    result.push({ code1, code2 });
  });
  return result;
}
$('#all-filters-container').on('click', '.flt-generic', function(){
  apply_filters();
});
//endregion

//region Price filter
$('#all-filters-container').on('change', '.flt-price', function(){
  $(this).val(parseFloat($(this).val()).toFixed(2));
  apply_filters();
});
//endregion
</script>
