$(document).ready(function() {

    if($('.icoSelect').length > 0) {
        $.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]);
          
          });
    }

    $('.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 bindIcoSelect(that) {

    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');
    });
}
