$(document).ready(function() {

      icoSelectIconsloaded = false;
      icoSelectIconsloading = false;

    // Pro již vybrané ikony při načtení stránky - aby se zobrazily jako vybrané
    $('.icoSelect input').each(function() {
        $(this).closest('.icoSelect').find('.icoSelect__option[data-ico="'+$(this).val()+'"]').addClass('is-selected');
        $(this).closest('.icoSelect').find('.icoSelect__option--selected').html($(this).closest('.icoSelect').find('.icoSelect__option.is-selected').html());
    });

    $('.icoSelect').each(function() {
        bindIcoSelect($(this));
    });

    $(document).click(function(e) {
        if(!$(e.target).hasClass('icoSelect__select')) {
            $('.icoSelect__options').removeClass('is-open');  
        } 
    });

});

function loadIcoSelectIcons() {
  if($('.icoSelect').length > 0 && !icoSelectIconsloaded && !icoSelectIconsloading) {
    icoSelectIconsloading = true;
    $.get("/images/svg/defs.svg", function(data) {
      var div = document.createElement("div");
      div.className = 'hidden';
      div.innerHTML = new XMLSerializer().serializeToString(data.documentElement);
      document.body.insertBefore(div, document.body.childNodes[0]);
      icoSelectIconsloaded = true;
      icoSelectIconsloading = false;
    });
  }
}

function bindIcoSelect(that) {

  loadIcoSelectIcons();

  that.find('.icoSelect__select').click(function() {
    if(!$(this).find('.icoSelect__options').hasClass('is-open')) {
      $(this).find('.icoSelect__options').addClass('is-open');
    }else {
      $(this).find('.icoSelect__options').removeClass('is-open');
    }
  });

  that.find('.icoSelect__option').click(function() {
    $(this).parent().find('.is-selected').removeClass('is-selected');
    $(this).addClass('is-selected');
    $(this).closest('.icoSelect').find('.icoSelect__option--selected').html($(this).html());
    $(this).closest('.icoSelect').find('input').val($(this).data('ico'));
    $(this).parent().removeClass('is-open');
  });
}
